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
This comment makes sense now, but not when the reader doesn't have the old code as a comparison. I suggest you just drop it.
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { controller().applications().get(application.id()).ifPresent(freshApplication -> { Deployment freshDeployment = freshApplication.deployments().get(deployment.zone()); if (freshDeployment != null) controller().applications().store(freshApplication.with(freshDeployment.withMetrics(appMetrics)), lock); }); } } catch (UncheckedIOException e) { log.warning("Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n" + e); } } } }
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { controller().applications().get(application.id()).ifPresent(freshApplication -> { Deployment freshDeployment = freshApplication.deployments().get(deployment.zone()); if (freshDeployment != null) controller().applications().store(freshApplication.with(freshDeployment.withMetrics(appMetrics)), lock); }); } } catch (UncheckedIOException e) { log.warning("Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n" + e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Imho this code would be cleaner by using 2 instances of if (not present) continue; instead of the nesting and 2 different ways of bailing out.
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { controller().applications().get(application.id()).ifPresent(freshApplication -> { Deployment freshDeployment = freshApplication.deployments().get(deployment.zone()); if (freshDeployment != null) controller().applications().store(freshApplication.with(freshDeployment.withMetrics(appMetrics)), lock); }); } } catch (UncheckedIOException e) { log.warning("Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n" + e); } } } }
controller().applications().get(application.id()).ifPresent(freshApplication -> {
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { controller().applications().get(application.id()).ifPresent(freshApplication -> { Deployment freshDeployment = freshApplication.deployments().get(deployment.zone()); if (freshDeployment != null) controller().applications().store(freshApplication.with(freshDeployment.withMetrics(appMetrics)), lock); }); } } catch (UncheckedIOException e) { log.warning("Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n" + e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
require will throw if it is missing, so I think you want to use get() and check Optional.isPresent
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().require(application.id()); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n", e); } } } }
application = controller().applications().require(application.id());
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Also lose the ":\n". Those are not for you to add :-)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().require(application.id()); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n", e); } } } }
log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n", e);
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Ah, I should have checked that :O
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().require(application.id()); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n", e); } } } }
application = controller().applications().require(application.id());
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Right, I guess the logger does that with the .log(...), then.
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().require(application.id()); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n", e); } } } }
log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval() + ":\n", e);
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
`get` returns an optional. Why not use `isPresent` instead of converting it to a `null`?
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
if (application == null)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Agree.
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
if (application == null)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Because I would have to introduce an additional local variable which would should represent the same as `application`, but with a different name. I think this confuses more than it clarifies; it may increase the risk of using the wrong variable further down; it makes the code less uniform; and it makes for quite a bit more text. I considered it, but didn't like it.
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
if (application == null)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Feel free to explain my error or bad taste.
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
if (application == null)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Not sure I understand. Can't you just use `get()` on the optional in the places you use the application?
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
if (application == null)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
Martin: Because there is an "application" variable already. Jonm: Good point. LGTM
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
if (application == null)
protected void maintain() { for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { log.log(Level.WARNING, "Timed out talking to YAMAS; retrying in " + maintenanceInterval(), e); } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
This includes connection loss, connection reconnect etc. There should be a full resync on connection reconnect since lots of events may have been lost. Why is removeApplications() not handling additions of applications? CHILD_ADDED CHILD_REMOVED CHILD_UPDATED CONNECTION_LOST CONNECTION_RECONNECTED CONNECTION_SUSPENDED INITIALIZED
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; case CHILD_REMOVED: applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; default: removeApplications(); break; } }
default:
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; case CHILD_REMOVED: applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; default: removeApplications(); break; } }
class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener { private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName()); private final Curator curator; private final Path applicationsPath; private final ExecutorService pathChildrenExecutor = Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName())); private final Curator.DirectoryCache directoryCache; private final ReloadHandler reloadHandler; private final TenantName tenant; private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { this.curator = curator; this.applicationsPath = applicationsPath; this.reloadHandler = reloadHandler; this.tenant = tenant; rewriteApplicationIds(); this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor); this.directoryCache.start(); this.directoryCache.addListener(this); } public static TenantApplications create(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { try { return new ZKTenantApplications(curator, applicationsPath, reloadHandler, tenant); } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant) + "Error creating application repo", e); } } private void rewriteApplicationIds() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); for (String appNode : appNodes) { Optional<ApplicationId> appId = parseApplication(appNode); appId.filter(id -> shouldBeRewritten(appNode, id)) .ifPresent(id -> rewriteApplicationId(id, appNode, readSessionId(id, appNode))); } } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application ids on upgrade", e); } } private long readSessionId(ApplicationId appId, String appNode) { String path = applicationsPath.append(appNode).getAbsolute(); try { return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path))); } catch (Exception e) { throw new IllegalArgumentException(Tenants.logPre(appId) + "Unable to read the session id from '" + path + "'", e); } } private boolean shouldBeRewritten(String appNode, ApplicationId appId) { return !appNode.equals(appId.serializedForm()); } private void rewriteApplicationId(ApplicationId appId, String origNode, long sessionId) { String newPath = applicationsPath.append(appId.serializedForm()).getAbsolute(); String oldPath = applicationsPath.append(origNode).getAbsolute(); try (CuratorTransaction transaction = new CuratorTransaction(curator)) { if (curator.framework().checkExists().forPath(newPath) == null) { transaction.add(CuratorOperations.create(newPath, Utf8.toAsciiBytes(sessionId))); } transaction.add(CuratorOperations.delete(oldPath)); transaction.commit(); } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application id from " + origNode + " to " + appId.serializedForm()); } } @Override public List<ApplicationId> listApplications() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); List<ApplicationId> applicationIds = new ArrayList<>(); for (String appNode : appNodes) { parseApplication(appNode).ifPresent(applicationIds::add); } return applicationIds; } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant)+"Unable to list applications", e); } } private Optional<ApplicationId> parseApplication(String appNode) { try { return Optional.of(ApplicationId.fromSerializedForm(appNode)); } catch (IllegalArgumentException e) { log.log(LogLevel.INFO, Tenants.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring."); return Optional.empty(); } } @Override public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) { if (listApplications().contains(applicationId)) { return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } else { return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } } @Override public long getSessionIdForApplication(ApplicationId applicationId) { return readSessionId(applicationId, applicationId.serializedForm()); } @Override public CuratorTransaction deleteApplication(ApplicationId applicationId) { Path path = applicationsPath.append(applicationId.serializedForm()); return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator); } @Override public void close() { directoryCache.close(); pathChildrenExecutor.shutdown(); } @Override private void applicationRemoved(ApplicationId applicationId) { reloadHandler.removeApplication(applicationId); log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application removed: " + applicationId); } private void applicationAdded(ApplicationId applicationId) { log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application added: " + applicationId); } private void removeApplications() { ImmutableSet<ApplicationId> allApplications = ImmutableSet.copyOf(listApplications()); log.log(Level.INFO, "We probably lost events, need to check if applications have been removed, " + " found these active applications: " + allApplications); reloadHandler.removeApplicationsExcept(allApplications); } }
class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener { private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName()); private final Curator curator; private final Path applicationsPath; private final ExecutorService pathChildrenExecutor = Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName())); private final Curator.DirectoryCache directoryCache; private final ReloadHandler reloadHandler; private final TenantName tenant; private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { this.curator = curator; this.applicationsPath = applicationsPath; this.reloadHandler = reloadHandler; this.tenant = tenant; rewriteApplicationIds(); this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor); this.directoryCache.start(); this.directoryCache.addListener(this); } public static TenantApplications create(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { try { return new ZKTenantApplications(curator, applicationsPath, reloadHandler, tenant); } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant) + "Error creating application repo", e); } } private void rewriteApplicationIds() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); for (String appNode : appNodes) { Optional<ApplicationId> appId = parseApplication(appNode); appId.filter(id -> shouldBeRewritten(appNode, id)) .ifPresent(id -> rewriteApplicationId(id, appNode, readSessionId(id, appNode))); } } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application ids on upgrade", e); } } private long readSessionId(ApplicationId appId, String appNode) { String path = applicationsPath.append(appNode).getAbsolute(); try { return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path))); } catch (Exception e) { throw new IllegalArgumentException(Tenants.logPre(appId) + "Unable to read the session id from '" + path + "'", e); } } private boolean shouldBeRewritten(String appNode, ApplicationId appId) { return !appNode.equals(appId.serializedForm()); } private void rewriteApplicationId(ApplicationId appId, String origNode, long sessionId) { String newPath = applicationsPath.append(appId.serializedForm()).getAbsolute(); String oldPath = applicationsPath.append(origNode).getAbsolute(); try (CuratorTransaction transaction = new CuratorTransaction(curator)) { if (curator.framework().checkExists().forPath(newPath) == null) { transaction.add(CuratorOperations.create(newPath, Utf8.toAsciiBytes(sessionId))); } transaction.add(CuratorOperations.delete(oldPath)); transaction.commit(); } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application id from " + origNode + " to " + appId.serializedForm()); } } @Override public List<ApplicationId> listApplications() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); List<ApplicationId> applicationIds = new ArrayList<>(); for (String appNode : appNodes) { parseApplication(appNode).ifPresent(applicationIds::add); } return applicationIds; } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant)+"Unable to list applications", e); } } private Optional<ApplicationId> parseApplication(String appNode) { try { return Optional.of(ApplicationId.fromSerializedForm(appNode)); } catch (IllegalArgumentException e) { log.log(LogLevel.INFO, Tenants.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring."); return Optional.empty(); } } @Override public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) { if (listApplications().contains(applicationId)) { return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } else { return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } } @Override public long getSessionIdForApplication(ApplicationId applicationId) { return readSessionId(applicationId, applicationId.serializedForm()); } @Override public CuratorTransaction deleteApplication(ApplicationId applicationId) { Path path = applicationsPath.append(applicationId.serializedForm()); return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator); } @Override public void close() { directoryCache.close(); pathChildrenExecutor.shutdown(); } @Override private void applicationRemoved(ApplicationId applicationId) { reloadHandler.removeApplication(applicationId); log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application removed: " + applicationId); } private void applicationAdded(ApplicationId applicationId) { log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application added: " + applicationId); } private void removeApplications() { ImmutableSet<ApplicationId> allApplications = ImmutableSet.copyOf(listApplications()); log.log(Level.INFO, "We probably lost events, need to check if applications have been removed, " + " found these active applications: " + allApplications); reloadHandler.removeApplicationsExcept(allApplications); } }
removeApplications() only removes applications because there is nothing that adds an application in this code (CHILD_ADDED calls applicationAdded(), but it only logs, which confused me too). An application is added when a session is activated (see makeActive() in RemoteSession). I agree that we need a full resync on reconnect, that's what I want to do. This PR was only to get more logging, but I wanted info from ApplicationMapper, so I made removeApplications()
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; case CHILD_REMOVED: applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; default: removeApplications(); break; } }
default:
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; case CHILD_REMOVED: applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; default: removeApplications(); break; } }
class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener { private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName()); private final Curator curator; private final Path applicationsPath; private final ExecutorService pathChildrenExecutor = Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName())); private final Curator.DirectoryCache directoryCache; private final ReloadHandler reloadHandler; private final TenantName tenant; private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { this.curator = curator; this.applicationsPath = applicationsPath; this.reloadHandler = reloadHandler; this.tenant = tenant; rewriteApplicationIds(); this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor); this.directoryCache.start(); this.directoryCache.addListener(this); } public static TenantApplications create(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { try { return new ZKTenantApplications(curator, applicationsPath, reloadHandler, tenant); } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant) + "Error creating application repo", e); } } private void rewriteApplicationIds() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); for (String appNode : appNodes) { Optional<ApplicationId> appId = parseApplication(appNode); appId.filter(id -> shouldBeRewritten(appNode, id)) .ifPresent(id -> rewriteApplicationId(id, appNode, readSessionId(id, appNode))); } } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application ids on upgrade", e); } } private long readSessionId(ApplicationId appId, String appNode) { String path = applicationsPath.append(appNode).getAbsolute(); try { return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path))); } catch (Exception e) { throw new IllegalArgumentException(Tenants.logPre(appId) + "Unable to read the session id from '" + path + "'", e); } } private boolean shouldBeRewritten(String appNode, ApplicationId appId) { return !appNode.equals(appId.serializedForm()); } private void rewriteApplicationId(ApplicationId appId, String origNode, long sessionId) { String newPath = applicationsPath.append(appId.serializedForm()).getAbsolute(); String oldPath = applicationsPath.append(origNode).getAbsolute(); try (CuratorTransaction transaction = new CuratorTransaction(curator)) { if (curator.framework().checkExists().forPath(newPath) == null) { transaction.add(CuratorOperations.create(newPath, Utf8.toAsciiBytes(sessionId))); } transaction.add(CuratorOperations.delete(oldPath)); transaction.commit(); } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application id from " + origNode + " to " + appId.serializedForm()); } } @Override public List<ApplicationId> listApplications() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); List<ApplicationId> applicationIds = new ArrayList<>(); for (String appNode : appNodes) { parseApplication(appNode).ifPresent(applicationIds::add); } return applicationIds; } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant)+"Unable to list applications", e); } } private Optional<ApplicationId> parseApplication(String appNode) { try { return Optional.of(ApplicationId.fromSerializedForm(appNode)); } catch (IllegalArgumentException e) { log.log(LogLevel.INFO, Tenants.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring."); return Optional.empty(); } } @Override public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) { if (listApplications().contains(applicationId)) { return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } else { return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } } @Override public long getSessionIdForApplication(ApplicationId applicationId) { return readSessionId(applicationId, applicationId.serializedForm()); } @Override public CuratorTransaction deleteApplication(ApplicationId applicationId) { Path path = applicationsPath.append(applicationId.serializedForm()); return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator); } @Override public void close() { directoryCache.close(); pathChildrenExecutor.shutdown(); } @Override private void applicationRemoved(ApplicationId applicationId) { reloadHandler.removeApplication(applicationId); log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application removed: " + applicationId); } private void applicationAdded(ApplicationId applicationId) { log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application added: " + applicationId); } private void removeApplications() { ImmutableSet<ApplicationId> allApplications = ImmutableSet.copyOf(listApplications()); log.log(Level.INFO, "We probably lost events, need to check if applications have been removed, " + " found these active applications: " + allApplications); reloadHandler.removeApplicationsExcept(allApplications); } }
class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener { private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName()); private final Curator curator; private final Path applicationsPath; private final ExecutorService pathChildrenExecutor = Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName())); private final Curator.DirectoryCache directoryCache; private final ReloadHandler reloadHandler; private final TenantName tenant; private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { this.curator = curator; this.applicationsPath = applicationsPath; this.reloadHandler = reloadHandler; this.tenant = tenant; rewriteApplicationIds(); this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor); this.directoryCache.start(); this.directoryCache.addListener(this); } public static TenantApplications create(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { try { return new ZKTenantApplications(curator, applicationsPath, reloadHandler, tenant); } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant) + "Error creating application repo", e); } } private void rewriteApplicationIds() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); for (String appNode : appNodes) { Optional<ApplicationId> appId = parseApplication(appNode); appId.filter(id -> shouldBeRewritten(appNode, id)) .ifPresent(id -> rewriteApplicationId(id, appNode, readSessionId(id, appNode))); } } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application ids on upgrade", e); } } private long readSessionId(ApplicationId appId, String appNode) { String path = applicationsPath.append(appNode).getAbsolute(); try { return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path))); } catch (Exception e) { throw new IllegalArgumentException(Tenants.logPre(appId) + "Unable to read the session id from '" + path + "'", e); } } private boolean shouldBeRewritten(String appNode, ApplicationId appId) { return !appNode.equals(appId.serializedForm()); } private void rewriteApplicationId(ApplicationId appId, String origNode, long sessionId) { String newPath = applicationsPath.append(appId.serializedForm()).getAbsolute(); String oldPath = applicationsPath.append(origNode).getAbsolute(); try (CuratorTransaction transaction = new CuratorTransaction(curator)) { if (curator.framework().checkExists().forPath(newPath) == null) { transaction.add(CuratorOperations.create(newPath, Utf8.toAsciiBytes(sessionId))); } transaction.add(CuratorOperations.delete(oldPath)); transaction.commit(); } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application id from " + origNode + " to " + appId.serializedForm()); } } @Override public List<ApplicationId> listApplications() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); List<ApplicationId> applicationIds = new ArrayList<>(); for (String appNode : appNodes) { parseApplication(appNode).ifPresent(applicationIds::add); } return applicationIds; } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant)+"Unable to list applications", e); } } private Optional<ApplicationId> parseApplication(String appNode) { try { return Optional.of(ApplicationId.fromSerializedForm(appNode)); } catch (IllegalArgumentException e) { log.log(LogLevel.INFO, Tenants.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring."); return Optional.empty(); } } @Override public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) { if (listApplications().contains(applicationId)) { return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } else { return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } } @Override public long getSessionIdForApplication(ApplicationId applicationId) { return readSessionId(applicationId, applicationId.serializedForm()); } @Override public CuratorTransaction deleteApplication(ApplicationId applicationId) { Path path = applicationsPath.append(applicationId.serializedForm()); return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator); } @Override public void close() { directoryCache.close(); pathChildrenExecutor.shutdown(); } @Override private void applicationRemoved(ApplicationId applicationId) { reloadHandler.removeApplication(applicationId); log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application removed: " + applicationId); } private void applicationAdded(ApplicationId applicationId) { log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application added: " + applicationId); } private void removeApplications() { ImmutableSet<ApplicationId> allApplications = ImmutableSet.copyOf(listApplications()); log.log(Level.INFO, "We probably lost events, need to check if applications have been removed, " + " found these active applications: " + allApplications); reloadHandler.removeApplicationsExcept(allApplications); } }
OK
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; case CHILD_REMOVED: applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; default: removeApplications(); break; } }
default:
public void childEvent(CuratorFramework client, PathChildrenCacheEvent event) throws Exception { switch (event.getType()) { case CHILD_ADDED: applicationAdded(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; case CHILD_REMOVED: applicationRemoved(ApplicationId.fromSerializedForm(Path.fromString(event.getData().getPath()).getName())); break; default: removeApplications(); break; } }
class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener { private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName()); private final Curator curator; private final Path applicationsPath; private final ExecutorService pathChildrenExecutor = Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName())); private final Curator.DirectoryCache directoryCache; private final ReloadHandler reloadHandler; private final TenantName tenant; private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { this.curator = curator; this.applicationsPath = applicationsPath; this.reloadHandler = reloadHandler; this.tenant = tenant; rewriteApplicationIds(); this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor); this.directoryCache.start(); this.directoryCache.addListener(this); } public static TenantApplications create(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { try { return new ZKTenantApplications(curator, applicationsPath, reloadHandler, tenant); } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant) + "Error creating application repo", e); } } private void rewriteApplicationIds() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); for (String appNode : appNodes) { Optional<ApplicationId> appId = parseApplication(appNode); appId.filter(id -> shouldBeRewritten(appNode, id)) .ifPresent(id -> rewriteApplicationId(id, appNode, readSessionId(id, appNode))); } } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application ids on upgrade", e); } } private long readSessionId(ApplicationId appId, String appNode) { String path = applicationsPath.append(appNode).getAbsolute(); try { return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path))); } catch (Exception e) { throw new IllegalArgumentException(Tenants.logPre(appId) + "Unable to read the session id from '" + path + "'", e); } } private boolean shouldBeRewritten(String appNode, ApplicationId appId) { return !appNode.equals(appId.serializedForm()); } private void rewriteApplicationId(ApplicationId appId, String origNode, long sessionId) { String newPath = applicationsPath.append(appId.serializedForm()).getAbsolute(); String oldPath = applicationsPath.append(origNode).getAbsolute(); try (CuratorTransaction transaction = new CuratorTransaction(curator)) { if (curator.framework().checkExists().forPath(newPath) == null) { transaction.add(CuratorOperations.create(newPath, Utf8.toAsciiBytes(sessionId))); } transaction.add(CuratorOperations.delete(oldPath)); transaction.commit(); } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application id from " + origNode + " to " + appId.serializedForm()); } } @Override public List<ApplicationId> listApplications() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); List<ApplicationId> applicationIds = new ArrayList<>(); for (String appNode : appNodes) { parseApplication(appNode).ifPresent(applicationIds::add); } return applicationIds; } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant)+"Unable to list applications", e); } } private Optional<ApplicationId> parseApplication(String appNode) { try { return Optional.of(ApplicationId.fromSerializedForm(appNode)); } catch (IllegalArgumentException e) { log.log(LogLevel.INFO, Tenants.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring."); return Optional.empty(); } } @Override public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) { if (listApplications().contains(applicationId)) { return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } else { return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } } @Override public long getSessionIdForApplication(ApplicationId applicationId) { return readSessionId(applicationId, applicationId.serializedForm()); } @Override public CuratorTransaction deleteApplication(ApplicationId applicationId) { Path path = applicationsPath.append(applicationId.serializedForm()); return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator); } @Override public void close() { directoryCache.close(); pathChildrenExecutor.shutdown(); } @Override private void applicationRemoved(ApplicationId applicationId) { reloadHandler.removeApplication(applicationId); log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application removed: " + applicationId); } private void applicationAdded(ApplicationId applicationId) { log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application added: " + applicationId); } private void removeApplications() { ImmutableSet<ApplicationId> allApplications = ImmutableSet.copyOf(listApplications()); log.log(Level.INFO, "We probably lost events, need to check if applications have been removed, " + " found these active applications: " + allApplications); reloadHandler.removeApplicationsExcept(allApplications); } }
class ZKTenantApplications implements TenantApplications, PathChildrenCacheListener { private static final Logger log = Logger.getLogger(ZKTenantApplications.class.getName()); private final Curator curator; private final Path applicationsPath; private final ExecutorService pathChildrenExecutor = Executors.newFixedThreadPool(1, ThreadFactoryFactory.getThreadFactory(ZKTenantApplications.class.getName())); private final Curator.DirectoryCache directoryCache; private final ReloadHandler reloadHandler; private final TenantName tenant; private ZKTenantApplications(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { this.curator = curator; this.applicationsPath = applicationsPath; this.reloadHandler = reloadHandler; this.tenant = tenant; rewriteApplicationIds(); this.directoryCache = curator.createDirectoryCache(applicationsPath.getAbsolute(), false, false, pathChildrenExecutor); this.directoryCache.start(); this.directoryCache.addListener(this); } public static TenantApplications create(Curator curator, Path applicationsPath, ReloadHandler reloadHandler, TenantName tenant) { try { return new ZKTenantApplications(curator, applicationsPath, reloadHandler, tenant); } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant) + "Error creating application repo", e); } } private void rewriteApplicationIds() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); for (String appNode : appNodes) { Optional<ApplicationId> appId = parseApplication(appNode); appId.filter(id -> shouldBeRewritten(appNode, id)) .ifPresent(id -> rewriteApplicationId(id, appNode, readSessionId(id, appNode))); } } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application ids on upgrade", e); } } private long readSessionId(ApplicationId appId, String appNode) { String path = applicationsPath.append(appNode).getAbsolute(); try { return Long.parseLong(Utf8.toString(curator.framework().getData().forPath(path))); } catch (Exception e) { throw new IllegalArgumentException(Tenants.logPre(appId) + "Unable to read the session id from '" + path + "'", e); } } private boolean shouldBeRewritten(String appNode, ApplicationId appId) { return !appNode.equals(appId.serializedForm()); } private void rewriteApplicationId(ApplicationId appId, String origNode, long sessionId) { String newPath = applicationsPath.append(appId.serializedForm()).getAbsolute(); String oldPath = applicationsPath.append(origNode).getAbsolute(); try (CuratorTransaction transaction = new CuratorTransaction(curator)) { if (curator.framework().checkExists().forPath(newPath) == null) { transaction.add(CuratorOperations.create(newPath, Utf8.toAsciiBytes(sessionId))); } transaction.add(CuratorOperations.delete(oldPath)); transaction.commit(); } catch (Exception e) { log.log(LogLevel.WARNING, "Error rewriting application id from " + origNode + " to " + appId.serializedForm()); } } @Override public List<ApplicationId> listApplications() { try { List<String> appNodes = curator.framework().getChildren().forPath(applicationsPath.getAbsolute()); List<ApplicationId> applicationIds = new ArrayList<>(); for (String appNode : appNodes) { parseApplication(appNode).ifPresent(applicationIds::add); } return applicationIds; } catch (Exception e) { throw new RuntimeException(Tenants.logPre(tenant)+"Unable to list applications", e); } } private Optional<ApplicationId> parseApplication(String appNode) { try { return Optional.of(ApplicationId.fromSerializedForm(appNode)); } catch (IllegalArgumentException e) { log.log(LogLevel.INFO, Tenants.logPre(tenant)+"Unable to parse application with id '" + appNode + "', ignoring."); return Optional.empty(); } } @Override public Transaction createPutApplicationTransaction(ApplicationId applicationId, long sessionId) { if (listApplications().contains(applicationId)) { return new CuratorTransaction(curator).add(CuratorOperations.setData(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } else { return new CuratorTransaction(curator).add(CuratorOperations.create(applicationsPath.append(applicationId.serializedForm()).getAbsolute(), Utf8.toAsciiBytes(sessionId))); } } @Override public long getSessionIdForApplication(ApplicationId applicationId) { return readSessionId(applicationId, applicationId.serializedForm()); } @Override public CuratorTransaction deleteApplication(ApplicationId applicationId) { Path path = applicationsPath.append(applicationId.serializedForm()); return CuratorTransaction.from(CuratorOperations.delete(path.getAbsolute()), curator); } @Override public void close() { directoryCache.close(); pathChildrenExecutor.shutdown(); } @Override private void applicationRemoved(ApplicationId applicationId) { reloadHandler.removeApplication(applicationId); log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application removed: " + applicationId); } private void applicationAdded(ApplicationId applicationId) { log.log(LogLevel.DEBUG, Tenants.logPre(applicationId) + "Application added: " + applicationId); } private void removeApplications() { ImmutableSet<ApplicationId> allApplications = ImmutableSet.copyOf(listApplications()); log.log(Level.INFO, "We probably lost events, need to check if applications have been removed, " + " found these active applications: " + allApplications); reloadHandler.removeApplicationsExcept(allApplications); } }
Can the divergence field really contain the string "null"? If so can we please change `NodeSerializer` to throw away values that are "null" and have `NodePatcher.asOptionalString` filter incoming "null" values? I assume it happens if clients send `{"hardwareDivergence": "null"}` instead of `{"hardwareDivergence": null}` as the latter is handled.
private List<Node> readyNodesWithHardwareDivergence() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareDivergence().isPresent() && !node.status().hardwareDivergence().get().equals("null")) .collect(Collectors.toList()); }
&& !node.status().hardwareDivergence().get().equals("null"))
private List<Node> readyNodesWithHardwareDivergence() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareDivergence().isPresent()) .collect(Collectors.toList()); }
class NodeFailer extends Maintainer { private static final Logger log = Logger.getLogger(NodeFailer.class.getName()); private static final Duration nodeRequestInterval = Duration.ofMinutes(10); /** Provides information about the status of ready hosts */ private final HostLivenessTracker hostLivenessTracker; /** Provides (more accurate) information about the status of active hosts */ private final ServiceMonitor serviceMonitor; private final Deployer deployer; private final Duration downTimeLimit; private final Clock clock; private final Orchestrator orchestrator; private final Instant constructionTime; private final ThrottlePolicy throttlePolicy; public NodeFailer(Deployer deployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, NodeRepository nodeRepository, Duration downTimeLimit, Clock clock, Orchestrator orchestrator, ThrottlePolicy throttlePolicy, JobControl jobControl) { super(nodeRepository, min(downTimeLimit.dividedBy(2), Duration.ofMinutes(5)), jobControl); this.deployer = deployer; this.hostLivenessTracker = hostLivenessTracker; this.serviceMonitor = serviceMonitor; this.downTimeLimit = downTimeLimit; this.clock = clock; this.orchestrator = orchestrator; this.constructionTime = clock.instant(); this.throttlePolicy = throttlePolicy; } @Override protected void maintain() { updateNodeLivenessEventsForReadyNodes(); for (Node node : readyNodesWhichAreDead()) { if (node.flavor().getType() == Flavor.Type.DOCKER_CONTAINER || node.type() == NodeType.host) continue; if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Not receiving config requests from node"); } for (Node node : readyNodesWithHardwareFailure()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node has hardware failure"); for (Node node: readyNodesWithHardwareDivergence()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node hardware diverges from spec"); for (Node node : determineActiveNodeDownStatus()) { Instant graceTimeEnd = node.history().event(History.Event.Type.down).get().at().plus(downTimeLimit); if (graceTimeEnd.isBefore(clock.instant()) && ! applicationSuspended(node) && failAllowedFor(node.type())) if (!throttle(node)) failActive(node, "Node has been down longer than " + downTimeLimit); } } private void updateNodeLivenessEventsForReadyNodes() { try (Mutex lock = nodeRepository().lockUnallocated()) { for (Node node : nodeRepository().getNodes(Node.State.ready)) { Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname()); if ( ! lastLocalRequest.isPresent()) continue; Optional<History.Event> recordedRequest = node.history().event(History.Event.Type.requested); if ( ! recordedRequest.isPresent() || recordedRequest.get().at().isBefore(lastLocalRequest.get())) { History updatedHistory = node.history().with(new History.Event(History.Event.Type.requested, Agent.system, lastLocalRequest.get())); nodeRepository().write(node.with(updatedHistory)); } } } } private List<Node> readyNodesWhichAreDead() { if (constructionTime.isAfter(clock.instant().minus(nodeRequestInterval).minus(nodeRequestInterval) )) return Collections.emptyList(); Instant oldestAcceptableRequestTime = clock.instant().minus(downTimeLimit).minus(nodeRequestInterval); return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> wasMadeReadyBefore(oldestAcceptableRequestTime, node)) .filter(node -> ! hasRecordedRequestAfter(oldestAcceptableRequestTime, node)) .collect(Collectors.toList()); } private boolean wasMadeReadyBefore(Instant instant, Node node) { Optional<History.Event> readiedEvent = node.history().event(History.Event.Type.readied); if ( ! readiedEvent.isPresent()) return false; return readiedEvent.get().at().isBefore(instant); } private boolean hasRecordedRequestAfter(Instant instant, Node node) { Optional<History.Event> lastRequest = node.history().event(History.Event.Type.requested); if ( ! lastRequest.isPresent()) return false; return lastRequest.get().at().isAfter(instant); } private List<Node> readyNodesWithHardwareFailure() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareFailureDescription().isPresent()) .collect(Collectors.toList()); } private boolean applicationSuspended(Node node) { try { return orchestrator.getApplicationInstanceStatus(node.allocation().get().owner()) == ApplicationInstanceStatus.ALLOWED_TO_BE_DOWN; } catch (ApplicationIdNotFoundException e) { return false; } } /** * We can attempt to fail any number of *tenant* and *host* nodes because the operation will not be effected * unless the node is replaced. * However, nodes of other types are not replaced (because all of the type are used by a single application), * so we only allow one to be in failed at any point in time to protect against runaway failing. */ private boolean failAllowedFor(NodeType nodeType) { if (nodeType == NodeType.tenant || nodeType == NodeType.host) return true; return nodeRepository().getNodes(nodeType, Node.State.failed).size() == 0; } /** * If the node is positively DOWN, and there is no "down" history record, we add it. * If the node is positively UP we remove any "down" history record. * * @return a list of all nodes which are positively currently in the down state */ private List<Node> determineActiveNodeDownStatus() { List<Node> downNodes = new ArrayList<>(); for (ApplicationInstance<ServiceMonitorStatus> application : serviceMonitor.queryStatusOfAllApplicationInstances().values()) { for (ServiceCluster<ServiceMonitorStatus> cluster : application.serviceClusters()) { for (ServiceInstance<ServiceMonitorStatus> service : cluster.serviceInstances()) { Optional<Node> node = nodeRepository().getNode(service.hostName().s(), Node.State.active); if ( ! node.isPresent()) continue; if (service.serviceStatus().equals(ServiceMonitorStatus.DOWN)) downNodes.add(recordAsDown(node.get())); else if (service.serviceStatus().equals(ServiceMonitorStatus.UP)) clearDownRecord(node.get()); } } } return downNodes; } /** * Record a node as down if not already recorded and returns the node in the new state. * This assumes the node is found in the node * repo and that the node is allocated. If we get here otherwise something is truly odd. */ private Node recordAsDown(Node node) { if (node.history().event(History.Event.Type.down).isPresent()) return node; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); return nodeRepository().write(node.downAt(clock.instant())); } } private void clearDownRecord(Node node) { if ( ! node.history().event(History.Event.Type.down).isPresent()) return; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); nodeRepository().write(node.up()); } } /** * Called when a node should be moved to the failed state: Do that if it seems safe, * which is when the node repo has available capacity to replace the node (and all its tenant nodes if host). * Otherwise not replacing the node ensures (by Orchestrator check) that no further action will be taken. * * @return whether node was successfully failed */ private boolean failActive(Node node, String reason) { Optional<Deployment> deployment = deployer.deployFromLocalActive(node.allocation().get().owner(), Duration.ofMinutes(30)); if ( ! deployment.isPresent()) return false; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { boolean allTenantNodesFailedOutSuccessfully = true; for (Node failingTenantNode : nodeRepository().getChildNodes(node.hostname())) { if (failingTenantNode.state() == Node.State.active) { allTenantNodesFailedOutSuccessfully &= failActive(failingTenantNode, reason); } else { nodeRepository().fail(failingTenantNode.hostname(), Agent.system, reason); } } if (! allTenantNodesFailedOutSuccessfully) return false; node = nodeRepository().fail(node.hostname(), Agent.system, reason); try { deployment.get().activate(); return true; } catch (RuntimeException e) { nodeRepository().reactivate(node.hostname(), Agent.system); log.log(Level.WARNING, "Attempted to fail " + node + " for " + node.allocation().get().owner() + ", but redeploying without the node failed", e); return false; } } } /** Returns true if node failing should be throttled */ private boolean throttle(Node node) { if (throttlePolicy == ThrottlePolicy.disabled) return false; Instant startOfThrottleWindow = clock.instant().minus(throttlePolicy.throttleWindow); List<Node> nodes = nodeRepository().getNodes().stream() .filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) .collect(Collectors.toList()); long recentlyFailedNodes = nodes.stream() .map(n -> n.history().event(History.Event.Type.failed)) .filter(Optional::isPresent) .map(Optional::get) .filter(failedEvent -> failedEvent.at().isAfter(startOfThrottleWindow)) .count(); boolean throttle = recentlyFailedNodes >= Math.max(nodes.size() * throttlePolicy.fractionAllowedToFail, throttlePolicy.minimumAllowedToFail); if (throttle) { log.info(String.format("Want to fail node %s, but throttling is in effect: %s", node.hostname(), throttlePolicy.toHumanReadableString())); } return throttle; } public enum ThrottlePolicy { hosted(Duration.ofDays(1), 0.01, 2), disabled(Duration.ZERO, 0, 0); public final Duration throttleWindow; public final double fractionAllowedToFail; public final int minimumAllowedToFail; ThrottlePolicy(Duration throttleWindow, double fractionAllowedToFail, int minimumAllowedToFail) { this.throttleWindow = throttleWindow; this.fractionAllowedToFail = fractionAllowedToFail; this.minimumAllowedToFail = minimumAllowedToFail; } public String toHumanReadableString() { return String.format("Max %.0f%% or %d nodes can fail over a period of %s", fractionAllowedToFail*100, minimumAllowedToFail, throttleWindow); } } }
class NodeFailer extends Maintainer { private static final Logger log = Logger.getLogger(NodeFailer.class.getName()); private static final Duration nodeRequestInterval = Duration.ofMinutes(10); /** Provides information about the status of ready hosts */ private final HostLivenessTracker hostLivenessTracker; /** Provides (more accurate) information about the status of active hosts */ private final ServiceMonitor serviceMonitor; private final Deployer deployer; private final Duration downTimeLimit; private final Clock clock; private final Orchestrator orchestrator; private final Instant constructionTime; private final ThrottlePolicy throttlePolicy; public NodeFailer(Deployer deployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, NodeRepository nodeRepository, Duration downTimeLimit, Clock clock, Orchestrator orchestrator, ThrottlePolicy throttlePolicy, JobControl jobControl) { super(nodeRepository, min(downTimeLimit.dividedBy(2), Duration.ofMinutes(5)), jobControl); this.deployer = deployer; this.hostLivenessTracker = hostLivenessTracker; this.serviceMonitor = serviceMonitor; this.downTimeLimit = downTimeLimit; this.clock = clock; this.orchestrator = orchestrator; this.constructionTime = clock.instant(); this.throttlePolicy = throttlePolicy; } @Override protected void maintain() { updateNodeLivenessEventsForReadyNodes(); for (Node node : readyNodesWhichAreDead()) { if (node.flavor().getType() == Flavor.Type.DOCKER_CONTAINER || node.type() == NodeType.host) continue; if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Not receiving config requests from node"); } for (Node node : readyNodesWithHardwareFailure()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node has hardware failure"); for (Node node: readyNodesWithHardwareDivergence()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node hardware diverges from spec"); for (Node node : determineActiveNodeDownStatus()) { Instant graceTimeEnd = node.history().event(History.Event.Type.down).get().at().plus(downTimeLimit); if (graceTimeEnd.isBefore(clock.instant()) && ! applicationSuspended(node) && failAllowedFor(node.type())) if (!throttle(node)) failActive(node, "Node has been down longer than " + downTimeLimit); } } private void updateNodeLivenessEventsForReadyNodes() { try (Mutex lock = nodeRepository().lockUnallocated()) { for (Node node : nodeRepository().getNodes(Node.State.ready)) { Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname()); if ( ! lastLocalRequest.isPresent()) continue; Optional<History.Event> recordedRequest = node.history().event(History.Event.Type.requested); if ( ! recordedRequest.isPresent() || recordedRequest.get().at().isBefore(lastLocalRequest.get())) { History updatedHistory = node.history().with(new History.Event(History.Event.Type.requested, Agent.system, lastLocalRequest.get())); nodeRepository().write(node.with(updatedHistory)); } } } } private List<Node> readyNodesWhichAreDead() { if (constructionTime.isAfter(clock.instant().minus(nodeRequestInterval).minus(nodeRequestInterval) )) return Collections.emptyList(); Instant oldestAcceptableRequestTime = clock.instant().minus(downTimeLimit).minus(nodeRequestInterval); return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> wasMadeReadyBefore(oldestAcceptableRequestTime, node)) .filter(node -> ! hasRecordedRequestAfter(oldestAcceptableRequestTime, node)) .collect(Collectors.toList()); } private boolean wasMadeReadyBefore(Instant instant, Node node) { Optional<History.Event> readiedEvent = node.history().event(History.Event.Type.readied); if ( ! readiedEvent.isPresent()) return false; return readiedEvent.get().at().isBefore(instant); } private boolean hasRecordedRequestAfter(Instant instant, Node node) { Optional<History.Event> lastRequest = node.history().event(History.Event.Type.requested); if ( ! lastRequest.isPresent()) return false; return lastRequest.get().at().isAfter(instant); } private List<Node> readyNodesWithHardwareFailure() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareFailureDescription().isPresent()) .collect(Collectors.toList()); } private boolean applicationSuspended(Node node) { try { return orchestrator.getApplicationInstanceStatus(node.allocation().get().owner()) == ApplicationInstanceStatus.ALLOWED_TO_BE_DOWN; } catch (ApplicationIdNotFoundException e) { return false; } } /** * We can attempt to fail any number of *tenant* and *host* nodes because the operation will not be effected * unless the node is replaced. * However, nodes of other types are not replaced (because all of the type are used by a single application), * so we only allow one to be in failed at any point in time to protect against runaway failing. */ private boolean failAllowedFor(NodeType nodeType) { if (nodeType == NodeType.tenant || nodeType == NodeType.host) return true; return nodeRepository().getNodes(nodeType, Node.State.failed).size() == 0; } /** * If the node is positively DOWN, and there is no "down" history record, we add it. * If the node is positively UP we remove any "down" history record. * * @return a list of all nodes which are positively currently in the down state */ private List<Node> determineActiveNodeDownStatus() { List<Node> downNodes = new ArrayList<>(); for (ApplicationInstance<ServiceMonitorStatus> application : serviceMonitor.queryStatusOfAllApplicationInstances().values()) { for (ServiceCluster<ServiceMonitorStatus> cluster : application.serviceClusters()) { for (ServiceInstance<ServiceMonitorStatus> service : cluster.serviceInstances()) { Optional<Node> node = nodeRepository().getNode(service.hostName().s(), Node.State.active); if ( ! node.isPresent()) continue; if (service.serviceStatus().equals(ServiceMonitorStatus.DOWN)) downNodes.add(recordAsDown(node.get())); else if (service.serviceStatus().equals(ServiceMonitorStatus.UP)) clearDownRecord(node.get()); } } } return downNodes; } /** * Record a node as down if not already recorded and returns the node in the new state. * This assumes the node is found in the node * repo and that the node is allocated. If we get here otherwise something is truly odd. */ private Node recordAsDown(Node node) { if (node.history().event(History.Event.Type.down).isPresent()) return node; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); return nodeRepository().write(node.downAt(clock.instant())); } } private void clearDownRecord(Node node) { if ( ! node.history().event(History.Event.Type.down).isPresent()) return; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); nodeRepository().write(node.up()); } } /** * Called when a node should be moved to the failed state: Do that if it seems safe, * which is when the node repo has available capacity to replace the node (and all its tenant nodes if host). * Otherwise not replacing the node ensures (by Orchestrator check) that no further action will be taken. * * @return whether node was successfully failed */ private boolean failActive(Node node, String reason) { Optional<Deployment> deployment = deployer.deployFromLocalActive(node.allocation().get().owner(), Duration.ofMinutes(30)); if ( ! deployment.isPresent()) return false; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { boolean allTenantNodesFailedOutSuccessfully = true; for (Node failingTenantNode : nodeRepository().getChildNodes(node.hostname())) { if (failingTenantNode.state() == Node.State.active) { allTenantNodesFailedOutSuccessfully &= failActive(failingTenantNode, reason); } else { nodeRepository().fail(failingTenantNode.hostname(), Agent.system, reason); } } if (! allTenantNodesFailedOutSuccessfully) return false; node = nodeRepository().fail(node.hostname(), Agent.system, reason); try { deployment.get().activate(); return true; } catch (RuntimeException e) { nodeRepository().reactivate(node.hostname(), Agent.system); log.log(Level.WARNING, "Attempted to fail " + node + " for " + node.allocation().get().owner() + ", but redeploying without the node failed", e); return false; } } } /** Returns true if node failing should be throttled */ private boolean throttle(Node node) { if (throttlePolicy == ThrottlePolicy.disabled) return false; Instant startOfThrottleWindow = clock.instant().minus(throttlePolicy.throttleWindow); List<Node> nodes = nodeRepository().getNodes().stream() .filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) .collect(Collectors.toList()); long recentlyFailedNodes = nodes.stream() .map(n -> n.history().event(History.Event.Type.failed)) .filter(Optional::isPresent) .map(Optional::get) .filter(failedEvent -> failedEvent.at().isAfter(startOfThrottleWindow)) .count(); boolean throttle = recentlyFailedNodes >= Math.max(nodes.size() * throttlePolicy.fractionAllowedToFail, throttlePolicy.minimumAllowedToFail); if (throttle) { log.info(String.format("Want to fail node %s, but throttling is in effect: %s", node.hostname(), throttlePolicy.toHumanReadableString())); } return throttle; } public enum ThrottlePolicy { hosted(Duration.ofDays(1), 0.01, 2), disabled(Duration.ZERO, 0, 0); public final Duration throttleWindow; public final double fractionAllowedToFail; public final int minimumAllowedToFail; ThrottlePolicy(Duration throttleWindow, double fractionAllowedToFail, int minimumAllowedToFail) { this.throttleWindow = throttleWindow; this.fractionAllowedToFail = fractionAllowedToFail; this.minimumAllowedToFail = minimumAllowedToFail; } public String toHumanReadableString() { return String.format("Max %.0f%% or %d nodes can fail over a period of %s", fractionAllowedToFail*100, minimumAllowedToFail, throttleWindow); } } }
Yes, most nodes today have it set to "null". I guess we should fix the client (SpecVerifier) too.
private List<Node> readyNodesWithHardwareDivergence() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareDivergence().isPresent() && !node.status().hardwareDivergence().get().equals("null")) .collect(Collectors.toList()); }
&& !node.status().hardwareDivergence().get().equals("null"))
private List<Node> readyNodesWithHardwareDivergence() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareDivergence().isPresent()) .collect(Collectors.toList()); }
class NodeFailer extends Maintainer { private static final Logger log = Logger.getLogger(NodeFailer.class.getName()); private static final Duration nodeRequestInterval = Duration.ofMinutes(10); /** Provides information about the status of ready hosts */ private final HostLivenessTracker hostLivenessTracker; /** Provides (more accurate) information about the status of active hosts */ private final ServiceMonitor serviceMonitor; private final Deployer deployer; private final Duration downTimeLimit; private final Clock clock; private final Orchestrator orchestrator; private final Instant constructionTime; private final ThrottlePolicy throttlePolicy; public NodeFailer(Deployer deployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, NodeRepository nodeRepository, Duration downTimeLimit, Clock clock, Orchestrator orchestrator, ThrottlePolicy throttlePolicy, JobControl jobControl) { super(nodeRepository, min(downTimeLimit.dividedBy(2), Duration.ofMinutes(5)), jobControl); this.deployer = deployer; this.hostLivenessTracker = hostLivenessTracker; this.serviceMonitor = serviceMonitor; this.downTimeLimit = downTimeLimit; this.clock = clock; this.orchestrator = orchestrator; this.constructionTime = clock.instant(); this.throttlePolicy = throttlePolicy; } @Override protected void maintain() { updateNodeLivenessEventsForReadyNodes(); for (Node node : readyNodesWhichAreDead()) { if (node.flavor().getType() == Flavor.Type.DOCKER_CONTAINER || node.type() == NodeType.host) continue; if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Not receiving config requests from node"); } for (Node node : readyNodesWithHardwareFailure()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node has hardware failure"); for (Node node: readyNodesWithHardwareDivergence()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node hardware diverges from spec"); for (Node node : determineActiveNodeDownStatus()) { Instant graceTimeEnd = node.history().event(History.Event.Type.down).get().at().plus(downTimeLimit); if (graceTimeEnd.isBefore(clock.instant()) && ! applicationSuspended(node) && failAllowedFor(node.type())) if (!throttle(node)) failActive(node, "Node has been down longer than " + downTimeLimit); } } private void updateNodeLivenessEventsForReadyNodes() { try (Mutex lock = nodeRepository().lockUnallocated()) { for (Node node : nodeRepository().getNodes(Node.State.ready)) { Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname()); if ( ! lastLocalRequest.isPresent()) continue; Optional<History.Event> recordedRequest = node.history().event(History.Event.Type.requested); if ( ! recordedRequest.isPresent() || recordedRequest.get().at().isBefore(lastLocalRequest.get())) { History updatedHistory = node.history().with(new History.Event(History.Event.Type.requested, Agent.system, lastLocalRequest.get())); nodeRepository().write(node.with(updatedHistory)); } } } } private List<Node> readyNodesWhichAreDead() { if (constructionTime.isAfter(clock.instant().minus(nodeRequestInterval).minus(nodeRequestInterval) )) return Collections.emptyList(); Instant oldestAcceptableRequestTime = clock.instant().minus(downTimeLimit).minus(nodeRequestInterval); return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> wasMadeReadyBefore(oldestAcceptableRequestTime, node)) .filter(node -> ! hasRecordedRequestAfter(oldestAcceptableRequestTime, node)) .collect(Collectors.toList()); } private boolean wasMadeReadyBefore(Instant instant, Node node) { Optional<History.Event> readiedEvent = node.history().event(History.Event.Type.readied); if ( ! readiedEvent.isPresent()) return false; return readiedEvent.get().at().isBefore(instant); } private boolean hasRecordedRequestAfter(Instant instant, Node node) { Optional<History.Event> lastRequest = node.history().event(History.Event.Type.requested); if ( ! lastRequest.isPresent()) return false; return lastRequest.get().at().isAfter(instant); } private List<Node> readyNodesWithHardwareFailure() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareFailureDescription().isPresent()) .collect(Collectors.toList()); } private boolean applicationSuspended(Node node) { try { return orchestrator.getApplicationInstanceStatus(node.allocation().get().owner()) == ApplicationInstanceStatus.ALLOWED_TO_BE_DOWN; } catch (ApplicationIdNotFoundException e) { return false; } } /** * We can attempt to fail any number of *tenant* and *host* nodes because the operation will not be effected * unless the node is replaced. * However, nodes of other types are not replaced (because all of the type are used by a single application), * so we only allow one to be in failed at any point in time to protect against runaway failing. */ private boolean failAllowedFor(NodeType nodeType) { if (nodeType == NodeType.tenant || nodeType == NodeType.host) return true; return nodeRepository().getNodes(nodeType, Node.State.failed).size() == 0; } /** * If the node is positively DOWN, and there is no "down" history record, we add it. * If the node is positively UP we remove any "down" history record. * * @return a list of all nodes which are positively currently in the down state */ private List<Node> determineActiveNodeDownStatus() { List<Node> downNodes = new ArrayList<>(); for (ApplicationInstance<ServiceMonitorStatus> application : serviceMonitor.queryStatusOfAllApplicationInstances().values()) { for (ServiceCluster<ServiceMonitorStatus> cluster : application.serviceClusters()) { for (ServiceInstance<ServiceMonitorStatus> service : cluster.serviceInstances()) { Optional<Node> node = nodeRepository().getNode(service.hostName().s(), Node.State.active); if ( ! node.isPresent()) continue; if (service.serviceStatus().equals(ServiceMonitorStatus.DOWN)) downNodes.add(recordAsDown(node.get())); else if (service.serviceStatus().equals(ServiceMonitorStatus.UP)) clearDownRecord(node.get()); } } } return downNodes; } /** * Record a node as down if not already recorded and returns the node in the new state. * This assumes the node is found in the node * repo and that the node is allocated. If we get here otherwise something is truly odd. */ private Node recordAsDown(Node node) { if (node.history().event(History.Event.Type.down).isPresent()) return node; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); return nodeRepository().write(node.downAt(clock.instant())); } } private void clearDownRecord(Node node) { if ( ! node.history().event(History.Event.Type.down).isPresent()) return; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); nodeRepository().write(node.up()); } } /** * Called when a node should be moved to the failed state: Do that if it seems safe, * which is when the node repo has available capacity to replace the node (and all its tenant nodes if host). * Otherwise not replacing the node ensures (by Orchestrator check) that no further action will be taken. * * @return whether node was successfully failed */ private boolean failActive(Node node, String reason) { Optional<Deployment> deployment = deployer.deployFromLocalActive(node.allocation().get().owner(), Duration.ofMinutes(30)); if ( ! deployment.isPresent()) return false; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { boolean allTenantNodesFailedOutSuccessfully = true; for (Node failingTenantNode : nodeRepository().getChildNodes(node.hostname())) { if (failingTenantNode.state() == Node.State.active) { allTenantNodesFailedOutSuccessfully &= failActive(failingTenantNode, reason); } else { nodeRepository().fail(failingTenantNode.hostname(), Agent.system, reason); } } if (! allTenantNodesFailedOutSuccessfully) return false; node = nodeRepository().fail(node.hostname(), Agent.system, reason); try { deployment.get().activate(); return true; } catch (RuntimeException e) { nodeRepository().reactivate(node.hostname(), Agent.system); log.log(Level.WARNING, "Attempted to fail " + node + " for " + node.allocation().get().owner() + ", but redeploying without the node failed", e); return false; } } } /** Returns true if node failing should be throttled */ private boolean throttle(Node node) { if (throttlePolicy == ThrottlePolicy.disabled) return false; Instant startOfThrottleWindow = clock.instant().minus(throttlePolicy.throttleWindow); List<Node> nodes = nodeRepository().getNodes().stream() .filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) .collect(Collectors.toList()); long recentlyFailedNodes = nodes.stream() .map(n -> n.history().event(History.Event.Type.failed)) .filter(Optional::isPresent) .map(Optional::get) .filter(failedEvent -> failedEvent.at().isAfter(startOfThrottleWindow)) .count(); boolean throttle = recentlyFailedNodes >= Math.max(nodes.size() * throttlePolicy.fractionAllowedToFail, throttlePolicy.minimumAllowedToFail); if (throttle) { log.info(String.format("Want to fail node %s, but throttling is in effect: %s", node.hostname(), throttlePolicy.toHumanReadableString())); } return throttle; } public enum ThrottlePolicy { hosted(Duration.ofDays(1), 0.01, 2), disabled(Duration.ZERO, 0, 0); public final Duration throttleWindow; public final double fractionAllowedToFail; public final int minimumAllowedToFail; ThrottlePolicy(Duration throttleWindow, double fractionAllowedToFail, int minimumAllowedToFail) { this.throttleWindow = throttleWindow; this.fractionAllowedToFail = fractionAllowedToFail; this.minimumAllowedToFail = minimumAllowedToFail; } public String toHumanReadableString() { return String.format("Max %.0f%% or %d nodes can fail over a period of %s", fractionAllowedToFail*100, minimumAllowedToFail, throttleWindow); } } }
class NodeFailer extends Maintainer { private static final Logger log = Logger.getLogger(NodeFailer.class.getName()); private static final Duration nodeRequestInterval = Duration.ofMinutes(10); /** Provides information about the status of ready hosts */ private final HostLivenessTracker hostLivenessTracker; /** Provides (more accurate) information about the status of active hosts */ private final ServiceMonitor serviceMonitor; private final Deployer deployer; private final Duration downTimeLimit; private final Clock clock; private final Orchestrator orchestrator; private final Instant constructionTime; private final ThrottlePolicy throttlePolicy; public NodeFailer(Deployer deployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, NodeRepository nodeRepository, Duration downTimeLimit, Clock clock, Orchestrator orchestrator, ThrottlePolicy throttlePolicy, JobControl jobControl) { super(nodeRepository, min(downTimeLimit.dividedBy(2), Duration.ofMinutes(5)), jobControl); this.deployer = deployer; this.hostLivenessTracker = hostLivenessTracker; this.serviceMonitor = serviceMonitor; this.downTimeLimit = downTimeLimit; this.clock = clock; this.orchestrator = orchestrator; this.constructionTime = clock.instant(); this.throttlePolicy = throttlePolicy; } @Override protected void maintain() { updateNodeLivenessEventsForReadyNodes(); for (Node node : readyNodesWhichAreDead()) { if (node.flavor().getType() == Flavor.Type.DOCKER_CONTAINER || node.type() == NodeType.host) continue; if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Not receiving config requests from node"); } for (Node node : readyNodesWithHardwareFailure()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node has hardware failure"); for (Node node: readyNodesWithHardwareDivergence()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node hardware diverges from spec"); for (Node node : determineActiveNodeDownStatus()) { Instant graceTimeEnd = node.history().event(History.Event.Type.down).get().at().plus(downTimeLimit); if (graceTimeEnd.isBefore(clock.instant()) && ! applicationSuspended(node) && failAllowedFor(node.type())) if (!throttle(node)) failActive(node, "Node has been down longer than " + downTimeLimit); } } private void updateNodeLivenessEventsForReadyNodes() { try (Mutex lock = nodeRepository().lockUnallocated()) { for (Node node : nodeRepository().getNodes(Node.State.ready)) { Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname()); if ( ! lastLocalRequest.isPresent()) continue; Optional<History.Event> recordedRequest = node.history().event(History.Event.Type.requested); if ( ! recordedRequest.isPresent() || recordedRequest.get().at().isBefore(lastLocalRequest.get())) { History updatedHistory = node.history().with(new History.Event(History.Event.Type.requested, Agent.system, lastLocalRequest.get())); nodeRepository().write(node.with(updatedHistory)); } } } } private List<Node> readyNodesWhichAreDead() { if (constructionTime.isAfter(clock.instant().minus(nodeRequestInterval).minus(nodeRequestInterval) )) return Collections.emptyList(); Instant oldestAcceptableRequestTime = clock.instant().minus(downTimeLimit).minus(nodeRequestInterval); return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> wasMadeReadyBefore(oldestAcceptableRequestTime, node)) .filter(node -> ! hasRecordedRequestAfter(oldestAcceptableRequestTime, node)) .collect(Collectors.toList()); } private boolean wasMadeReadyBefore(Instant instant, Node node) { Optional<History.Event> readiedEvent = node.history().event(History.Event.Type.readied); if ( ! readiedEvent.isPresent()) return false; return readiedEvent.get().at().isBefore(instant); } private boolean hasRecordedRequestAfter(Instant instant, Node node) { Optional<History.Event> lastRequest = node.history().event(History.Event.Type.requested); if ( ! lastRequest.isPresent()) return false; return lastRequest.get().at().isAfter(instant); } private List<Node> readyNodesWithHardwareFailure() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareFailureDescription().isPresent()) .collect(Collectors.toList()); } private boolean applicationSuspended(Node node) { try { return orchestrator.getApplicationInstanceStatus(node.allocation().get().owner()) == ApplicationInstanceStatus.ALLOWED_TO_BE_DOWN; } catch (ApplicationIdNotFoundException e) { return false; } } /** * We can attempt to fail any number of *tenant* and *host* nodes because the operation will not be effected * unless the node is replaced. * However, nodes of other types are not replaced (because all of the type are used by a single application), * so we only allow one to be in failed at any point in time to protect against runaway failing. */ private boolean failAllowedFor(NodeType nodeType) { if (nodeType == NodeType.tenant || nodeType == NodeType.host) return true; return nodeRepository().getNodes(nodeType, Node.State.failed).size() == 0; } /** * If the node is positively DOWN, and there is no "down" history record, we add it. * If the node is positively UP we remove any "down" history record. * * @return a list of all nodes which are positively currently in the down state */ private List<Node> determineActiveNodeDownStatus() { List<Node> downNodes = new ArrayList<>(); for (ApplicationInstance<ServiceMonitorStatus> application : serviceMonitor.queryStatusOfAllApplicationInstances().values()) { for (ServiceCluster<ServiceMonitorStatus> cluster : application.serviceClusters()) { for (ServiceInstance<ServiceMonitorStatus> service : cluster.serviceInstances()) { Optional<Node> node = nodeRepository().getNode(service.hostName().s(), Node.State.active); if ( ! node.isPresent()) continue; if (service.serviceStatus().equals(ServiceMonitorStatus.DOWN)) downNodes.add(recordAsDown(node.get())); else if (service.serviceStatus().equals(ServiceMonitorStatus.UP)) clearDownRecord(node.get()); } } } return downNodes; } /** * Record a node as down if not already recorded and returns the node in the new state. * This assumes the node is found in the node * repo and that the node is allocated. If we get here otherwise something is truly odd. */ private Node recordAsDown(Node node) { if (node.history().event(History.Event.Type.down).isPresent()) return node; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); return nodeRepository().write(node.downAt(clock.instant())); } } private void clearDownRecord(Node node) { if ( ! node.history().event(History.Event.Type.down).isPresent()) return; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); nodeRepository().write(node.up()); } } /** * Called when a node should be moved to the failed state: Do that if it seems safe, * which is when the node repo has available capacity to replace the node (and all its tenant nodes if host). * Otherwise not replacing the node ensures (by Orchestrator check) that no further action will be taken. * * @return whether node was successfully failed */ private boolean failActive(Node node, String reason) { Optional<Deployment> deployment = deployer.deployFromLocalActive(node.allocation().get().owner(), Duration.ofMinutes(30)); if ( ! deployment.isPresent()) return false; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { boolean allTenantNodesFailedOutSuccessfully = true; for (Node failingTenantNode : nodeRepository().getChildNodes(node.hostname())) { if (failingTenantNode.state() == Node.State.active) { allTenantNodesFailedOutSuccessfully &= failActive(failingTenantNode, reason); } else { nodeRepository().fail(failingTenantNode.hostname(), Agent.system, reason); } } if (! allTenantNodesFailedOutSuccessfully) return false; node = nodeRepository().fail(node.hostname(), Agent.system, reason); try { deployment.get().activate(); return true; } catch (RuntimeException e) { nodeRepository().reactivate(node.hostname(), Agent.system); log.log(Level.WARNING, "Attempted to fail " + node + " for " + node.allocation().get().owner() + ", but redeploying without the node failed", e); return false; } } } /** Returns true if node failing should be throttled */ private boolean throttle(Node node) { if (throttlePolicy == ThrottlePolicy.disabled) return false; Instant startOfThrottleWindow = clock.instant().minus(throttlePolicy.throttleWindow); List<Node> nodes = nodeRepository().getNodes().stream() .filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) .collect(Collectors.toList()); long recentlyFailedNodes = nodes.stream() .map(n -> n.history().event(History.Event.Type.failed)) .filter(Optional::isPresent) .map(Optional::get) .filter(failedEvent -> failedEvent.at().isAfter(startOfThrottleWindow)) .count(); boolean throttle = recentlyFailedNodes >= Math.max(nodes.size() * throttlePolicy.fractionAllowedToFail, throttlePolicy.minimumAllowedToFail); if (throttle) { log.info(String.format("Want to fail node %s, but throttling is in effect: %s", node.hostname(), throttlePolicy.toHumanReadableString())); } return throttle; } public enum ThrottlePolicy { hosted(Duration.ofDays(1), 0.01, 2), disabled(Duration.ZERO, 0, 0); public final Duration throttleWindow; public final double fractionAllowedToFail; public final int minimumAllowedToFail; ThrottlePolicy(Duration throttleWindow, double fractionAllowedToFail, int minimumAllowedToFail) { this.throttleWindow = throttleWindow; this.fractionAllowedToFail = fractionAllowedToFail; this.minimumAllowedToFail = minimumAllowedToFail; } public String toHumanReadableString() { return String.format("Max %.0f%% or %d nodes can fail over a period of %s", fractionAllowedToFail*100, minimumAllowedToFail, throttleWindow); } } }
Can be simplified to `value.filter(v -> !v.equals("null"))`
private Optional<String> removeQuotedNulls(Optional<String> value) { return value.isPresent() && value.get().equals("null") ? Optional.empty() : value; }
return value.isPresent() && value.get().equals("null") ? Optional.empty() : value;
private Optional<String> removeQuotedNulls(Optional<String> value) { return value.filter(v -> !v.equals("null")); }
class NodeSerializer { /** The configured node flavors */ private final NodeFlavors flavors; private static final String hostnameKey = "hostname"; private static final String ipAddressesKey = "ipAddresses"; private static final String additionalIpAddressesKey = "additionalIpAddresses"; private static final String openStackIdKey = "openStackId"; private static final String parentHostnameKey = "parentHostname"; private static final String historyKey = "history"; private static final String instanceKey = "instance"; private static final String rebootGenerationKey = "rebootGeneration"; private static final String currentRebootGenerationKey = "currentRebootGeneration"; private static final String vespaVersionKey = "vespaVersion"; private static final String failCountKey = "failCount"; private static final String hardwareFailureKey = "hardwareFailure"; private static final String nodeTypeKey = "type"; private static final String wantToRetireKey = "wantToRetire"; private static final String wantToDeprovisionKey = "wantToDeprovision"; private static final String hardwareDivergenceKey = "hardwareDivergence"; private static final String flavorKey = "flavor"; private static final String tenantIdKey = "tenantId"; private static final String applicationIdKey = "applicationId"; private static final String instanceIdKey = "instanceId"; private static final String serviceIdKey = "serviceId"; private static final String restartGenerationKey = "restartGeneration"; private static final String currentRestartGenerationKey = "currentRestartGeneration"; private static final String removableKey = "removable"; private static final String wantedVespaVersionKey = "wantedVespaVersion"; private static final String historyEventTypeKey = "type"; private static final String atKey = "at"; private static final String agentKey = "agent"; public NodeSerializer(NodeFlavors flavors) { this.flavors = flavors; } public byte[] toJson(Node node) { try { Slime slime = new Slime(); toSlime(node, slime.setObject()); return SlimeUtils.toJsonBytes(slime); } catch (IOException e) { throw new RuntimeException("Serialization of " + node + " to json failed", e); } } private void toSlime(Node node, Cursor object) { object.setString(hostnameKey, node.hostname()); toSlime(node.ipAddresses(), object.setArray(ipAddressesKey)); toSlime(node.additionalIpAddresses(), object.setArray(additionalIpAddressesKey)); object.setString(openStackIdKey, node.openStackId()); node.parentHostname().ifPresent(hostname -> object.setString(parentHostnameKey, hostname)); object.setString(flavorKey, node.flavor().name()); object.setLong(rebootGenerationKey, node.status().reboot().wanted()); object.setLong(currentRebootGenerationKey, node.status().reboot().current()); node.status().vespaVersion().ifPresent(version -> object.setString(vespaVersionKey, version.toString())); object.setLong(failCountKey, node.status().failCount()); node.status().hardwareFailureDescription().ifPresent(failure -> object.setString(hardwareFailureKey, failure)); object.setBool(wantToRetireKey, node.status().wantToRetire()); object.setBool(wantToDeprovisionKey, node.status().wantToDeprovision()); node.allocation().ifPresent(allocation -> toSlime(allocation, object.setObject(instanceKey))); toSlime(node.history(), object.setArray(historyKey)); object.setString(nodeTypeKey, toString(node.type())); node.status().hardwareDivergence().ifPresent(hardwareDivergence -> object.setString(hardwareDivergenceKey, hardwareDivergence)); } private void toSlime(Allocation allocation, Cursor object) { object.setString(tenantIdKey, allocation.owner().tenant().value()); object.setString(applicationIdKey, allocation.owner().application().value()); object.setString(instanceIdKey, allocation.owner().instance().value()); object.setString(serviceIdKey, allocation.membership().stringValue()); object.setLong(restartGenerationKey, allocation.restartGeneration().wanted()); object.setLong(currentRestartGenerationKey, allocation.restartGeneration().current()); object.setBool(removableKey, allocation.isRemovable()); object.setString(wantedVespaVersionKey, allocation.membership().cluster().vespaVersion().toString()); } private void toSlime(History history, Cursor array) { for (History.Event event : history.events()) toSlime(event, array.addObject()); } private void toSlime(History.Event event, Cursor object) { object.setString(historyEventTypeKey, toString(event.type())); object.setLong(atKey, event.at().toEpochMilli()); object.setString(agentKey, toString(event.agent())); } private void toSlime(Set<String> ipAddresses, Cursor array) { ipAddresses.forEach(array::addString); } public Node fromJson(Node.State state, byte[] data) { return nodeFromSlime(state, SlimeUtils.jsonToSlime(data).get()); } private Node nodeFromSlime(Node.State state, Inspector object) { return new Node(object.field(openStackIdKey).asString(), ipAddressesFromSlime(object, ipAddressesKey), ipAddressesFromSlime(object, additionalIpAddressesKey), object.field(hostnameKey).asString(), parentHostnameFromSlime(object), flavorFromSlime(object), statusFromSlime(object), state, allocationFromSlime(object.field(instanceKey)), historyFromSlime(object.field(historyKey)), nodeTypeFromString(object.field(nodeTypeKey).asString())); } private Status statusFromSlime(Inspector object) { boolean wantToDeprovision = object.field(wantToDeprovisionKey).valid() && object.field(wantToDeprovisionKey).asBool(); return new Status(generationFromSlime(object, rebootGenerationKey, currentRebootGenerationKey), versionFromSlime(object.field(vespaVersionKey)), (int)object.field(failCountKey).asLong(), hardwareFailureDescriptionFromSlime(object), object.field(wantToRetireKey).asBool(), wantToDeprovision, removeQuotedNulls(hardwareDivergenceFromSlime(object))); } private Flavor flavorFromSlime(Inspector object) { return flavors.getFlavorOrThrow(object.field(flavorKey).asString()); } private Optional<Allocation> allocationFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(new Allocation(applicationIdFromSlime(object), clusterMembershipFromSlime(object), generationFromSlime(object, restartGenerationKey, currentRestartGenerationKey), object.field(removableKey).asBool())); } private ApplicationId applicationIdFromSlime(Inspector object) { return ApplicationId.from(TenantName.from(object.field(tenantIdKey).asString()), ApplicationName.from(object.field(applicationIdKey).asString()), InstanceName.from(object.field(instanceIdKey).asString())); } private History historyFromSlime(Inspector array) { List<History.Event> events = new ArrayList<>(); array.traverse((ArrayTraverser) (int i, Inspector item) -> { History.Event event = eventFromSlime(item); if (event != null) events.add(event); }); return new History(events); } private History.Event eventFromSlime(Inspector object) { History.Event.Type type = eventTypeFromString(object.field(historyEventTypeKey).asString()); if (type == null) return null; Instant at = Instant.ofEpochMilli(object.field(atKey).asLong()); Agent agent = eventAgentFromSlime(object.field(agentKey)); return new History.Event(type, agent, at); } private Generation generationFromSlime(Inspector object, String wantedField, String currentField) { Inspector current = object.field(currentField); return new Generation(object.field(wantedField).asLong(), current.asLong()); } private ClusterMembership clusterMembershipFromSlime(Inspector object) { return ClusterMembership.from(object.field(serviceIdKey).asString(), versionFromSlime(object.field(wantedVespaVersionKey)).get()); } private Optional<Version> versionFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(Version.fromString(object.asString())); } private Optional<String> parentHostnameFromSlime(Inspector object) { if (object.field(parentHostnameKey).valid()) return Optional.of(object.field(parentHostnameKey).asString()); else return Optional.empty(); } private Optional<String> hardwareDivergenceFromSlime(Inspector object) { if (object.field(hardwareDivergenceKey).valid()) { return Optional.of(object.field(hardwareDivergenceKey).asString()); } return Optional.empty(); } private Set<String> ipAddressesFromSlime(Inspector object, String key) { ImmutableSet.Builder<String> ipAddresses = ImmutableSet.builder(); object.field(key).traverse((ArrayTraverser) (i, item) -> ipAddresses.add(item.asString())); return ipAddresses.build(); } private Optional<String> hardwareFailureDescriptionFromSlime(Inspector object) { if (object.field(hardwareFailureKey).valid()) { return Optional.of(object.field(hardwareFailureKey).asString()); } return Optional.empty(); } /** Returns the event type, or null if this event type should be ignored */ private History.Event.Type eventTypeFromString(String eventTypeString) { switch (eventTypeString) { case "provisioned" : return History.Event.Type.provisioned; case "readied" : return History.Event.Type.readied; case "reserved" : return History.Event.Type.reserved; case "activated" : return History.Event.Type.activated; case "retired" : return History.Event.Type.retired; case "deactivated" : return History.Event.Type.deactivated; case "parked" : return History.Event.Type.parked; case "failed" : return History.Event.Type.failed; case "deallocated" : return History.Event.Type.deallocated; case "down" : return History.Event.Type.down; case "requested" : return History.Event.Type.requested; case "rebooted" : return History.Event.Type.rebooted; } throw new IllegalArgumentException("Unknown node event type '" + eventTypeString + "'"); } private String toString(History.Event.Type nodeEventType) { switch (nodeEventType) { case provisioned : return "provisioned"; case readied : return "readied"; case reserved : return "reserved"; case activated : return "activated"; case retired : return "retired"; case deactivated : return "deactivated"; case parked : return "parked"; case failed : return "failed"; case deallocated : return "deallocated"; case down : return "down"; case requested: return "requested"; case rebooted: return "rebooted"; } throw new IllegalArgumentException("Serialized form of '" + nodeEventType + "' not defined"); } private Agent eventAgentFromSlime(Inspector eventAgentField) { if ( ! eventAgentField.valid()) return Agent.system; switch (eventAgentField.asString()) { case "application" : return Agent.application; case "system" : return Agent.system; case "operator" : return Agent.operator; case "NodeRetirer" : return Agent.NodeRetirer; } throw new IllegalArgumentException("Unknown node event agent '" + eventAgentField.asString() + "'"); } private String toString(Agent agent) { switch (agent) { case application : return "application"; case system : return "system"; case operator : return "operator"; case NodeRetirer : return "NodeRetirer"; } throw new IllegalArgumentException("Serialized form of '" + agent + "' not defined"); } private NodeType nodeTypeFromString(String typeString) { switch (typeString) { case "tenant" : return NodeType.tenant; case "host" : return NodeType.host; case "proxy" : return NodeType.proxy; default : throw new IllegalArgumentException("Unknown node type '" + typeString + "'"); } } private String toString(NodeType type) { switch (type) { case tenant: return "tenant"; case host: return "host"; case proxy: return "proxy"; } throw new IllegalArgumentException("Serialized form of '" + type + "' not defined"); } }
class NodeSerializer { /** The configured node flavors */ private final NodeFlavors flavors; private static final String hostnameKey = "hostname"; private static final String ipAddressesKey = "ipAddresses"; private static final String additionalIpAddressesKey = "additionalIpAddresses"; private static final String openStackIdKey = "openStackId"; private static final String parentHostnameKey = "parentHostname"; private static final String historyKey = "history"; private static final String instanceKey = "instance"; private static final String rebootGenerationKey = "rebootGeneration"; private static final String currentRebootGenerationKey = "currentRebootGeneration"; private static final String vespaVersionKey = "vespaVersion"; private static final String failCountKey = "failCount"; private static final String hardwareFailureKey = "hardwareFailure"; private static final String nodeTypeKey = "type"; private static final String wantToRetireKey = "wantToRetire"; private static final String wantToDeprovisionKey = "wantToDeprovision"; private static final String hardwareDivergenceKey = "hardwareDivergence"; private static final String flavorKey = "flavor"; private static final String tenantIdKey = "tenantId"; private static final String applicationIdKey = "applicationId"; private static final String instanceIdKey = "instanceId"; private static final String serviceIdKey = "serviceId"; private static final String restartGenerationKey = "restartGeneration"; private static final String currentRestartGenerationKey = "currentRestartGeneration"; private static final String removableKey = "removable"; private static final String wantedVespaVersionKey = "wantedVespaVersion"; private static final String historyEventTypeKey = "type"; private static final String atKey = "at"; private static final String agentKey = "agent"; public NodeSerializer(NodeFlavors flavors) { this.flavors = flavors; } public byte[] toJson(Node node) { try { Slime slime = new Slime(); toSlime(node, slime.setObject()); return SlimeUtils.toJsonBytes(slime); } catch (IOException e) { throw new RuntimeException("Serialization of " + node + " to json failed", e); } } private void toSlime(Node node, Cursor object) { object.setString(hostnameKey, node.hostname()); toSlime(node.ipAddresses(), object.setArray(ipAddressesKey)); toSlime(node.additionalIpAddresses(), object.setArray(additionalIpAddressesKey)); object.setString(openStackIdKey, node.openStackId()); node.parentHostname().ifPresent(hostname -> object.setString(parentHostnameKey, hostname)); object.setString(flavorKey, node.flavor().name()); object.setLong(rebootGenerationKey, node.status().reboot().wanted()); object.setLong(currentRebootGenerationKey, node.status().reboot().current()); node.status().vespaVersion().ifPresent(version -> object.setString(vespaVersionKey, version.toString())); object.setLong(failCountKey, node.status().failCount()); node.status().hardwareFailureDescription().ifPresent(failure -> object.setString(hardwareFailureKey, failure)); object.setBool(wantToRetireKey, node.status().wantToRetire()); object.setBool(wantToDeprovisionKey, node.status().wantToDeprovision()); node.allocation().ifPresent(allocation -> toSlime(allocation, object.setObject(instanceKey))); toSlime(node.history(), object.setArray(historyKey)); object.setString(nodeTypeKey, toString(node.type())); node.status().hardwareDivergence().ifPresent(hardwareDivergence -> object.setString(hardwareDivergenceKey, hardwareDivergence)); } private void toSlime(Allocation allocation, Cursor object) { object.setString(tenantIdKey, allocation.owner().tenant().value()); object.setString(applicationIdKey, allocation.owner().application().value()); object.setString(instanceIdKey, allocation.owner().instance().value()); object.setString(serviceIdKey, allocation.membership().stringValue()); object.setLong(restartGenerationKey, allocation.restartGeneration().wanted()); object.setLong(currentRestartGenerationKey, allocation.restartGeneration().current()); object.setBool(removableKey, allocation.isRemovable()); object.setString(wantedVespaVersionKey, allocation.membership().cluster().vespaVersion().toString()); } private void toSlime(History history, Cursor array) { for (History.Event event : history.events()) toSlime(event, array.addObject()); } private void toSlime(History.Event event, Cursor object) { object.setString(historyEventTypeKey, toString(event.type())); object.setLong(atKey, event.at().toEpochMilli()); object.setString(agentKey, toString(event.agent())); } private void toSlime(Set<String> ipAddresses, Cursor array) { ipAddresses.forEach(array::addString); } public Node fromJson(Node.State state, byte[] data) { return nodeFromSlime(state, SlimeUtils.jsonToSlime(data).get()); } private Node nodeFromSlime(Node.State state, Inspector object) { return new Node(object.field(openStackIdKey).asString(), ipAddressesFromSlime(object, ipAddressesKey), ipAddressesFromSlime(object, additionalIpAddressesKey), object.field(hostnameKey).asString(), parentHostnameFromSlime(object), flavorFromSlime(object), statusFromSlime(object), state, allocationFromSlime(object.field(instanceKey)), historyFromSlime(object.field(historyKey)), nodeTypeFromString(object.field(nodeTypeKey).asString())); } private Status statusFromSlime(Inspector object) { boolean wantToDeprovision = object.field(wantToDeprovisionKey).valid() && object.field(wantToDeprovisionKey).asBool(); return new Status(generationFromSlime(object, rebootGenerationKey, currentRebootGenerationKey), versionFromSlime(object.field(vespaVersionKey)), (int)object.field(failCountKey).asLong(), hardwareFailureDescriptionFromSlime(object), object.field(wantToRetireKey).asBool(), wantToDeprovision, removeQuotedNulls(hardwareDivergenceFromSlime(object))); } private Flavor flavorFromSlime(Inspector object) { return flavors.getFlavorOrThrow(object.field(flavorKey).asString()); } private Optional<Allocation> allocationFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(new Allocation(applicationIdFromSlime(object), clusterMembershipFromSlime(object), generationFromSlime(object, restartGenerationKey, currentRestartGenerationKey), object.field(removableKey).asBool())); } private ApplicationId applicationIdFromSlime(Inspector object) { return ApplicationId.from(TenantName.from(object.field(tenantIdKey).asString()), ApplicationName.from(object.field(applicationIdKey).asString()), InstanceName.from(object.field(instanceIdKey).asString())); } private History historyFromSlime(Inspector array) { List<History.Event> events = new ArrayList<>(); array.traverse((ArrayTraverser) (int i, Inspector item) -> { History.Event event = eventFromSlime(item); if (event != null) events.add(event); }); return new History(events); } private History.Event eventFromSlime(Inspector object) { History.Event.Type type = eventTypeFromString(object.field(historyEventTypeKey).asString()); if (type == null) return null; Instant at = Instant.ofEpochMilli(object.field(atKey).asLong()); Agent agent = eventAgentFromSlime(object.field(agentKey)); return new History.Event(type, agent, at); } private Generation generationFromSlime(Inspector object, String wantedField, String currentField) { Inspector current = object.field(currentField); return new Generation(object.field(wantedField).asLong(), current.asLong()); } private ClusterMembership clusterMembershipFromSlime(Inspector object) { return ClusterMembership.from(object.field(serviceIdKey).asString(), versionFromSlime(object.field(wantedVespaVersionKey)).get()); } private Optional<Version> versionFromSlime(Inspector object) { if ( ! object.valid()) return Optional.empty(); return Optional.of(Version.fromString(object.asString())); } private Optional<String> parentHostnameFromSlime(Inspector object) { if (object.field(parentHostnameKey).valid()) return Optional.of(object.field(parentHostnameKey).asString()); else return Optional.empty(); } private Optional<String> hardwareDivergenceFromSlime(Inspector object) { if (object.field(hardwareDivergenceKey).valid()) { return Optional.of(object.field(hardwareDivergenceKey).asString()); } return Optional.empty(); } private Set<String> ipAddressesFromSlime(Inspector object, String key) { ImmutableSet.Builder<String> ipAddresses = ImmutableSet.builder(); object.field(key).traverse((ArrayTraverser) (i, item) -> ipAddresses.add(item.asString())); return ipAddresses.build(); } private Optional<String> hardwareFailureDescriptionFromSlime(Inspector object) { if (object.field(hardwareFailureKey).valid()) { return Optional.of(object.field(hardwareFailureKey).asString()); } return Optional.empty(); } /** Returns the event type, or null if this event type should be ignored */ private History.Event.Type eventTypeFromString(String eventTypeString) { switch (eventTypeString) { case "provisioned" : return History.Event.Type.provisioned; case "readied" : return History.Event.Type.readied; case "reserved" : return History.Event.Type.reserved; case "activated" : return History.Event.Type.activated; case "retired" : return History.Event.Type.retired; case "deactivated" : return History.Event.Type.deactivated; case "parked" : return History.Event.Type.parked; case "failed" : return History.Event.Type.failed; case "deallocated" : return History.Event.Type.deallocated; case "down" : return History.Event.Type.down; case "requested" : return History.Event.Type.requested; case "rebooted" : return History.Event.Type.rebooted; } throw new IllegalArgumentException("Unknown node event type '" + eventTypeString + "'"); } private String toString(History.Event.Type nodeEventType) { switch (nodeEventType) { case provisioned : return "provisioned"; case readied : return "readied"; case reserved : return "reserved"; case activated : return "activated"; case retired : return "retired"; case deactivated : return "deactivated"; case parked : return "parked"; case failed : return "failed"; case deallocated : return "deallocated"; case down : return "down"; case requested: return "requested"; case rebooted: return "rebooted"; } throw new IllegalArgumentException("Serialized form of '" + nodeEventType + "' not defined"); } private Agent eventAgentFromSlime(Inspector eventAgentField) { if ( ! eventAgentField.valid()) return Agent.system; switch (eventAgentField.asString()) { case "application" : return Agent.application; case "system" : return Agent.system; case "operator" : return Agent.operator; case "NodeRetirer" : return Agent.NodeRetirer; } throw new IllegalArgumentException("Unknown node event agent '" + eventAgentField.asString() + "'"); } private String toString(Agent agent) { switch (agent) { case application : return "application"; case system : return "system"; case operator : return "operator"; case NodeRetirer : return "NodeRetirer"; } throw new IllegalArgumentException("Serialized form of '" + agent + "' not defined"); } private NodeType nodeTypeFromString(String typeString) { switch (typeString) { case "tenant" : return NodeType.tenant; case "host" : return NodeType.host; case "proxy" : return NodeType.proxy; default : throw new IllegalArgumentException("Unknown node type '" + typeString + "'"); } } private String toString(NodeType type) { switch (type) { case tenant: return "tenant"; case host: return "host"; case proxy: return "proxy"; } throw new IllegalArgumentException("Serialized form of '" + type + "' not defined"); } }
Same as above.
private Optional<String> removeQuotedNulls(Optional<String> value) { return value.isPresent() && value.get().equals("null") ? Optional.empty() : value; }
return value.isPresent() && value.get().equals("null") ? Optional.empty() : value;
private Optional<String> removeQuotedNulls(Optional<String> value) { return value.filter(v -> !v.equals("null")); }
class NodePatcher { public static final String HARDWARE_FAILURE_DESCRIPTION = "hardwareFailureDescription"; private final NodeFlavors nodeFlavors; private final Inspector inspector; private final NodeRepository nodeRepository; private Node node; public NodePatcher(NodeFlavors nodeFlavors, InputStream json, Node node, NodeRepository nodeRepository) { try { this.nodeFlavors = nodeFlavors; inspector = SlimeUtils.jsonToSlime(IOUtils.readBytes(json, 1000 * 1000)).get(); this.node = node; this.nodeRepository = nodeRepository; } catch (IOException e) { throw new RuntimeException("Error reading request body", e); } } /** * Apply the json to the node and return all nodes affected by the patch. * More than 1 node may be affected if e.g. the node is a Docker host, which may have * children that must be updated in a consistent manner. */ public List<Node> apply() { inspector.traverse((String name, Inspector value) -> { try { node = applyField(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not set field '" + name + "'", e); } } ); List<Node> nodes = new ArrayList<>(); if (node.type() == NodeType.host) { nodes.addAll(modifiedDockerChildNodes()); } nodes.add(node); return nodes; } private List<Node> modifiedDockerChildNodes() { List<Node> children = nodeRepository.getChildNodes(node.hostname()); boolean modified = false; if (inspector.field(HARDWARE_FAILURE_DESCRIPTION).valid()) { Optional<String> hardwareFailure = asOptionalString(inspector.field(HARDWARE_FAILURE_DESCRIPTION)); modified = true; children = children.stream() .map(node -> node.with(node.status().withHardwareFailureDescription(hardwareFailure))) .collect(Collectors.toList()); } return modified ? children : new ArrayList<>(); } private Node applyField(String name, Inspector value) { switch (name) { case "convergedStateVersion" : return node; case "currentRebootGeneration" : return node.withCurrentRebootGeneration(asLong(value), nodeRepository.clock().instant()); case "currentRestartGeneration" : return patchCurrentRestartGeneration(asLong(value)); case "currentDockerImage" : Version versionFromImage = Optional.of(asString(value)) .filter(s -> !s.isEmpty()) .map(DockerImage::new) .map(DockerImage::tagAsVersion) .orElse(Version.emptyVersion); return node.with(node.status().withVespaVersion(versionFromImage)); case "currentVespaVersion" : return node.with(node.status().withVespaVersion(Version.fromString(asString(value)))); case "currentHostedVersion" : return node; case "failCount" : return node.with(node.status().setFailCount(asLong(value).intValue())); case "flavor" : return node.with(nodeFlavors.getFlavorOrThrow(asString(value))); case HARDWARE_FAILURE_DESCRIPTION: return node.with(node.status().withHardwareFailureDescription(asOptionalString(value))); case "parentHostname" : return node.withParentHostname(asString(value)); case "ipAddresses" : return node.withIpAddresses(asStringSet(value)); case "additionalIpAddresses" : return node.withAdditionalIpAddresses(asStringSet(value)); case "wantToRetire" : return node.with(node.status().withWantToRetire(asBoolean(value))); case "wantToDeprovision" : return node.with(node.status().withWantToDeprovision(asBoolean(value))); case "hardwareDivergence" : return node.with(node.status().withHardwareDivergence(removeQuotedNulls(asOptionalString(value)))); default : throw new IllegalArgumentException("Could not apply field '" + name + "' on a node: No such modifiable field"); } } private Set<String> asStringSet(Inspector field) { if ( ! field.type().equals(Type.ARRAY)) throw new IllegalArgumentException("Expected an ARRAY value, got a " + field.type()); TreeSet<String> strings = new TreeSet<>(); for (int i = 0; i < field.entries(); i++) { Inspector entry = field.entry(i); if ( ! entry.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + entry.type()); strings.add(entry.asString()); } return strings; } private Node patchCurrentRestartGeneration(Long value) { Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) return node.with(allocation.get().withRestart(allocation.get().restartGeneration().withCurrent(value))); else throw new IllegalArgumentException("Node is not allocated"); } private Long asLong(Inspector field) { if ( ! field.type().equals(Type.LONG)) throw new IllegalArgumentException("Expected a LONG value, got a " + field.type()); return field.asLong(); } private String asString(Inspector field) { if ( ! field.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + field.type()); return field.asString(); } private Optional<String> asOptionalString(Inspector field) { return field.type().equals(Type.NIX) ? Optional.empty() : Optional.of(asString(field)); } private boolean asBoolean(Inspector field) { if ( ! field.type().equals(Type.BOOL)) throw new IllegalArgumentException("Expected a BOOL value, got a " + field.type()); return field.asBool(); } }
class NodePatcher { public static final String HARDWARE_FAILURE_DESCRIPTION = "hardwareFailureDescription"; private final NodeFlavors nodeFlavors; private final Inspector inspector; private final NodeRepository nodeRepository; private Node node; public NodePatcher(NodeFlavors nodeFlavors, InputStream json, Node node, NodeRepository nodeRepository) { try { this.nodeFlavors = nodeFlavors; inspector = SlimeUtils.jsonToSlime(IOUtils.readBytes(json, 1000 * 1000)).get(); this.node = node; this.nodeRepository = nodeRepository; } catch (IOException e) { throw new RuntimeException("Error reading request body", e); } } /** * Apply the json to the node and return all nodes affected by the patch. * More than 1 node may be affected if e.g. the node is a Docker host, which may have * children that must be updated in a consistent manner. */ public List<Node> apply() { inspector.traverse((String name, Inspector value) -> { try { node = applyField(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not set field '" + name + "'", e); } } ); List<Node> nodes = new ArrayList<>(); if (node.type() == NodeType.host) { nodes.addAll(modifiedDockerChildNodes()); } nodes.add(node); return nodes; } private List<Node> modifiedDockerChildNodes() { List<Node> children = nodeRepository.getChildNodes(node.hostname()); boolean modified = false; if (inspector.field(HARDWARE_FAILURE_DESCRIPTION).valid()) { Optional<String> hardwareFailure = asOptionalString(inspector.field(HARDWARE_FAILURE_DESCRIPTION)); modified = true; children = children.stream() .map(node -> node.with(node.status().withHardwareFailureDescription(hardwareFailure))) .collect(Collectors.toList()); } return modified ? children : new ArrayList<>(); } private Node applyField(String name, Inspector value) { switch (name) { case "convergedStateVersion" : return node; case "currentRebootGeneration" : return node.withCurrentRebootGeneration(asLong(value), nodeRepository.clock().instant()); case "currentRestartGeneration" : return patchCurrentRestartGeneration(asLong(value)); case "currentDockerImage" : Version versionFromImage = Optional.of(asString(value)) .filter(s -> !s.isEmpty()) .map(DockerImage::new) .map(DockerImage::tagAsVersion) .orElse(Version.emptyVersion); return node.with(node.status().withVespaVersion(versionFromImage)); case "currentVespaVersion" : return node.with(node.status().withVespaVersion(Version.fromString(asString(value)))); case "currentHostedVersion" : return node; case "failCount" : return node.with(node.status().setFailCount(asLong(value).intValue())); case "flavor" : return node.with(nodeFlavors.getFlavorOrThrow(asString(value))); case HARDWARE_FAILURE_DESCRIPTION: return node.with(node.status().withHardwareFailureDescription(asOptionalString(value))); case "parentHostname" : return node.withParentHostname(asString(value)); case "ipAddresses" : return node.withIpAddresses(asStringSet(value)); case "additionalIpAddresses" : return node.withAdditionalIpAddresses(asStringSet(value)); case "wantToRetire" : return node.with(node.status().withWantToRetire(asBoolean(value))); case "wantToDeprovision" : return node.with(node.status().withWantToDeprovision(asBoolean(value))); case "hardwareDivergence" : return node.with(node.status().withHardwareDivergence(removeQuotedNulls(asOptionalString(value)))); default : throw new IllegalArgumentException("Could not apply field '" + name + "' on a node: No such modifiable field"); } } private Set<String> asStringSet(Inspector field) { if ( ! field.type().equals(Type.ARRAY)) throw new IllegalArgumentException("Expected an ARRAY value, got a " + field.type()); TreeSet<String> strings = new TreeSet<>(); for (int i = 0; i < field.entries(); i++) { Inspector entry = field.entry(i); if ( ! entry.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + entry.type()); strings.add(entry.asString()); } return strings; } private Node patchCurrentRestartGeneration(Long value) { Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) return node.with(allocation.get().withRestart(allocation.get().restartGeneration().withCurrent(value))); else throw new IllegalArgumentException("Node is not allocated"); } private Long asLong(Inspector field) { if ( ! field.type().equals(Type.LONG)) throw new IllegalArgumentException("Expected a LONG value, got a " + field.type()); return field.asLong(); } private String asString(Inspector field) { if ( ! field.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + field.type()); return field.asString(); } private Optional<String> asOptionalString(Inspector field) { return field.type().equals(Type.NIX) ? Optional.empty() : Optional.of(asString(field)); } private boolean asBoolean(Inspector field) { if ( ! field.type().equals(Type.BOOL)) throw new IllegalArgumentException("Expected a BOOL value, got a " + field.type()); return field.asBool(); } }
Also, it would be nice have a test that sends "null" at the REST API level.
private Optional<String> removeQuotedNulls(Optional<String> value) { return value.isPresent() && value.get().equals("null") ? Optional.empty() : value; }
return value.isPresent() && value.get().equals("null") ? Optional.empty() : value;
private Optional<String> removeQuotedNulls(Optional<String> value) { return value.filter(v -> !v.equals("null")); }
class NodePatcher { public static final String HARDWARE_FAILURE_DESCRIPTION = "hardwareFailureDescription"; private final NodeFlavors nodeFlavors; private final Inspector inspector; private final NodeRepository nodeRepository; private Node node; public NodePatcher(NodeFlavors nodeFlavors, InputStream json, Node node, NodeRepository nodeRepository) { try { this.nodeFlavors = nodeFlavors; inspector = SlimeUtils.jsonToSlime(IOUtils.readBytes(json, 1000 * 1000)).get(); this.node = node; this.nodeRepository = nodeRepository; } catch (IOException e) { throw new RuntimeException("Error reading request body", e); } } /** * Apply the json to the node and return all nodes affected by the patch. * More than 1 node may be affected if e.g. the node is a Docker host, which may have * children that must be updated in a consistent manner. */ public List<Node> apply() { inspector.traverse((String name, Inspector value) -> { try { node = applyField(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not set field '" + name + "'", e); } } ); List<Node> nodes = new ArrayList<>(); if (node.type() == NodeType.host) { nodes.addAll(modifiedDockerChildNodes()); } nodes.add(node); return nodes; } private List<Node> modifiedDockerChildNodes() { List<Node> children = nodeRepository.getChildNodes(node.hostname()); boolean modified = false; if (inspector.field(HARDWARE_FAILURE_DESCRIPTION).valid()) { Optional<String> hardwareFailure = asOptionalString(inspector.field(HARDWARE_FAILURE_DESCRIPTION)); modified = true; children = children.stream() .map(node -> node.with(node.status().withHardwareFailureDescription(hardwareFailure))) .collect(Collectors.toList()); } return modified ? children : new ArrayList<>(); } private Node applyField(String name, Inspector value) { switch (name) { case "convergedStateVersion" : return node; case "currentRebootGeneration" : return node.withCurrentRebootGeneration(asLong(value), nodeRepository.clock().instant()); case "currentRestartGeneration" : return patchCurrentRestartGeneration(asLong(value)); case "currentDockerImage" : Version versionFromImage = Optional.of(asString(value)) .filter(s -> !s.isEmpty()) .map(DockerImage::new) .map(DockerImage::tagAsVersion) .orElse(Version.emptyVersion); return node.with(node.status().withVespaVersion(versionFromImage)); case "currentVespaVersion" : return node.with(node.status().withVespaVersion(Version.fromString(asString(value)))); case "currentHostedVersion" : return node; case "failCount" : return node.with(node.status().setFailCount(asLong(value).intValue())); case "flavor" : return node.with(nodeFlavors.getFlavorOrThrow(asString(value))); case HARDWARE_FAILURE_DESCRIPTION: return node.with(node.status().withHardwareFailureDescription(asOptionalString(value))); case "parentHostname" : return node.withParentHostname(asString(value)); case "ipAddresses" : return node.withIpAddresses(asStringSet(value)); case "additionalIpAddresses" : return node.withAdditionalIpAddresses(asStringSet(value)); case "wantToRetire" : return node.with(node.status().withWantToRetire(asBoolean(value))); case "wantToDeprovision" : return node.with(node.status().withWantToDeprovision(asBoolean(value))); case "hardwareDivergence" : return node.with(node.status().withHardwareDivergence(removeQuotedNulls(asOptionalString(value)))); default : throw new IllegalArgumentException("Could not apply field '" + name + "' on a node: No such modifiable field"); } } private Set<String> asStringSet(Inspector field) { if ( ! field.type().equals(Type.ARRAY)) throw new IllegalArgumentException("Expected an ARRAY value, got a " + field.type()); TreeSet<String> strings = new TreeSet<>(); for (int i = 0; i < field.entries(); i++) { Inspector entry = field.entry(i); if ( ! entry.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + entry.type()); strings.add(entry.asString()); } return strings; } private Node patchCurrentRestartGeneration(Long value) { Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) return node.with(allocation.get().withRestart(allocation.get().restartGeneration().withCurrent(value))); else throw new IllegalArgumentException("Node is not allocated"); } private Long asLong(Inspector field) { if ( ! field.type().equals(Type.LONG)) throw new IllegalArgumentException("Expected a LONG value, got a " + field.type()); return field.asLong(); } private String asString(Inspector field) { if ( ! field.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + field.type()); return field.asString(); } private Optional<String> asOptionalString(Inspector field) { return field.type().equals(Type.NIX) ? Optional.empty() : Optional.of(asString(field)); } private boolean asBoolean(Inspector field) { if ( ! field.type().equals(Type.BOOL)) throw new IllegalArgumentException("Expected a BOOL value, got a " + field.type()); return field.asBool(); } }
class NodePatcher { public static final String HARDWARE_FAILURE_DESCRIPTION = "hardwareFailureDescription"; private final NodeFlavors nodeFlavors; private final Inspector inspector; private final NodeRepository nodeRepository; private Node node; public NodePatcher(NodeFlavors nodeFlavors, InputStream json, Node node, NodeRepository nodeRepository) { try { this.nodeFlavors = nodeFlavors; inspector = SlimeUtils.jsonToSlime(IOUtils.readBytes(json, 1000 * 1000)).get(); this.node = node; this.nodeRepository = nodeRepository; } catch (IOException e) { throw new RuntimeException("Error reading request body", e); } } /** * Apply the json to the node and return all nodes affected by the patch. * More than 1 node may be affected if e.g. the node is a Docker host, which may have * children that must be updated in a consistent manner. */ public List<Node> apply() { inspector.traverse((String name, Inspector value) -> { try { node = applyField(name, value); } catch (IllegalArgumentException e) { throw new IllegalArgumentException("Could not set field '" + name + "'", e); } } ); List<Node> nodes = new ArrayList<>(); if (node.type() == NodeType.host) { nodes.addAll(modifiedDockerChildNodes()); } nodes.add(node); return nodes; } private List<Node> modifiedDockerChildNodes() { List<Node> children = nodeRepository.getChildNodes(node.hostname()); boolean modified = false; if (inspector.field(HARDWARE_FAILURE_DESCRIPTION).valid()) { Optional<String> hardwareFailure = asOptionalString(inspector.field(HARDWARE_FAILURE_DESCRIPTION)); modified = true; children = children.stream() .map(node -> node.with(node.status().withHardwareFailureDescription(hardwareFailure))) .collect(Collectors.toList()); } return modified ? children : new ArrayList<>(); } private Node applyField(String name, Inspector value) { switch (name) { case "convergedStateVersion" : return node; case "currentRebootGeneration" : return node.withCurrentRebootGeneration(asLong(value), nodeRepository.clock().instant()); case "currentRestartGeneration" : return patchCurrentRestartGeneration(asLong(value)); case "currentDockerImage" : Version versionFromImage = Optional.of(asString(value)) .filter(s -> !s.isEmpty()) .map(DockerImage::new) .map(DockerImage::tagAsVersion) .orElse(Version.emptyVersion); return node.with(node.status().withVespaVersion(versionFromImage)); case "currentVespaVersion" : return node.with(node.status().withVespaVersion(Version.fromString(asString(value)))); case "currentHostedVersion" : return node; case "failCount" : return node.with(node.status().setFailCount(asLong(value).intValue())); case "flavor" : return node.with(nodeFlavors.getFlavorOrThrow(asString(value))); case HARDWARE_FAILURE_DESCRIPTION: return node.with(node.status().withHardwareFailureDescription(asOptionalString(value))); case "parentHostname" : return node.withParentHostname(asString(value)); case "ipAddresses" : return node.withIpAddresses(asStringSet(value)); case "additionalIpAddresses" : return node.withAdditionalIpAddresses(asStringSet(value)); case "wantToRetire" : return node.with(node.status().withWantToRetire(asBoolean(value))); case "wantToDeprovision" : return node.with(node.status().withWantToDeprovision(asBoolean(value))); case "hardwareDivergence" : return node.with(node.status().withHardwareDivergence(removeQuotedNulls(asOptionalString(value)))); default : throw new IllegalArgumentException("Could not apply field '" + name + "' on a node: No such modifiable field"); } } private Set<String> asStringSet(Inspector field) { if ( ! field.type().equals(Type.ARRAY)) throw new IllegalArgumentException("Expected an ARRAY value, got a " + field.type()); TreeSet<String> strings = new TreeSet<>(); for (int i = 0; i < field.entries(); i++) { Inspector entry = field.entry(i); if ( ! entry.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + entry.type()); strings.add(entry.asString()); } return strings; } private Node patchCurrentRestartGeneration(Long value) { Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) return node.with(allocation.get().withRestart(allocation.get().restartGeneration().withCurrent(value))); else throw new IllegalArgumentException("Node is not allocated"); } private Long asLong(Inspector field) { if ( ! field.type().equals(Type.LONG)) throw new IllegalArgumentException("Expected a LONG value, got a " + field.type()); return field.asLong(); } private String asString(Inspector field) { if ( ! field.type().equals(Type.STRING)) throw new IllegalArgumentException("Expected a STRING value, got a " + field.type()); return field.asString(); } private Optional<String> asOptionalString(Inspector field) { return field.type().equals(Type.NIX) ? Optional.empty() : Optional.of(asString(field)); } private boolean asBoolean(Inspector field) { if ( ! field.type().equals(Type.BOOL)) throw new IllegalArgumentException("Expected a BOOL value, got a " + field.type()); return field.asBool(); } }
The problem is that `node-admin`'s node-repo client doesn't support updating value to `null` in its current state (because of `JsonInclude.Include.NON_NULL`), so we had to improvise a little as the students were on their final week. I dont think anyone has touched that code since :man_shrugging: .
private List<Node> readyNodesWithHardwareDivergence() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareDivergence().isPresent() && !node.status().hardwareDivergence().get().equals("null")) .collect(Collectors.toList()); }
&& !node.status().hardwareDivergence().get().equals("null"))
private List<Node> readyNodesWithHardwareDivergence() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareDivergence().isPresent()) .collect(Collectors.toList()); }
class NodeFailer extends Maintainer { private static final Logger log = Logger.getLogger(NodeFailer.class.getName()); private static final Duration nodeRequestInterval = Duration.ofMinutes(10); /** Provides information about the status of ready hosts */ private final HostLivenessTracker hostLivenessTracker; /** Provides (more accurate) information about the status of active hosts */ private final ServiceMonitor serviceMonitor; private final Deployer deployer; private final Duration downTimeLimit; private final Clock clock; private final Orchestrator orchestrator; private final Instant constructionTime; private final ThrottlePolicy throttlePolicy; public NodeFailer(Deployer deployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, NodeRepository nodeRepository, Duration downTimeLimit, Clock clock, Orchestrator orchestrator, ThrottlePolicy throttlePolicy, JobControl jobControl) { super(nodeRepository, min(downTimeLimit.dividedBy(2), Duration.ofMinutes(5)), jobControl); this.deployer = deployer; this.hostLivenessTracker = hostLivenessTracker; this.serviceMonitor = serviceMonitor; this.downTimeLimit = downTimeLimit; this.clock = clock; this.orchestrator = orchestrator; this.constructionTime = clock.instant(); this.throttlePolicy = throttlePolicy; } @Override protected void maintain() { updateNodeLivenessEventsForReadyNodes(); for (Node node : readyNodesWhichAreDead()) { if (node.flavor().getType() == Flavor.Type.DOCKER_CONTAINER || node.type() == NodeType.host) continue; if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Not receiving config requests from node"); } for (Node node : readyNodesWithHardwareFailure()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node has hardware failure"); for (Node node: readyNodesWithHardwareDivergence()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node hardware diverges from spec"); for (Node node : determineActiveNodeDownStatus()) { Instant graceTimeEnd = node.history().event(History.Event.Type.down).get().at().plus(downTimeLimit); if (graceTimeEnd.isBefore(clock.instant()) && ! applicationSuspended(node) && failAllowedFor(node.type())) if (!throttle(node)) failActive(node, "Node has been down longer than " + downTimeLimit); } } private void updateNodeLivenessEventsForReadyNodes() { try (Mutex lock = nodeRepository().lockUnallocated()) { for (Node node : nodeRepository().getNodes(Node.State.ready)) { Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname()); if ( ! lastLocalRequest.isPresent()) continue; Optional<History.Event> recordedRequest = node.history().event(History.Event.Type.requested); if ( ! recordedRequest.isPresent() || recordedRequest.get().at().isBefore(lastLocalRequest.get())) { History updatedHistory = node.history().with(new History.Event(History.Event.Type.requested, Agent.system, lastLocalRequest.get())); nodeRepository().write(node.with(updatedHistory)); } } } } private List<Node> readyNodesWhichAreDead() { if (constructionTime.isAfter(clock.instant().minus(nodeRequestInterval).minus(nodeRequestInterval) )) return Collections.emptyList(); Instant oldestAcceptableRequestTime = clock.instant().minus(downTimeLimit).minus(nodeRequestInterval); return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> wasMadeReadyBefore(oldestAcceptableRequestTime, node)) .filter(node -> ! hasRecordedRequestAfter(oldestAcceptableRequestTime, node)) .collect(Collectors.toList()); } private boolean wasMadeReadyBefore(Instant instant, Node node) { Optional<History.Event> readiedEvent = node.history().event(History.Event.Type.readied); if ( ! readiedEvent.isPresent()) return false; return readiedEvent.get().at().isBefore(instant); } private boolean hasRecordedRequestAfter(Instant instant, Node node) { Optional<History.Event> lastRequest = node.history().event(History.Event.Type.requested); if ( ! lastRequest.isPresent()) return false; return lastRequest.get().at().isAfter(instant); } private List<Node> readyNodesWithHardwareFailure() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareFailureDescription().isPresent()) .collect(Collectors.toList()); } private boolean applicationSuspended(Node node) { try { return orchestrator.getApplicationInstanceStatus(node.allocation().get().owner()) == ApplicationInstanceStatus.ALLOWED_TO_BE_DOWN; } catch (ApplicationIdNotFoundException e) { return false; } } /** * We can attempt to fail any number of *tenant* and *host* nodes because the operation will not be effected * unless the node is replaced. * However, nodes of other types are not replaced (because all of the type are used by a single application), * so we only allow one to be in failed at any point in time to protect against runaway failing. */ private boolean failAllowedFor(NodeType nodeType) { if (nodeType == NodeType.tenant || nodeType == NodeType.host) return true; return nodeRepository().getNodes(nodeType, Node.State.failed).size() == 0; } /** * If the node is positively DOWN, and there is no "down" history record, we add it. * If the node is positively UP we remove any "down" history record. * * @return a list of all nodes which are positively currently in the down state */ private List<Node> determineActiveNodeDownStatus() { List<Node> downNodes = new ArrayList<>(); for (ApplicationInstance<ServiceMonitorStatus> application : serviceMonitor.queryStatusOfAllApplicationInstances().values()) { for (ServiceCluster<ServiceMonitorStatus> cluster : application.serviceClusters()) { for (ServiceInstance<ServiceMonitorStatus> service : cluster.serviceInstances()) { Optional<Node> node = nodeRepository().getNode(service.hostName().s(), Node.State.active); if ( ! node.isPresent()) continue; if (service.serviceStatus().equals(ServiceMonitorStatus.DOWN)) downNodes.add(recordAsDown(node.get())); else if (service.serviceStatus().equals(ServiceMonitorStatus.UP)) clearDownRecord(node.get()); } } } return downNodes; } /** * Record a node as down if not already recorded and returns the node in the new state. * This assumes the node is found in the node * repo and that the node is allocated. If we get here otherwise something is truly odd. */ private Node recordAsDown(Node node) { if (node.history().event(History.Event.Type.down).isPresent()) return node; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); return nodeRepository().write(node.downAt(clock.instant())); } } private void clearDownRecord(Node node) { if ( ! node.history().event(History.Event.Type.down).isPresent()) return; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); nodeRepository().write(node.up()); } } /** * Called when a node should be moved to the failed state: Do that if it seems safe, * which is when the node repo has available capacity to replace the node (and all its tenant nodes if host). * Otherwise not replacing the node ensures (by Orchestrator check) that no further action will be taken. * * @return whether node was successfully failed */ private boolean failActive(Node node, String reason) { Optional<Deployment> deployment = deployer.deployFromLocalActive(node.allocation().get().owner(), Duration.ofMinutes(30)); if ( ! deployment.isPresent()) return false; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { boolean allTenantNodesFailedOutSuccessfully = true; for (Node failingTenantNode : nodeRepository().getChildNodes(node.hostname())) { if (failingTenantNode.state() == Node.State.active) { allTenantNodesFailedOutSuccessfully &= failActive(failingTenantNode, reason); } else { nodeRepository().fail(failingTenantNode.hostname(), Agent.system, reason); } } if (! allTenantNodesFailedOutSuccessfully) return false; node = nodeRepository().fail(node.hostname(), Agent.system, reason); try { deployment.get().activate(); return true; } catch (RuntimeException e) { nodeRepository().reactivate(node.hostname(), Agent.system); log.log(Level.WARNING, "Attempted to fail " + node + " for " + node.allocation().get().owner() + ", but redeploying without the node failed", e); return false; } } } /** Returns true if node failing should be throttled */ private boolean throttle(Node node) { if (throttlePolicy == ThrottlePolicy.disabled) return false; Instant startOfThrottleWindow = clock.instant().minus(throttlePolicy.throttleWindow); List<Node> nodes = nodeRepository().getNodes().stream() .filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) .collect(Collectors.toList()); long recentlyFailedNodes = nodes.stream() .map(n -> n.history().event(History.Event.Type.failed)) .filter(Optional::isPresent) .map(Optional::get) .filter(failedEvent -> failedEvent.at().isAfter(startOfThrottleWindow)) .count(); boolean throttle = recentlyFailedNodes >= Math.max(nodes.size() * throttlePolicy.fractionAllowedToFail, throttlePolicy.minimumAllowedToFail); if (throttle) { log.info(String.format("Want to fail node %s, but throttling is in effect: %s", node.hostname(), throttlePolicy.toHumanReadableString())); } return throttle; } public enum ThrottlePolicy { hosted(Duration.ofDays(1), 0.01, 2), disabled(Duration.ZERO, 0, 0); public final Duration throttleWindow; public final double fractionAllowedToFail; public final int minimumAllowedToFail; ThrottlePolicy(Duration throttleWindow, double fractionAllowedToFail, int minimumAllowedToFail) { this.throttleWindow = throttleWindow; this.fractionAllowedToFail = fractionAllowedToFail; this.minimumAllowedToFail = minimumAllowedToFail; } public String toHumanReadableString() { return String.format("Max %.0f%% or %d nodes can fail over a period of %s", fractionAllowedToFail*100, minimumAllowedToFail, throttleWindow); } } }
class NodeFailer extends Maintainer { private static final Logger log = Logger.getLogger(NodeFailer.class.getName()); private static final Duration nodeRequestInterval = Duration.ofMinutes(10); /** Provides information about the status of ready hosts */ private final HostLivenessTracker hostLivenessTracker; /** Provides (more accurate) information about the status of active hosts */ private final ServiceMonitor serviceMonitor; private final Deployer deployer; private final Duration downTimeLimit; private final Clock clock; private final Orchestrator orchestrator; private final Instant constructionTime; private final ThrottlePolicy throttlePolicy; public NodeFailer(Deployer deployer, HostLivenessTracker hostLivenessTracker, ServiceMonitor serviceMonitor, NodeRepository nodeRepository, Duration downTimeLimit, Clock clock, Orchestrator orchestrator, ThrottlePolicy throttlePolicy, JobControl jobControl) { super(nodeRepository, min(downTimeLimit.dividedBy(2), Duration.ofMinutes(5)), jobControl); this.deployer = deployer; this.hostLivenessTracker = hostLivenessTracker; this.serviceMonitor = serviceMonitor; this.downTimeLimit = downTimeLimit; this.clock = clock; this.orchestrator = orchestrator; this.constructionTime = clock.instant(); this.throttlePolicy = throttlePolicy; } @Override protected void maintain() { updateNodeLivenessEventsForReadyNodes(); for (Node node : readyNodesWhichAreDead()) { if (node.flavor().getType() == Flavor.Type.DOCKER_CONTAINER || node.type() == NodeType.host) continue; if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Not receiving config requests from node"); } for (Node node : readyNodesWithHardwareFailure()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node has hardware failure"); for (Node node: readyNodesWithHardwareDivergence()) if ( ! throttle(node)) nodeRepository().fail(node.hostname(), Agent.system, "Node hardware diverges from spec"); for (Node node : determineActiveNodeDownStatus()) { Instant graceTimeEnd = node.history().event(History.Event.Type.down).get().at().plus(downTimeLimit); if (graceTimeEnd.isBefore(clock.instant()) && ! applicationSuspended(node) && failAllowedFor(node.type())) if (!throttle(node)) failActive(node, "Node has been down longer than " + downTimeLimit); } } private void updateNodeLivenessEventsForReadyNodes() { try (Mutex lock = nodeRepository().lockUnallocated()) { for (Node node : nodeRepository().getNodes(Node.State.ready)) { Optional<Instant> lastLocalRequest = hostLivenessTracker.lastRequestFrom(node.hostname()); if ( ! lastLocalRequest.isPresent()) continue; Optional<History.Event> recordedRequest = node.history().event(History.Event.Type.requested); if ( ! recordedRequest.isPresent() || recordedRequest.get().at().isBefore(lastLocalRequest.get())) { History updatedHistory = node.history().with(new History.Event(History.Event.Type.requested, Agent.system, lastLocalRequest.get())); nodeRepository().write(node.with(updatedHistory)); } } } } private List<Node> readyNodesWhichAreDead() { if (constructionTime.isAfter(clock.instant().minus(nodeRequestInterval).minus(nodeRequestInterval) )) return Collections.emptyList(); Instant oldestAcceptableRequestTime = clock.instant().minus(downTimeLimit).minus(nodeRequestInterval); return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> wasMadeReadyBefore(oldestAcceptableRequestTime, node)) .filter(node -> ! hasRecordedRequestAfter(oldestAcceptableRequestTime, node)) .collect(Collectors.toList()); } private boolean wasMadeReadyBefore(Instant instant, Node node) { Optional<History.Event> readiedEvent = node.history().event(History.Event.Type.readied); if ( ! readiedEvent.isPresent()) return false; return readiedEvent.get().at().isBefore(instant); } private boolean hasRecordedRequestAfter(Instant instant, Node node) { Optional<History.Event> lastRequest = node.history().event(History.Event.Type.requested); if ( ! lastRequest.isPresent()) return false; return lastRequest.get().at().isAfter(instant); } private List<Node> readyNodesWithHardwareFailure() { return nodeRepository().getNodes(Node.State.ready).stream() .filter(node -> node.status().hardwareFailureDescription().isPresent()) .collect(Collectors.toList()); } private boolean applicationSuspended(Node node) { try { return orchestrator.getApplicationInstanceStatus(node.allocation().get().owner()) == ApplicationInstanceStatus.ALLOWED_TO_BE_DOWN; } catch (ApplicationIdNotFoundException e) { return false; } } /** * We can attempt to fail any number of *tenant* and *host* nodes because the operation will not be effected * unless the node is replaced. * However, nodes of other types are not replaced (because all of the type are used by a single application), * so we only allow one to be in failed at any point in time to protect against runaway failing. */ private boolean failAllowedFor(NodeType nodeType) { if (nodeType == NodeType.tenant || nodeType == NodeType.host) return true; return nodeRepository().getNodes(nodeType, Node.State.failed).size() == 0; } /** * If the node is positively DOWN, and there is no "down" history record, we add it. * If the node is positively UP we remove any "down" history record. * * @return a list of all nodes which are positively currently in the down state */ private List<Node> determineActiveNodeDownStatus() { List<Node> downNodes = new ArrayList<>(); for (ApplicationInstance<ServiceMonitorStatus> application : serviceMonitor.queryStatusOfAllApplicationInstances().values()) { for (ServiceCluster<ServiceMonitorStatus> cluster : application.serviceClusters()) { for (ServiceInstance<ServiceMonitorStatus> service : cluster.serviceInstances()) { Optional<Node> node = nodeRepository().getNode(service.hostName().s(), Node.State.active); if ( ! node.isPresent()) continue; if (service.serviceStatus().equals(ServiceMonitorStatus.DOWN)) downNodes.add(recordAsDown(node.get())); else if (service.serviceStatus().equals(ServiceMonitorStatus.UP)) clearDownRecord(node.get()); } } } return downNodes; } /** * Record a node as down if not already recorded and returns the node in the new state. * This assumes the node is found in the node * repo and that the node is allocated. If we get here otherwise something is truly odd. */ private Node recordAsDown(Node node) { if (node.history().event(History.Event.Type.down).isPresent()) return node; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); return nodeRepository().write(node.downAt(clock.instant())); } } private void clearDownRecord(Node node) { if ( ! node.history().event(History.Event.Type.down).isPresent()) return; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { node = nodeRepository().getNode(node.hostname(), Node.State.active).get(); nodeRepository().write(node.up()); } } /** * Called when a node should be moved to the failed state: Do that if it seems safe, * which is when the node repo has available capacity to replace the node (and all its tenant nodes if host). * Otherwise not replacing the node ensures (by Orchestrator check) that no further action will be taken. * * @return whether node was successfully failed */ private boolean failActive(Node node, String reason) { Optional<Deployment> deployment = deployer.deployFromLocalActive(node.allocation().get().owner(), Duration.ofMinutes(30)); if ( ! deployment.isPresent()) return false; try (Mutex lock = nodeRepository().lock(node.allocation().get().owner())) { boolean allTenantNodesFailedOutSuccessfully = true; for (Node failingTenantNode : nodeRepository().getChildNodes(node.hostname())) { if (failingTenantNode.state() == Node.State.active) { allTenantNodesFailedOutSuccessfully &= failActive(failingTenantNode, reason); } else { nodeRepository().fail(failingTenantNode.hostname(), Agent.system, reason); } } if (! allTenantNodesFailedOutSuccessfully) return false; node = nodeRepository().fail(node.hostname(), Agent.system, reason); try { deployment.get().activate(); return true; } catch (RuntimeException e) { nodeRepository().reactivate(node.hostname(), Agent.system); log.log(Level.WARNING, "Attempted to fail " + node + " for " + node.allocation().get().owner() + ", but redeploying without the node failed", e); return false; } } } /** Returns true if node failing should be throttled */ private boolean throttle(Node node) { if (throttlePolicy == ThrottlePolicy.disabled) return false; Instant startOfThrottleWindow = clock.instant().minus(throttlePolicy.throttleWindow); List<Node> nodes = nodeRepository().getNodes().stream() .filter(n -> n.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) .collect(Collectors.toList()); long recentlyFailedNodes = nodes.stream() .map(n -> n.history().event(History.Event.Type.failed)) .filter(Optional::isPresent) .map(Optional::get) .filter(failedEvent -> failedEvent.at().isAfter(startOfThrottleWindow)) .count(); boolean throttle = recentlyFailedNodes >= Math.max(nodes.size() * throttlePolicy.fractionAllowedToFail, throttlePolicy.minimumAllowedToFail); if (throttle) { log.info(String.format("Want to fail node %s, but throttling is in effect: %s", node.hostname(), throttlePolicy.toHumanReadableString())); } return throttle; } public enum ThrottlePolicy { hosted(Duration.ofDays(1), 0.01, 2), disabled(Duration.ZERO, 0, 0); public final Duration throttleWindow; public final double fractionAllowedToFail; public final int minimumAllowedToFail; ThrottlePolicy(Duration throttleWindow, double fractionAllowedToFail, int minimumAllowedToFail) { this.throttleWindow = throttleWindow; this.fractionAllowedToFail = fractionAllowedToFail; this.minimumAllowedToFail = minimumAllowedToFail; } public String toHumanReadableString() { return String.format("Max %.0f%% or %d nodes can fail over a period of %s", fractionAllowedToFail*100, minimumAllowedToFail, throttleWindow); } } }
@hmusum For the TenantTest.testJsonSerialization() test, this initialize() call ends up trying to copy classes() "/home/hakon/1/vespa-engine/vespa/configserver/target/1509484982440-0" to serverdefs() "/home/hakon/1/vespa-engine/vespa/configserver/target/1509484982440-0/serverdef". Which ends up recursing down and creating as many serverdef as it possibly can before the OS returns an error. I wouldn't have noticed this if it were not for the fact than mvn clean is extremely slow on configserver.
public ConfigServerDB(ConfigserverConfig configserverConfig) { this.configserverConfig = configserverConfig; this.serverDB = new File(Defaults.getDefaults().underVespaHome(configserverConfig.configServerDBDir())); createDirectory(serverdefs()); try { initialize(configserverConfig.configModelPluginDir()); } catch (IllegalArgumentException e) { log.log(LogLevel.ERROR, "Error initializing serverdb: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Unable to initialize server db", e); } }
initialize(configserverConfig.configModelPluginDir());
public ConfigServerDB(ConfigserverConfig configserverConfig) { this.configserverConfig = configserverConfig; this.serverDB = new File(Defaults.getDefaults().underVespaHome(configserverConfig.configServerDBDir())); createDirectory(serverdefs()); try { initialize(configserverConfig.configModelPluginDir()); } catch (IllegalArgumentException e) { log.log(LogLevel.ERROR, "Error initializing serverdb: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Unable to initialize server db", e); } }
class ConfigServerDB { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ConfigServerDB.class.getName()); private final File serverDB; private final ConfigserverConfig configserverConfig; public static ConfigServerDB createTestConfigServerDb(String dbDir, String definitionsDir) { return new ConfigServerDB(new ConfigserverConfig(new ConfigserverConfig.Builder() .configServerDBDir(dbDir) .configDefinitionsDir(definitionsDir))); } public File classes() { return new File(Defaults.getDefaults().underVespaHome(configserverConfig.configDefinitionsDir()));} public File serverdefs() { return new File(serverDB, "serverdefs"); } public static void createDirectory(File d) { if (d.exists()) { if (!d.isDirectory()) { throw new IllegalArgumentException(d.getAbsolutePath() + " exists, but isn't a directory."); } } else { if (!d.mkdirs()) { throw new IllegalArgumentException("Couldn't create " + d.getAbsolutePath()); } } } private void initialize(List<String> pluginDirectories) throws IOException { IOUtils.recursiveDeleteDir(serverdefs()); IOUtils.copyDirectory(classes(), serverdefs()); ConfigDefinitionDir configDefinitionDir = new ConfigDefinitionDir(serverdefs()); ArrayList<Bundle> bundles = new ArrayList<>(); for (String pluginDirectory : pluginDirectories) { bundles.addAll(Bundle.getBundles(new File(pluginDirectory))); } log.log(LogLevel.DEBUG, "Found " + bundles.size() + " bundles"); List<Bundle> addedBundles = new ArrayList<>(); for (Bundle bundle : bundles) { log.log(LogLevel.DEBUG, "Bundle in " + bundle.getFile().getAbsolutePath() + " appears to contain " + bundle.getDefEntries().size() + " entries"); configDefinitionDir.addConfigDefinitionsFromBundle(bundle, addedBundles); addedBundles.add(bundle); } } public ConfigserverConfig getConfigserverConfig() { return configserverConfig; } }
class ConfigServerDB { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ConfigServerDB.class.getName()); private final File serverDB; private final ConfigserverConfig configserverConfig; public static ConfigServerDB createTestConfigServerDb(String dbDir, String definitionsDir) { return new ConfigServerDB(new ConfigserverConfig(new ConfigserverConfig.Builder() .configServerDBDir(dbDir) .configDefinitionsDir(definitionsDir))); } public File classes() { return new File(Defaults.getDefaults().underVespaHome(configserverConfig.configDefinitionsDir()));} public File serverdefs() { return new File(serverDB, "serverdefs"); } public static void createDirectory(File d) { if (d.exists()) { if (!d.isDirectory()) { throw new IllegalArgumentException(d.getAbsolutePath() + " exists, but isn't a directory."); } } else { if (!d.mkdirs()) { throw new IllegalArgumentException("Couldn't create " + d.getAbsolutePath()); } } } private void initialize(List<String> pluginDirectories) throws IOException { IOUtils.recursiveDeleteDir(serverdefs()); IOUtils.copyDirectory(classes(), serverdefs()); ConfigDefinitionDir configDefinitionDir = new ConfigDefinitionDir(serverdefs()); ArrayList<Bundle> bundles = new ArrayList<>(); for (String pluginDirectory : pluginDirectories) { bundles.addAll(Bundle.getBundles(new File(pluginDirectory))); } log.log(LogLevel.DEBUG, "Found " + bundles.size() + " bundles"); List<Bundle> addedBundles = new ArrayList<>(); for (Bundle bundle : bundles) { log.log(LogLevel.DEBUG, "Bundle in " + bundle.getFile().getAbsolutePath() + " appears to contain " + bundle.getDefEntries().size() + " entries"); configDefinitionDir.addConfigDefinitionsFromBundle(bundle, addedBundles); addedBundles.add(bundle); } } public ConfigserverConfig getConfigserverConfig() { return configserverConfig; } }
Nice catch @hakonhall, thanks! PR to fix this: https://github.com/vespa-engine/vespa/pull/3958
public ConfigServerDB(ConfigserverConfig configserverConfig) { this.configserverConfig = configserverConfig; this.serverDB = new File(Defaults.getDefaults().underVespaHome(configserverConfig.configServerDBDir())); createDirectory(serverdefs()); try { initialize(configserverConfig.configModelPluginDir()); } catch (IllegalArgumentException e) { log.log(LogLevel.ERROR, "Error initializing serverdb: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Unable to initialize server db", e); } }
initialize(configserverConfig.configModelPluginDir());
public ConfigServerDB(ConfigserverConfig configserverConfig) { this.configserverConfig = configserverConfig; this.serverDB = new File(Defaults.getDefaults().underVespaHome(configserverConfig.configServerDBDir())); createDirectory(serverdefs()); try { initialize(configserverConfig.configModelPluginDir()); } catch (IllegalArgumentException e) { log.log(LogLevel.ERROR, "Error initializing serverdb: " + e.getMessage()); } catch (IOException e) { throw new RuntimeException("Unable to initialize server db", e); } }
class ConfigServerDB { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ConfigServerDB.class.getName()); private final File serverDB; private final ConfigserverConfig configserverConfig; public static ConfigServerDB createTestConfigServerDb(String dbDir, String definitionsDir) { return new ConfigServerDB(new ConfigserverConfig(new ConfigserverConfig.Builder() .configServerDBDir(dbDir) .configDefinitionsDir(definitionsDir))); } public File classes() { return new File(Defaults.getDefaults().underVespaHome(configserverConfig.configDefinitionsDir()));} public File serverdefs() { return new File(serverDB, "serverdefs"); } public static void createDirectory(File d) { if (d.exists()) { if (!d.isDirectory()) { throw new IllegalArgumentException(d.getAbsolutePath() + " exists, but isn't a directory."); } } else { if (!d.mkdirs()) { throw new IllegalArgumentException("Couldn't create " + d.getAbsolutePath()); } } } private void initialize(List<String> pluginDirectories) throws IOException { IOUtils.recursiveDeleteDir(serverdefs()); IOUtils.copyDirectory(classes(), serverdefs()); ConfigDefinitionDir configDefinitionDir = new ConfigDefinitionDir(serverdefs()); ArrayList<Bundle> bundles = new ArrayList<>(); for (String pluginDirectory : pluginDirectories) { bundles.addAll(Bundle.getBundles(new File(pluginDirectory))); } log.log(LogLevel.DEBUG, "Found " + bundles.size() + " bundles"); List<Bundle> addedBundles = new ArrayList<>(); for (Bundle bundle : bundles) { log.log(LogLevel.DEBUG, "Bundle in " + bundle.getFile().getAbsolutePath() + " appears to contain " + bundle.getDefEntries().size() + " entries"); configDefinitionDir.addConfigDefinitionsFromBundle(bundle, addedBundles); addedBundles.add(bundle); } } public ConfigserverConfig getConfigserverConfig() { return configserverConfig; } }
class ConfigServerDB { private static final java.util.logging.Logger log = java.util.logging.Logger.getLogger(ConfigServerDB.class.getName()); private final File serverDB; private final ConfigserverConfig configserverConfig; public static ConfigServerDB createTestConfigServerDb(String dbDir, String definitionsDir) { return new ConfigServerDB(new ConfigserverConfig(new ConfigserverConfig.Builder() .configServerDBDir(dbDir) .configDefinitionsDir(definitionsDir))); } public File classes() { return new File(Defaults.getDefaults().underVespaHome(configserverConfig.configDefinitionsDir()));} public File serverdefs() { return new File(serverDB, "serverdefs"); } public static void createDirectory(File d) { if (d.exists()) { if (!d.isDirectory()) { throw new IllegalArgumentException(d.getAbsolutePath() + " exists, but isn't a directory."); } } else { if (!d.mkdirs()) { throw new IllegalArgumentException("Couldn't create " + d.getAbsolutePath()); } } } private void initialize(List<String> pluginDirectories) throws IOException { IOUtils.recursiveDeleteDir(serverdefs()); IOUtils.copyDirectory(classes(), serverdefs()); ConfigDefinitionDir configDefinitionDir = new ConfigDefinitionDir(serverdefs()); ArrayList<Bundle> bundles = new ArrayList<>(); for (String pluginDirectory : pluginDirectories) { bundles.addAll(Bundle.getBundles(new File(pluginDirectory))); } log.log(LogLevel.DEBUG, "Found " + bundles.size() + " bundles"); List<Bundle> addedBundles = new ArrayList<>(); for (Bundle bundle : bundles) { log.log(LogLevel.DEBUG, "Bundle in " + bundle.getFile().getAbsolutePath() + " appears to contain " + bundle.getDefEntries().size() + " entries"); configDefinitionDir.addConfigDefinitionsFromBundle(bundle, addedBundles); addedBundles.add(bundle); } } public ConfigserverConfig getConfigserverConfig() { return configserverConfig; } }
maybe we should use `wantedVespaVersion` instead ?
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
metric.set("wantedVersion", wantedVersionNumber, context);
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
`wantToChangeVespaVersion` instead?
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
metric.set("wantToChangeVersion", converged ? 0 : 1, context);
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
`currentVespaVersion` instead?
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
metric.set("currentVersion", currentVersionNumber, context);
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Done
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
metric.set("currentVersion", currentVersionNumber, context);
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Done
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
metric.set("wantToChangeVersion", converged ? 0 : 1, context);
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Done
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
metric.set("wantedVersion", wantedVersionNumber, context);
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
What does 'automatically' mean here? If this is done elsewhere, this comment will become outdated when the other code changes.
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Let me remove the comment.
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
private void updateNodeMetrics(Node node) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); nodes.forEach(this::updateNodeMetrics); updateStateMetrics(nodes); updateDockerMetrics(nodes); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Why `localhost`?
private IdentityDocument generateIdDocument(Node node) { Allocation allocation = node.allocation().get(); ProviderUniqueId providerUniqueId = new ProviderUniqueId( allocation.owner().tenant().value(), allocation.owner().application().value(), zone.environment().value(), zone.region().value(), allocation.owner().instance().value(), allocation.membership().cluster().id().value(), allocation.membership().index()); return new IdentityDocument( providerUniqueId, "localhost", node.hostname(), Instant.now()); }
"localhost",
private IdentityDocument generateIdDocument(Node node) { Allocation allocation = node.allocation().orElseThrow(() -> new RuntimeException("No allocation for node " + node.hostname())); ProviderUniqueId providerUniqueId = new ProviderUniqueId( allocation.owner().tenant().value(), allocation.owner().application().value(), zone.environment().value(), zone.region().value(), allocation.owner().instance().value(), allocation.membership().cluster().id().value(), allocation.membership().index()); return new IdentityDocument( providerUniqueId, "localhost", node.hostname(), Instant.now()); }
class IdentityDocumentGenerator { private final NodeRepository nodeRepository; private final Zone zone; private final KeyProvider keyProvider; public IdentityDocumentGenerator(NodeRepository nodeRepository, Zone zone, KeyProvider keyProvider) { this.nodeRepository = nodeRepository; this.zone = zone; this.keyProvider = keyProvider; } public String generateSignedIdentityDocument(String hostname) { Node node = nodeRepository.getNode(hostname).orElseThrow(() -> new RuntimeException("Unable to find node " + hostname)); try { IdentityDocument identityDocument = generateIdDocument(node); String identityDocumentString = Utils.getMapper().writeValueAsString(identityDocument); String encodedIdentityDocument = Base64.getEncoder().encodeToString(identityDocumentString.getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); PrivateKey privateKey = Crypto.loadPrivateKey(keyProvider.getPrivateKey(0)); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); String signature = Base64.getEncoder().encodeToString(sigGenerator.sign()); SignedIdentityDocument signedIdentityDocument = new SignedIdentityDocument( encodedIdentityDocument, signature, SignedIdentityDocument.DEFAULT_KEY_VERSION, SignedIdentityDocument.DEFAILT_DOCUMENT_VERSION ); return Utils.getMapper().writeValueAsString(signedIdentityDocument); } catch (Exception e) { throw new RuntimeException("Exception generating identity document: " + e.getMessage()); } } }
class IdentityDocumentGenerator { private final NodeRepository nodeRepository; private final Zone zone; private final KeyProvider keyProvider; private final String dnsSuffix; private final String providerService; private final String ztsUrl; public IdentityDocumentGenerator(AthenzProviderServiceConfig config, NodeRepository nodeRepository, Zone zone, KeyProvider keyProvider) { this.nodeRepository = nodeRepository; this.zone = zone; this.keyProvider = keyProvider; this.dnsSuffix = config.certDnsSuffix(); this.providerService = config.serviceName(); this.ztsUrl = config.ztsUrl(); } public String generateSignedIdentityDocument(String hostname) { Node node = nodeRepository.getNode(hostname).orElseThrow(() -> new RuntimeException("Unable to find node " + hostname)); try { IdentityDocument identityDocument = generateIdDocument(node); String identityDocumentString = Utils.getMapper().writeValueAsString(identityDocument); String encodedIdentityDocument = Base64.getEncoder().encodeToString(identityDocumentString.getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); PrivateKey privateKey = Crypto.loadPrivateKey(keyProvider.getPrivateKey(0)); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); String signature = Base64.getEncoder().encodeToString(sigGenerator.sign()); SignedIdentityDocument signedIdentityDocument = new SignedIdentityDocument( encodedIdentityDocument, signature, SignedIdentityDocument.DEFAULT_KEY_VERSION, identityDocument.providerUniqueId.asString(), dnsSuffix, providerService, ztsUrl, SignedIdentityDocument.DEFAILT_DOCUMENT_VERSION ); return Utils.getMapper().writeValueAsString(signedIdentityDocument); } catch (Exception e) { throw new RuntimeException("Exception generating identity document: " + e.getMessage(), e); } } }
Consider use `Optional.ifPresent` in the future
public void getConfig(ConfigserverConfig.Builder builder) { for (String pluginDir : getConfigModelPluginDirs()) { builder.configModelPluginDir(pluginDir); } if (options.sessionLifeTimeSecs().isPresent()) { builder.sessionLifetime(options.sessionLifeTimeSecs().get()); } if (options.zookeeperBarrierTimeout().isPresent()) { builder.zookeeper(new ConfigserverConfig.Zookeeper.Builder().barrierTimeout(options.zookeeperBarrierTimeout().get())); } if (options.rpcPort().isPresent()) { builder.rpcport(options.rpcPort().get()); } if (options.multiTenant().isPresent()) { builder.multitenant(options.multiTenant().get()); } if (options.payloadCompressionType().isPresent()) { builder.payloadCompressionType(ConfigserverConfig.PayloadCompressionType.Enum.valueOf(options.payloadCompressionType().get())); } for (ConfigServer server : getConfigServers()) { ConfigserverConfig.Zookeeperserver.Builder zkBuilder = new ConfigserverConfig.Zookeeperserver.Builder(); zkBuilder.hostname(server.hostName); if (options.zookeeperClientPort().isPresent()) { zkBuilder.port(options.zookeeperClientPort().get()); } builder.zookeeperserver(zkBuilder); } if (options.environment().isPresent()) { builder.environment(options.environment().get()); } if (options.region().isPresent()) { builder.region(options.region().get()); } if (options.system().isPresent()) { builder.environment(options.system().get()); } if (options.defaultFlavor().isPresent()) { builder.defaultFlavor(options.defaultFlavor().get()); } if (options.defaultAdminFlavor().isPresent()) { builder.defaultAdminFlavor(options.defaultAdminFlavor().get()); } if (options.defaultContainerFlavor().isPresent()) { builder.defaultContainerFlavor(options.defaultContainerFlavor().get()); } if (options.defaultContentFlavor().isPresent()) { builder.defaultContentFlavor(options.defaultContentFlavor().get()); } builder.serverId(HostName.getLocalhost()); if (!containerCluster.getHttp().getHttpServer().getConnectorFactories().isEmpty()) { builder.httpport(containerCluster.getHttp().getHttpServer().getConnectorFactories().get(0).getListenPort()); } if (options.useVespaVersionInRequest().isPresent()) { builder.useVespaVersionInRequest(options.useVespaVersionInRequest().get()); } else if (options.multiTenant().isPresent()) { builder.useVespaVersionInRequest(options.multiTenant().get()); } if (options.hostedVespa().isPresent()) { builder.hostedVespa(options.hostedVespa().get()); } if (options.numParallelTenantLoaders().isPresent()) { builder.numParallelTenantLoaders(options.numParallelTenantLoaders().get()); } if (options.dockerRegistry().isPresent()) { builder.dockerRegistry(options.dockerRegistry().get()); } if (options.dockerVespaBaseImage().isPresent()) { builder.dockerVespaBaseImage(options.dockerVespaBaseImage().get()); } if (options.serviceProviderEndpoint().isPresent()) { builder.serviceProviderEndpoint(options.serviceProviderEndpoint().get()); } }
if (options.serviceProviderEndpoint().isPresent()) {
public void getConfig(ConfigserverConfig.Builder builder) { for (String pluginDir : getConfigModelPluginDirs()) { builder.configModelPluginDir(pluginDir); } if (options.sessionLifeTimeSecs().isPresent()) { builder.sessionLifetime(options.sessionLifeTimeSecs().get()); } if (options.zookeeperBarrierTimeout().isPresent()) { builder.zookeeper(new ConfigserverConfig.Zookeeper.Builder().barrierTimeout(options.zookeeperBarrierTimeout().get())); } if (options.rpcPort().isPresent()) { builder.rpcport(options.rpcPort().get()); } if (options.multiTenant().isPresent()) { builder.multitenant(options.multiTenant().get()); } if (options.payloadCompressionType().isPresent()) { builder.payloadCompressionType(ConfigserverConfig.PayloadCompressionType.Enum.valueOf(options.payloadCompressionType().get())); } for (ConfigServer server : getConfigServers()) { ConfigserverConfig.Zookeeperserver.Builder zkBuilder = new ConfigserverConfig.Zookeeperserver.Builder(); zkBuilder.hostname(server.hostName); if (options.zookeeperClientPort().isPresent()) { zkBuilder.port(options.zookeeperClientPort().get()); } builder.zookeeperserver(zkBuilder); } if (options.environment().isPresent()) { builder.environment(options.environment().get()); } if (options.region().isPresent()) { builder.region(options.region().get()); } if (options.system().isPresent()) { builder.environment(options.system().get()); } if (options.defaultFlavor().isPresent()) { builder.defaultFlavor(options.defaultFlavor().get()); } if (options.defaultAdminFlavor().isPresent()) { builder.defaultAdminFlavor(options.defaultAdminFlavor().get()); } if (options.defaultContainerFlavor().isPresent()) { builder.defaultContainerFlavor(options.defaultContainerFlavor().get()); } if (options.defaultContentFlavor().isPresent()) { builder.defaultContentFlavor(options.defaultContentFlavor().get()); } builder.serverId(HostName.getLocalhost()); if (!containerCluster.getHttp().getHttpServer().getConnectorFactories().isEmpty()) { builder.httpport(containerCluster.getHttp().getHttpServer().getConnectorFactories().get(0).getListenPort()); } if (options.useVespaVersionInRequest().isPresent()) { builder.useVespaVersionInRequest(options.useVespaVersionInRequest().get()); } else if (options.multiTenant().isPresent()) { builder.useVespaVersionInRequest(options.multiTenant().get()); } if (options.hostedVespa().isPresent()) { builder.hostedVespa(options.hostedVespa().get()); } if (options.numParallelTenantLoaders().isPresent()) { builder.numParallelTenantLoaders(options.numParallelTenantLoaders().get()); } if (options.dockerRegistry().isPresent()) { builder.dockerRegistry(options.dockerRegistry().get()); } if (options.dockerVespaBaseImage().isPresent()) { builder.dockerVespaBaseImage(options.dockerVespaBaseImage().get()); } if (options.serviceProviderEndpoint().isPresent()) { builder.serviceProviderEndpoint(options.serviceProviderEndpoint().get()); } }
class ConfigserverCluster extends AbstractConfigProducer implements ZookeeperServerConfig.Producer, ConfigserverConfig.Producer, ScoreBoardConfig.Producer, StatisticsConfig.Producer, HealthMonitorConfig.Producer { private final CloudConfigOptions options; private ContainerCluster containerCluster; public ConfigserverCluster(AbstractConfigProducer parent, String subId, CloudConfigOptions options) { super(parent, subId); this.options = options; } public void setContainerCluster(ContainerCluster containerCluster) { this.containerCluster = containerCluster; Environment environment = options.environment().isPresent() ? Environment.from(options.environment().get()) : Environment.defaultEnvironment(); RegionName region = options.region().isPresent() ? RegionName.from(options.region().get()) : RegionName.defaultName(); SystemName system = options.system().isPresent() ? SystemName.from(options.system().get()) : SystemName.defaultSystem(); containerCluster.setZone(new Zone(system, environment, region)); } @Override public void getConfig(ZookeeperServerConfig.Builder builder) { String myhostname = HostName.getLocalhost(); int myid = 0; int i = 0; for (ConfigServer server : getConfigServers()) { if (server.hostName.equals(myhostname)) { myid = i; } builder.server(getZkServer(server, i)); i++; } builder.myid(myid); if (options.zookeeperClientPort().isPresent()) { builder.clientPort(options.zookeeperClientPort().get()); } } @Override private String[] getConfigModelPluginDirs() { if (options.configModelPluginDirs().length > 0) { return options.configModelPluginDirs(); } else { return new String[]{Defaults.getDefaults().underVespaHome("lib/jars/config-models")}; } } private ConfigServer[] getConfigServers() { if (options.allConfigServers().length > 0) { return options.allConfigServers(); } else { return new ConfigServer[]{new ConfigServer(HostName.getLocalhost(), Optional.<Integer>empty()) }; } } private ZookeeperServerConfig.Server.Builder getZkServer(ConfigServer server, int id) { ZookeeperServerConfig.Server.Builder builder = new ZookeeperServerConfig.Server.Builder(); if (options.zookeeperElectionPort().isPresent()) { builder.electionPort(options.zookeeperElectionPort().get()); } if (options.zookeeperQuorumPort().isPresent()) { builder.quorumPort(options.zookeeperQuorumPort().get()); } builder.hostname(server.hostName); builder.id(id); return builder; } @Override public void getConfig(ScoreBoardConfig.Builder builder) { builder.applicationName("configserver"); builder.flushTime(60); builder.step(60); } @Override public void getConfig(StatisticsConfig.Builder builder) { builder.collectionintervalsec(60.0); builder.loggingintervalsec(60.0); } @Override public void getConfig(HealthMonitorConfig.Builder builder) { builder.snapshot_interval(60.0); } }
class ConfigserverCluster extends AbstractConfigProducer implements ZookeeperServerConfig.Producer, ConfigserverConfig.Producer, ScoreBoardConfig.Producer, StatisticsConfig.Producer, HealthMonitorConfig.Producer { private final CloudConfigOptions options; private ContainerCluster containerCluster; public ConfigserverCluster(AbstractConfigProducer parent, String subId, CloudConfigOptions options) { super(parent, subId); this.options = options; } public void setContainerCluster(ContainerCluster containerCluster) { this.containerCluster = containerCluster; Environment environment = options.environment().isPresent() ? Environment.from(options.environment().get()) : Environment.defaultEnvironment(); RegionName region = options.region().isPresent() ? RegionName.from(options.region().get()) : RegionName.defaultName(); SystemName system = options.system().isPresent() ? SystemName.from(options.system().get()) : SystemName.defaultSystem(); containerCluster.setZone(new Zone(system, environment, region)); } @Override public void getConfig(ZookeeperServerConfig.Builder builder) { String myhostname = HostName.getLocalhost(); int myid = 0; int i = 0; for (ConfigServer server : getConfigServers()) { if (server.hostName.equals(myhostname)) { myid = i; } builder.server(getZkServer(server, i)); i++; } builder.myid(myid); if (options.zookeeperClientPort().isPresent()) { builder.clientPort(options.zookeeperClientPort().get()); } } @Override private String[] getConfigModelPluginDirs() { if (options.configModelPluginDirs().length > 0) { return options.configModelPluginDirs(); } else { return new String[]{Defaults.getDefaults().underVespaHome("lib/jars/config-models")}; } } private ConfigServer[] getConfigServers() { if (options.allConfigServers().length > 0) { return options.allConfigServers(); } else { return new ConfigServer[]{new ConfigServer(HostName.getLocalhost(), Optional.<Integer>empty()) }; } } private ZookeeperServerConfig.Server.Builder getZkServer(ConfigServer server, int id) { ZookeeperServerConfig.Server.Builder builder = new ZookeeperServerConfig.Server.Builder(); if (options.zookeeperElectionPort().isPresent()) { builder.electionPort(options.zookeeperElectionPort().get()); } if (options.zookeeperQuorumPort().isPresent()) { builder.quorumPort(options.zookeeperQuorumPort().get()); } builder.hostname(server.hostName); builder.id(id); return builder; } @Override public void getConfig(ScoreBoardConfig.Builder builder) { builder.applicationName("configserver"); builder.flushTime(60); builder.step(60); } @Override public void getConfig(StatisticsConfig.Builder builder) { builder.collectionintervalsec(60.0); builder.loggingintervalsec(60.0); } @Override public void getConfig(HealthMonitorConfig.Builder builder) { builder.snapshot_interval(60.0); } }
I prefer having all methods called from the constructor as static
public AthenzIdentityProvider(IdentityConfig config, ServiceProviderApi serviceProviderApi, AthenzService athenzService) throws IOException { KeyPair keyPair = createKeyPair(); String signedIdentityDocument = serviceProviderApi.getSignedIdentityDocument(); this.athenzUrl = getZtsEndpoint(signedIdentityDocument); dnsSuffix = getDnsSuffix(signedIdentityDocument); providerUniqueId = getProviderUniqueId(signedIdentityDocument); providerServiceName = getProviderServiceName(signedIdentityDocument); InstanceRegisterInformation instanceRegisterInformation = new InstanceRegisterInformation( providerServiceName, config.domain(), config.serviceName(), signedIdentityDocument, createCSR(keyPair, config), true ); instanceIdentity = athenzService.sendInstanceRegisterRequest(instanceRegisterInformation, athenzUrl); }
this.athenzUrl = getZtsEndpoint(signedIdentityDocument);
public AthenzIdentityProvider(IdentityConfig config, ServiceProviderApi serviceProviderApi, AthenzService athenzService) throws IOException { KeyPair keyPair = createKeyPair(); String signedIdentityDocument = serviceProviderApi.getSignedIdentityDocument(); this.athenzUrl = getZtsEndpoint(signedIdentityDocument); dnsSuffix = getDnsSuffix(signedIdentityDocument); providerUniqueId = getProviderUniqueId(signedIdentityDocument); providerServiceName = getProviderServiceName(signedIdentityDocument); InstanceRegisterInformation instanceRegisterInformation = new InstanceRegisterInformation( providerServiceName, config.domain(), config.serviceName(), signedIdentityDocument, createCSR(keyPair, config), true ); instanceIdentity = athenzService.sendInstanceRegisterRequest(instanceRegisterInformation, athenzUrl); }
class AthenzIdentityProvider extends AbstractComponent { private InstanceIdentity instanceIdentity; private final String athenzUrl; private final String dnsSuffix; private final String providerUniqueId; private final String providerServiceName; @Inject public AthenzIdentityProvider(IdentityConfig config, ConfigserverConfig configserverConfig) throws IOException { this(config, new ServiceProviderApi(configserverConfig.serviceProviderEndpoint()), new AthenzService()); } private String getProviderUniqueId(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "provider-unique-id"); } private String getDnsSuffix(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "dns-suffix"); } private String getProviderServiceName(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "provider-service"); } private String getZtsEndpoint(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "zts-endpoint"); } private String getJsonNode(String jsonString, String path) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(jsonString); return jsonNode.get(path).asText(); } private KeyPair createKeyPair() { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); return kpg.generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } } private String createCSR(KeyPair keyPair, IdentityConfig identityConfig) throws IOException { try { GeneralName[] sanDnsNames = new GeneralName[]{ new GeneralName(GeneralName.dNSName, String.format("%s.%s.%s", identityConfig.serviceName(), identityConfig.domain().replace(".", "-"), dnsSuffix)), new GeneralName(GeneralName.dNSName, String.format("%s.instanceid.athenz.%s", providerUniqueId, dnsSuffix)) }; return Crypto.generateX509CSR(keyPair.getPrivate(), keyPair.getPublic(), String.format("CN=%s.%s", identityConfig.domain(), identityConfig.serviceName()), sanDnsNames); } catch (OperatorCreationException e) { e.printStackTrace(); throw new RuntimeException(e); } } public String getNToken() { return instanceIdentity.getServiceToken(); } public String getX509Cert() { return instanceIdentity.getX509Certificate(); } }
class AthenzIdentityProvider extends AbstractComponent { private InstanceIdentity instanceIdentity; private final String athenzUrl; private final String dnsSuffix; private final String providerUniqueId; private final String providerServiceName; @Inject public AthenzIdentityProvider(IdentityConfig config, ConfigserverConfig configserverConfig) throws IOException { this(config, new ServiceProviderApi(configserverConfig.serviceProviderEndpoint()), new AthenzService()); } private String getProviderUniqueId(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "provider-unique-id"); } private String getDnsSuffix(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "dns-suffix"); } private String getProviderServiceName(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "provider-service"); } private String getZtsEndpoint(String signedIdentityDocument) throws IOException { return getJsonNode(signedIdentityDocument, "zts-endpoint"); } private String getJsonNode(String jsonString, String path) throws IOException { ObjectMapper mapper = new ObjectMapper(); JsonNode jsonNode = mapper.readTree(jsonString); return jsonNode.get(path).asText(); } private KeyPair createKeyPair() { try { KeyPairGenerator kpg = KeyPairGenerator.getInstance("RSA"); return kpg.generateKeyPair(); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); throw new RuntimeException(e); } } private String createCSR(KeyPair keyPair, IdentityConfig identityConfig) throws IOException { try { GeneralName[] sanDnsNames = new GeneralName[]{ new GeneralName(GeneralName.dNSName, String.format("%s.%s.%s", identityConfig.serviceName(), identityConfig.domain().replace(".", "-"), dnsSuffix)), new GeneralName(GeneralName.dNSName, String.format("%s.instanceid.athenz.%s", providerUniqueId, dnsSuffix)) }; return Crypto.generateX509CSR(keyPair.getPrivate(), keyPair.getPublic(), String.format("CN=%s.%s", identityConfig.domain(), identityConfig.serviceName()), sanDnsNames); } catch (OperatorCreationException e) { e.printStackTrace(); throw new RuntimeException(e); } } public String getNToken() { return instanceIdentity.getServiceToken(); } public String getX509Cert() { return instanceIdentity.getX509Certificate(); } }
Replace `System.out` with log statement
InstanceIdentity sendInstanceRegisterRequest(InstanceRegisterInformation instanceRegisterInformation, String athenzUrl) { try(CloseableHttpClient client = HttpClientBuilder.create().build()) { ObjectMapper objectMapper = new ObjectMapper(); System.out.println(objectMapper.writeValueAsString(instanceRegisterInformation)); HttpUriRequest postRequest = RequestBuilder.post() .setUri(athenzUrl + "/instance") .setEntity(new StringEntity(objectMapper.writeValueAsString(instanceRegisterInformation), ContentType.APPLICATION_JSON)) .build(); CloseableHttpResponse response = client.execute(postRequest); if(HttpStatus.isSuccess(response.getStatusLine().getStatusCode())) { return objectMapper.readValue(response.getEntity().getContent(), InstanceIdentity.class); } else { String s = EntityUtils.toString(response.getEntity()); System.out.println("s = " + s); throw new RuntimeException(response.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
System.out.println(objectMapper.writeValueAsString(instanceRegisterInformation));
InstanceIdentity sendInstanceRegisterRequest(InstanceRegisterInformation instanceRegisterInformation, String athenzUrl) { try(CloseableHttpClient client = HttpClientBuilder.create().build()) { ObjectMapper objectMapper = new ObjectMapper(); System.out.println(objectMapper.writeValueAsString(instanceRegisterInformation)); HttpUriRequest postRequest = RequestBuilder.post() .setUri(athenzUrl + "/instance") .setEntity(new StringEntity(objectMapper.writeValueAsString(instanceRegisterInformation), ContentType.APPLICATION_JSON)) .build(); CloseableHttpResponse response = client.execute(postRequest); if(HttpStatus.isSuccess(response.getStatusLine().getStatusCode())) { return objectMapper.readValue(response.getEntity().getContent(), InstanceIdentity.class); } else { String s = EntityUtils.toString(response.getEntity()); System.out.println("s = " + s); throw new RuntimeException(response.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
class AthenzService { /** * Send instance register request to ZTS, get InstanceIdentity * * @param instanceRegisterInformation */ }
class AthenzService { /** * Send instance register request to ZTS, get InstanceIdentity * * @param instanceRegisterInformation */ }
Same as above
InstanceIdentity sendInstanceRegisterRequest(InstanceRegisterInformation instanceRegisterInformation, String athenzUrl) { try(CloseableHttpClient client = HttpClientBuilder.create().build()) { ObjectMapper objectMapper = new ObjectMapper(); System.out.println(objectMapper.writeValueAsString(instanceRegisterInformation)); HttpUriRequest postRequest = RequestBuilder.post() .setUri(athenzUrl + "/instance") .setEntity(new StringEntity(objectMapper.writeValueAsString(instanceRegisterInformation), ContentType.APPLICATION_JSON)) .build(); CloseableHttpResponse response = client.execute(postRequest); if(HttpStatus.isSuccess(response.getStatusLine().getStatusCode())) { return objectMapper.readValue(response.getEntity().getContent(), InstanceIdentity.class); } else { String s = EntityUtils.toString(response.getEntity()); System.out.println("s = " + s); throw new RuntimeException(response.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
System.out.println("s = " + s);
InstanceIdentity sendInstanceRegisterRequest(InstanceRegisterInformation instanceRegisterInformation, String athenzUrl) { try(CloseableHttpClient client = HttpClientBuilder.create().build()) { ObjectMapper objectMapper = new ObjectMapper(); System.out.println(objectMapper.writeValueAsString(instanceRegisterInformation)); HttpUriRequest postRequest = RequestBuilder.post() .setUri(athenzUrl + "/instance") .setEntity(new StringEntity(objectMapper.writeValueAsString(instanceRegisterInformation), ContentType.APPLICATION_JSON)) .build(); CloseableHttpResponse response = client.execute(postRequest); if(HttpStatus.isSuccess(response.getStatusLine().getStatusCode())) { return objectMapper.readValue(response.getEntity().getContent(), InstanceIdentity.class); } else { String s = EntityUtils.toString(response.getEntity()); System.out.println("s = " + s); throw new RuntimeException(response.toString()); } } catch (IOException e) { throw new RuntimeException(e); } }
class AthenzService { /** * Send instance register request to ZTS, get InstanceIdentity * * @param instanceRegisterInformation */ }
class AthenzService { /** * Send instance register request to ZTS, get InstanceIdentity * * @param instanceRegisterInformation */ }
Use fake domains in tests, e.g. "issues.tld".
public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.com/" + propertyId.id()); }
return URI.create("www.issues.com/" + propertyId.id());
public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.tld/" + propertyId.id()); }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.com/" + propertyId.id()); } @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.com/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.tld/" + propertyId.id()); } @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.tld/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
Same as above.
public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.com/" + propertyId.id()); }
return URI.create("www.contacts.com/" + propertyId.id());
public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.tld/" + propertyId.id()); }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.com/" + propertyId.id()); } @Override @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.com/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.tld/" + propertyId.id()); } @Override @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.tld/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
Same as above.
public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.com/" + propertyId.id()); }
return URI.create("www.properties.com/" + propertyId.id());
public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.tld/" + propertyId.id()); }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.com/" + propertyId.id()); } @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.com/" + propertyId.id()); } @Override public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.tld/" + propertyId.id()); } @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.tld/" + propertyId.id()); } @Override public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
Sure.
public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.com/" + propertyId.id()); }
return URI.create("www.issues.com/" + propertyId.id());
public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.tld/" + propertyId.id()); }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.com/" + propertyId.id()); } @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.com/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.tld/" + propertyId.id()); } @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.tld/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
Yes master.
public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.com/" + propertyId.id()); }
return URI.create("www.contacts.com/" + propertyId.id());
public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.tld/" + propertyId.id()); }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.com/" + propertyId.id()); } @Override @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.com/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.tld/" + propertyId.id()); } @Override @Override public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.tld/" + propertyId.id()); } public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
Right away!
public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.com/" + propertyId.id()); }
return URI.create("www.properties.com/" + propertyId.id());
public URI propertyUri(PropertyId propertyId) { return URI.create("www.properties.tld/" + propertyId.id()); }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.com/" + propertyId.id()); } @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.com/" + propertyId.id()); } @Override public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
class MockOrganization implements Organization { private final Clock clock; private final AtomicLong counter; private final HashMap<IssueId, WrappedIssue> issues; private final HashMap<PropertyId, PropertyInfo> properties; @Inject @SuppressWarnings("unused") public MockOrganization() { this(Clock.systemUTC()); } public MockOrganization(Clock clock) { this.clock = clock; counter = new AtomicLong(); issues = new HashMap<>(); properties = new HashMap<>(); } @Override public IssueId file(Issue issue) { IssueId issueId = IssueId.from("" + counter.incrementAndGet()); issues.put(issueId, new WrappedIssue(issue)); return issueId; } @Override public Optional<IssueId> findBySimilarity(Issue issue) { return issues.entrySet().stream() .filter(entry -> entry.getValue().issue.summary().equals(issue.summary())) .findFirst() .map(Map.Entry::getKey); } @Override public void update(IssueId issueId, String description) { touch(issueId); } @Override public void commentOn(IssueId issueId, String comment) { touch(issueId); } @Override public boolean isOpen(IssueId issueId) { return issues.get(issueId).open; } @Override public boolean isActive(IssueId issueId, Duration maxInactivity) { return issues.get(issueId).updated.isAfter(clock.instant().minus(maxInactivity)); } @Override public Optional<User> assigneeOf(IssueId issueId) { return Optional.ofNullable(issues.get(issueId).assignee); } @Override public boolean reassign(IssueId issueId, User assignee) { issues.get(issueId).assignee = assignee; touch(issueId); return true; } @Override public List<? extends List<? extends User>> contactsFor(PropertyId propertyId) { return properties.get(propertyId).contacts; } @Override public URI issueCreationUri(PropertyId propertyId) { return URI.create("www.issues.tld/" + propertyId.id()); } @Override public URI contactsUri(PropertyId propertyId) { return URI.create("www.contacts.tld/" + propertyId.id()); } @Override public void close(IssueId issueId) { issues.get(issueId).open = false; touch(issueId); } public void setDefaultAssigneeFor(PropertyId propertyId, User defaultAssignee) { properties.get(propertyId).defaultAssignee = defaultAssignee; } public void setContactsFor(PropertyId propertyId, List<List<User>> contacts) { properties.get(propertyId).contacts = contacts; } public void addProperty(PropertyId propertyId) { properties.put(propertyId, new PropertyInfo()); } private void touch(IssueId issueId) { issues.get(issueId).updated = clock.instant(); } private class WrappedIssue { private Issue issue; private Instant updated; private boolean open; private User assignee; private WrappedIssue(Issue issue) { this.issue = issue; updated = clock.instant(); open = true; assignee = issue.assignee().orElse(properties.get(issue.propertyId()).defaultAssignee); } } private class PropertyInfo { private User defaultAssignee; private List<List<User>> contacts = Collections.emptyList(); } }
So something's not right ...
private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.isSuccess() && ! productionUpgradeHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (next != null && isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().equals(nextSuccess.revision())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; }
if ( ! previous.isSuccess() &&
private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent()) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (next != null && isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().equals(nextSuccess.revision())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (deploymentComplete(application)) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application, report.jobType())) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** Returns whether all production zones listed in deployment spec last were successful on the currently deploying change. */ private boolean deploymentComplete(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; return order.jobsFrom(application.deploymentSpec()).stream() .filter(JobType::isProduction) .allMatch(jobType -> application.deploymentJobs().isSuccessful(application.deploying().get(), jobType)); } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, (change instanceof Change.VersionChange ? "Upgrading to " + ((Change.VersionChange)change).version() : "Deploying " + change)); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().isPresent() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this job just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application, JobType jobType) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); return (jobStatus != null && jobStatus.firstFailing().get().at().isAfter(clock.instant().minus(Duration.ofSeconds(10)))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to put the job at the front of the build system queue (or the back) * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (jobType.isProduction() && isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (jobs.stream().anyMatch(JobType::isProduction) && isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionUpgradeHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (deploymentComplete(application)) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application, report.jobType())) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** Returns whether all production zones listed in deployment spec last were successful on the currently deploying change. */ private boolean deploymentComplete(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; return order.jobsFrom(application.deploymentSpec()).stream() .filter(JobType::isProduction) .allMatch(jobType -> application.deploymentJobs().isSuccessful(application.deploying().get(), jobType)); } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, (change instanceof Change.VersionChange ? "Upgrading to " + ((Change.VersionChange)change).version() : "Deploying " + change)); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().isPresent() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this job just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application, JobType jobType) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); return (jobStatus != null && jobStatus.firstFailing().get().at().isAfter(clock.instant().minus(Duration.ofSeconds(10)))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to put the job at the front of the build system queue (or the back) * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (jobType.isProduction() && isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (jobs.stream().anyMatch(JobType::isProduction) && isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
Should we have a delimiter between multiple, individual errors, or are they already in a "self-delimiting" format?
private String getUnconsumedErrors() { StringBuilder errors = null; Deque<RoutingNode> stack = new ArrayDeque<>(); stack.push(this); while (!stack.isEmpty()) { RoutingNode node = stack.pop(); if (node.reply != null) { for (int i = 0; i < node.reply.getNumErrors(); ++i) { Error error = node.reply.getError(i); int errorCode = error.getCode(); RoutingNode it = node; while (it != null) { if (it.routingContext != null && it.routingContext.isConsumableError(errorCode)) { errorCode = ErrorCode.NONE; break; } it = it.parent; } if (errorCode != ErrorCode.NONE) { if (errors == null) { errors = new StringBuilder(); } errors.append(error.toString()); shouldRetry = resender != null && resender.canRetry(errorCode); if (!shouldRetry) { return errors.toString(); } } } } else { for (RoutingNode child : node.children) { stack.push(child); } } } return errors != null ? errors.toString() : null; }
errors.append(error.toString());
private String getUnconsumedErrors() { StringBuilder errors = null; Deque<RoutingNode> stack = new ArrayDeque<>(); stack.push(this); while (!stack.isEmpty()) { RoutingNode node = stack.pop(); if (node.reply != null) { for (int i = 0; i < node.reply.getNumErrors(); ++i) { Error error = node.reply.getError(i); int errorCode = error.getCode(); RoutingNode it = node; while (it != null) { if (it.routingContext != null && it.routingContext.isConsumableError(errorCode)) { errorCode = ErrorCode.NONE; break; } it = it.parent; } if (errorCode != ErrorCode.NONE) { if (errors == null) { errors = new StringBuilder(); } else { errors.append("\n"); } errors.append(error.toString()); shouldRetry = resender != null && resender.canRetry(errorCode); if (!shouldRetry) { return errors.toString(); } } } } else { for (RoutingNode child : node.children) { stack.push(child); } } } return errors != null ? errors.toString() : null; }
class is implemented so * that it passes a null reply to the handler to notify the discard. * * @param mbus The message bus on which we are running. * @param net The network layer we are to transmit through. * @param resender The resender to schedule with. * @param handler The handler to receive the final reply. * @param msg The message being sent. */ public RoutingNode(MessageBus mbus, Network net, Resender resender, ReplyHandler handler, Message msg) { this.mbus = mbus; this.net = net; this.resender = resender; this.handler = handler; this.msg = msg; this.trace = new Trace(msg.getTrace().getLevel()); this.route = msg.getRoute(); this.parent = null; if (route != null) { routeMetrics = mbus.getMetrics().getRouteMetrics(route); } }
class is implemented so * that it passes a null reply to the handler to notify the discard. * * @param mbus The message bus on which we are running. * @param net The network layer we are to transmit through. * @param resender The resender to schedule with. * @param handler The handler to receive the final reply. * @param msg The message being sent. */ public RoutingNode(MessageBus mbus, Network net, Resender resender, ReplyHandler handler, Message msg) { this.mbus = mbus; this.net = net; this.resender = resender; this.handler = handler; this.msg = msg; this.trace = new Trace(msg.getTrace().getLevel()); this.route = msg.getRoute(); this.parent = null; if (route != null) { routeMetrics = mbus.getMetrics().getRouteMetrics(route); } }
This code should be in the Indentity, not in ContainerCluster
public void getConfig(IdentityConfig.Builder builder) { if (identity != null) { String cfgHostName = getRoot().getDeployState().getProperties() .configServerSpecs().stream().findFirst().map(ConfigServerSpec::getHostName) .orElse(""); builder.loadBalancerAddress(cfgHostName); identity.getConfig(builder); } }
if (identity != null) {
public void getConfig(IdentityConfig.Builder builder) { if (identity != null) { String cfgHostName = getRoot().getDeployState().getProperties() .configServerSpecs().stream().findFirst().map(ConfigServerSpec::getHostName) .orElse(""); builder.loadBalancerAddress(cfgHostName); identity.getConfig(builder); } }
class MbusParams { final Double maxConcurrentFactor; final Double documentExpansionFactor; final Integer containerCoreMemory; public MbusParams(Double maxConcurrentFactor, Double documentExpansionFactor, Integer containerCoreMemory) { this.maxConcurrentFactor = maxConcurrentFactor; this.documentExpansionFactor = documentExpansionFactor; this.containerCoreMemory = containerCoreMemory; } }
class MbusParams { final Double maxConcurrentFactor; final Double documentExpansionFactor; final Integer containerCoreMemory; public MbusParams(Double maxConcurrentFactor, Double documentExpansionFactor, Integer containerCoreMemory) { this.maxConcurrentFactor = maxConcurrentFactor; this.documentExpansionFactor = documentExpansionFactor; this.containerCoreMemory = containerCoreMemory; } }
Ignore this, looked at single commit by itself :)
private String getUnconsumedErrors() { StringBuilder errors = null; Deque<RoutingNode> stack = new ArrayDeque<>(); stack.push(this); while (!stack.isEmpty()) { RoutingNode node = stack.pop(); if (node.reply != null) { for (int i = 0; i < node.reply.getNumErrors(); ++i) { Error error = node.reply.getError(i); int errorCode = error.getCode(); RoutingNode it = node; while (it != null) { if (it.routingContext != null && it.routingContext.isConsumableError(errorCode)) { errorCode = ErrorCode.NONE; break; } it = it.parent; } if (errorCode != ErrorCode.NONE) { if (errors == null) { errors = new StringBuilder(); } errors.append(error.toString()); shouldRetry = resender != null && resender.canRetry(errorCode); if (!shouldRetry) { return errors.toString(); } } } } else { for (RoutingNode child : node.children) { stack.push(child); } } } return errors != null ? errors.toString() : null; }
errors.append(error.toString());
private String getUnconsumedErrors() { StringBuilder errors = null; Deque<RoutingNode> stack = new ArrayDeque<>(); stack.push(this); while (!stack.isEmpty()) { RoutingNode node = stack.pop(); if (node.reply != null) { for (int i = 0; i < node.reply.getNumErrors(); ++i) { Error error = node.reply.getError(i); int errorCode = error.getCode(); RoutingNode it = node; while (it != null) { if (it.routingContext != null && it.routingContext.isConsumableError(errorCode)) { errorCode = ErrorCode.NONE; break; } it = it.parent; } if (errorCode != ErrorCode.NONE) { if (errors == null) { errors = new StringBuilder(); } else { errors.append("\n"); } errors.append(error.toString()); shouldRetry = resender != null && resender.canRetry(errorCode); if (!shouldRetry) { return errors.toString(); } } } } else { for (RoutingNode child : node.children) { stack.push(child); } } } return errors != null ? errors.toString() : null; }
class is implemented so * that it passes a null reply to the handler to notify the discard. * * @param mbus The message bus on which we are running. * @param net The network layer we are to transmit through. * @param resender The resender to schedule with. * @param handler The handler to receive the final reply. * @param msg The message being sent. */ public RoutingNode(MessageBus mbus, Network net, Resender resender, ReplyHandler handler, Message msg) { this.mbus = mbus; this.net = net; this.resender = resender; this.handler = handler; this.msg = msg; this.trace = new Trace(msg.getTrace().getLevel()); this.route = msg.getRoute(); this.parent = null; if (route != null) { routeMetrics = mbus.getMetrics().getRouteMetrics(route); } }
class is implemented so * that it passes a null reply to the handler to notify the discard. * * @param mbus The message bus on which we are running. * @param net The network layer we are to transmit through. * @param resender The resender to schedule with. * @param handler The handler to receive the final reply. * @param msg The message being sent. */ public RoutingNode(MessageBus mbus, Network net, Resender resender, ReplyHandler handler, Message msg) { this.mbus = mbus; this.net = net; this.resender = resender; this.handler = handler; this.msg = msg; this.trace = new Trace(msg.getTrace().getLevel()); this.route = msg.getRoute(); this.parent = null; if (route != null) { routeMetrics = mbus.getMetrics().getRouteMetrics(route); } }
If the class is available on the classpath, use `com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl.class.getName()` instead
public Identity(String domain, String service) { super("com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl"); this.domain = domain; this.service = service; }
super("com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl");
public Identity(String domain, String service) { super("com.yahoo.container.jdisc.athenz.impl.AthenzIdentityProviderImpl"); this.domain = domain; this.service = service; }
class Identity extends SimpleComponent implements IdentityConfig.Producer { private final String domain; private final String service; @Override public void getConfig(IdentityConfig.Builder builder) { builder.domain(domain); builder.service(service); } }
class Identity extends SimpleComponent implements IdentityConfig.Producer { private final String domain; private final String service; @Override public void getConfig(IdentityConfig.Builder builder) { builder.domain(domain); builder.service(service); } }
This feels wrong to me, I don't know why this was here already, but I would've expected this check to be in `setReady()`. Its strange that an `inactive`/`reserved` node can be denied changing to `dirty` because HW failure/divergence, meanwhile denying changing to `ready` seems reasonable. Its fine by me since the HW failure check was here already. @hakonhall / @mpolden have any opinion on this?
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent())
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
This method is only called from the REST API, as a manual operation. In that case it can only be moved from provisioned, failed or parked (the condition above this one) and it doesn't make sense to move a node from those states if it has hardware failure.
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent())
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
> as a manual operation and by Chef, right?
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent())
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
Looks like it, but only if the node is one of the allowed states.
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent())
public Node setDirty(String hostname) { Node nodeToDirty = getNode(hostname, Node.State.provisioned, Node.State.failed, Node.State.parked).orElseThrow(() -> new IllegalArgumentException("Could not deallocate " + hostname + ": No such node in the provisioned, failed or parked state")); if (nodeToDirty.status().hardwareFailureDescription().isPresent() || nodeToDirty.status().hardwareDivergence().isPresent()) throw new IllegalArgumentException("Could not deallocate " + hostname + ": It has a hardware failure/spec divergence"); return setDirty(nodeToDirty); }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
class NodeRepository extends AbstractComponent { private final CuratorDatabaseClient db; private final Curator curator; private final Clock clock; private final NodeFlavors flavors; private final NameResolver nameResolver; private final DockerImage dockerImage; /** * Creates a node repository form a zookeeper provider. * This will use the system time to make time-sensitive decisions */ @Inject public NodeRepository(NodeRepositoryConfig config, NodeFlavors flavors, Curator curator, Zone zone) { this(flavors, curator, Clock.systemUTC(), zone, new DnsNameResolver(), new DockerImage(config.dockerImage())); } /** * Creates a node repository form a zookeeper provider and a clock instance * which will be used for time-sensitive decisions. */ public NodeRepository(NodeFlavors flavors, Curator curator, Clock clock, Zone zone, NameResolver nameResolver, DockerImage dockerImage) { this.db = new CuratorDatabaseClient(flavors, curator, clock, zone); this.curator = curator; this.clock = clock; this.flavors = flavors; this.nameResolver = nameResolver; this.dockerImage = dockerImage; for (Node.State state : Node.State.values()) db.writeTo(state, db.getNodes(state), Agent.system, Optional.empty()); } /** Returns the curator database client used by this */ public CuratorDatabaseClient database() { return db; } /** Returns the Docker image to use for nodes in this */ public DockerImage dockerImage() { return dockerImage; } /** @return The name resolver used to resolve hostname and ip addresses */ public NameResolver nameResolver() { return nameResolver; } /** * Finds and returns the node with the hostname in any of the given states, or empty if not found * * @param hostname the full host name of the node * @param inState the states the node may be in. If no states are given, it will be returned from any state * @return the node, or empty if it was not found in any of the given states */ public Optional<Node> getNode(String hostname, Node.State ... inState) { return db.getNode(hostname, inState); } /** * Returns all nodes in any of the given states. * * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(Node.State ... inState) { return db.getNodes(inState).stream().collect(Collectors.toList()); } /** * Finds and returns the nodes of the given type in any of the given states. * * @param type the node type to return * @param inState the states to return nodes from. If no states are given, all nodes of the given type are returned * @return the node, or empty if it was not found in any of the given states */ public List<Node> getNodes(NodeType type, Node.State ... inState) { return db.getNodes(inState).stream().filter(node -> node.type().equals(type)).collect(Collectors.toList()); } /** * Finds and returns all nodes that are children of the given parent node * * @param hostname Parent hostname * @return List of child nodes */ public List<Node> getChildNodes(String hostname) { return db.getNodes().stream() .filter(node -> node.parentHostname() .map(parentHostname -> parentHostname.equals(hostname)) .orElse(false)) .collect(Collectors.toList()); } public List<Node> getNodes(ApplicationId id, Node.State ... inState) { return db.getNodes(id, inState); } public List<Node> getInactive() { return db.getNodes(Node.State.inactive); } public List<Node> getFailed() { return db.getNodes(Node.State.failed); } /** * Returns a set of nodes that should be trusted by the given node. */ private NodeAcl getNodeAcl(Node node, NodeList candidates) { Set<Node> trustedNodes = new TreeSet<>(Comparator.comparing(Node::hostname)); Set<String> trustedNetworks = new HashSet<>(); node.allocation().ifPresent(allocation -> trustedNodes.addAll(candidates.owner(allocation.owner()).asList())); trustedNodes.addAll(getConfigNodes()); switch (node.type()) { case tenant: trustedNodes.addAll(candidates.parentNodes(trustedNodes).asList()); trustedNodes.addAll(candidates.nodeType(NodeType.proxy).asList()); if (node.state() == Node.State.ready) { trustedNodes.addAll(candidates.nodeType(NodeType.tenant).asList()); } break; case config: trustedNodes.addAll(candidates.asList()); break; case proxy: break; case host: trustedNetworks.add("172.17.0.0/16"); break; default: throw new IllegalArgumentException( String.format("Don't know how to create ACL for node [hostname=%s type=%s]", node.hostname(), node.type())); } return new NodeAcl(node, trustedNodes, trustedNetworks); } /** * Creates a list of node ACLs which identify which nodes the given node should trust * * @param node Node for which to generate ACLs * @param children Return ACLs for the children of the given node (e.g. containers on a Docker host) * @return List of node ACLs */ public List<NodeAcl> getNodeAcls(Node node, boolean children) { NodeList candidates = new NodeList(getNodes()); if (children) { return candidates.childNodes(node).asList().stream() .map(childNode -> getNodeAcl(childNode, candidates)) .collect(Collectors.collectingAndThen(Collectors.toList(), Collections::unmodifiableList)); } else { return Collections.singletonList(getNodeAcl(node, candidates)); } } /** Get config node by hostname */ public Optional<Node> getConfigNode(String hostname) { return getConfigNodes().stream() .filter(n -> hostname.equals(n.hostname())) .findFirst(); } /** Get default flavor override for an application, if present. */ public Optional<String> getDefaultFlavorOverride(ApplicationId applicationId) { return db.getDefaultFlavorForApplication(applicationId); } public NodeFlavors getAvailableFlavors() { return flavors; } /** Creates a new node object, without adding it to the node repo. If no IP address is given, it will be resolved */ public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Set<String> additionalIpAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { if (ipAddresses.isEmpty()) { ipAddresses = nameResolver.getAllByNameOrThrow(hostname); } return Node.create(openStackId, ImmutableSet.copyOf(ipAddresses), additionalIpAddresses, hostname, parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Set<String> ipAddresses, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, ipAddresses, Collections.emptySet(), parentHostname, flavor, type); } public Node createNode(String openStackId, String hostname, Optional<String> parentHostname, Flavor flavor, NodeType type) { return createNode(openStackId, hostname, Collections.emptySet(), parentHostname, flavor, type); } /** Adds a list of newly created docker container nodes to the node repository as <i>reserved</i> nodes */ public List<Node> addDockerNodes(List<Node> nodes) { for (Node node : nodes) { if (!node.flavor().getType().equals(Flavor.Type.DOCKER_CONTAINER)) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": This is not a docker node"); } if (!node.allocation().isPresent()) { throw new IllegalArgumentException("Cannot add " + node.hostname() + ": Docker containers needs to be allocated"); } Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodesInState(nodes, Node.State.reserved); } } /** Adds a list of (newly created) nodes to the node repository as <i>provisioned</i> nodes */ public List<Node> addNodes(List<Node> nodes) { for (Node node : nodes) { Optional<Node> existing = getNode(node.hostname()); if (existing.isPresent()) throw new IllegalArgumentException("Cannot add " + node.hostname() + ": A node with this name already exists"); } try (Mutex lock = lockUnallocated()) { return db.addNodes(nodes); } } /** Sets a list of nodes ready and returns the nodes in the ready state */ public List<Node> setReady(List<Node> nodes) { for (Node node : nodes) if (node.state() != Node.State.dirty) throw new IllegalArgumentException("Can not set " + node + " ready. It is not dirty."); try (Mutex lock = lockUnallocated()) { return db.writeTo(Node.State.ready, nodes, Agent.system, Optional.empty()); } } public Node setReady(String hostname) { Node nodeToReady = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to ready: Node not found")); if (nodeToReady.state() == Node.State.ready) return nodeToReady; return setReady(Collections.singletonList(nodeToReady)).get(0); } /** Reserve nodes. This method does <b>not</b> lock the node repository */ public List<Node> reserve(List<Node> nodes) { return db.writeTo(Node.State.reserved, nodes, Agent.application, Optional.empty()); } /** Activate nodes. This method does <b>not</b> lock the node repository */ public List<Node> activate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.active, nodes, Agent.application, Optional.empty(), transaction); } /** * Sets a list of nodes to have their allocation removable (active to inactive) in the node repository. * * @param application the application the nodes belong to * @param nodes the nodes to make removable. These nodes MUST be in the active state. */ public void setRemovable(ApplicationId application, List<Node> nodes) { try (Mutex lock = lock(application)) { List<Node> removableNodes = nodes.stream().map(node -> node.with(node.allocation().get().removable())) .collect(Collectors.toList()); write(removableNodes); } } public void deactivate(ApplicationId application, NestedTransaction transaction) { try (Mutex lock = lock(application)) { db.writeTo(Node.State.inactive, db.getNodes(application, Node.State.reserved, Node.State.active), Agent.application, Optional.empty(), transaction ); } } /** * Deactivates these nodes in a transaction and returns * the nodes in the new state which will hold if the transaction commits. * This method does <b>not</b> lock */ public List<Node> deactivate(List<Node> nodes, NestedTransaction transaction) { return db.writeTo(Node.State.inactive, nodes, Agent.application, Optional.empty(), transaction); } /** Move nodes to the dirty state */ public List<Node> setDirty(List<Node> nodes) { return performOn(NodeListFilter.from(nodes), this::setDirty); } /** Move a single node to the dirty state */ public Node setDirty(Node node) { return db.writeTo(Node.State.dirty, node, Agent.system, Optional.empty()); } /** * Set a node dirty, which is in the provisioned, failed or parked state. * Use this to clean newly provisioned nodes or to recycle failed nodes which have been repaired or put on hold. * * @throws IllegalArgumentException if the node has hardware failure */ /** * Fails this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node fail(String hostname, Agent agent, String reason) { return move(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Fails all the nodes that are children of hostname before finally failing the hostname itself. * * @return List of all the failed nodes in their new state */ public List<Node> failRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.failed, agent, Optional.of(reason)); } /** * Parks this node and returns it in its new state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node park(String hostname, Agent agent, String reason) { return move(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Parks all the nodes that are children of hostname before finally parking the hostname itself. * * @return List of all the parked nodes in their new state */ public List<Node> parkRecursively(String hostname, Agent agent, String reason) { return moveRecursively(hostname, Node.State.parked, agent, Optional.of(reason)); } /** * Moves a previously failed or parked node back to the active state. * * @return the node in its new state * @throws NoSuchNodeException if the node is not found */ public Node reactivate(String hostname, Agent agent) { return move(hostname, Node.State.active, agent, Optional.empty()); } private List<Node> moveRecursively(String hostname, Node.State toState, Agent agent, Optional<String> reason) { List<Node> moved = getChildNodes(hostname).stream() .map(child -> move(child, toState, agent, reason)) .collect(Collectors.toList()); moved.add(move(hostname, toState, agent, reason)); return moved; } private Node move(String hostname, Node.State toState, Agent agent, Optional<String> reason) { Node node = getNode(hostname).orElseThrow(() -> new NoSuchNodeException("Could not move " + hostname + " to " + toState + ": Node not found")); return move(node, toState, agent, reason); } private Node move(Node node, Node.State toState, Agent agent, Optional<String> reason) { if (toState == Node.State.active && ! node.allocation().isPresent()) throw new IllegalArgumentException("Could not set " + node.hostname() + " active. It has no allocation."); try (Mutex lock = lock(node)) { if (toState == Node.State.active) { for (Node currentActive : getNodes(node.allocation().get().owner(), Node.State.active)) { if (node.allocation().get().membership().cluster().equals(currentActive.allocation().get().membership().cluster()) && node.allocation().get().membership().index() == currentActive.allocation().get().membership().index()) throw new IllegalArgumentException("Could not move " + node + " to active:" + "It has the same cluster and index as an existing node"); } } return db.writeTo(toState, node, agent, reason); } } /* * This method is used to enable a smooth rollout of dynamic docker flavor allocations. Once we have switch * everything this can be simplified to only deleting the node. * * Should only be called by node-admin for docker containers */ public List<Node> markNodeAvailableForNewAllocation(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); if (node.flavor().getType() != Flavor.Type.DOCKER_CONTAINER) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be a docker container node"); } else if (node.state() != Node.State.dirty) { throw new IllegalArgumentException( "Cannot make " + hostname + " available for new allocation, must be in state dirty, but was in " + node.state()); } if (dynamicAllocationEnabled()) { return removeRecursively(node, true); } else { return setReady(Collections.singletonList(node)); } } /** * Removes all the nodes that are children of hostname before finally removing the hostname itself. * * @return List of all the nodes that have been removed */ public List<Node> removeRecursively(String hostname) { Node node = getNode(hostname).orElseThrow(() -> new NotFoundException("No node with hostname \"" + hostname + '"')); return removeRecursively(node, false); } private List<Node> removeRecursively(Node node, boolean force) { try (Mutex lock = lockUnallocated()) { List<Node> removed = node.type() != NodeType.host ? new ArrayList<>() : getChildNodes(node.hostname()).stream() .filter(child -> force || verifyRemovalIsAllowed(child, true)) .collect(Collectors.toList()); if (force || verifyRemovalIsAllowed(node, false)) removed.add(node); db.removeNodes(removed); return removed; } catch (RuntimeException e) { throw new IllegalArgumentException("Failed to delete " + node.hostname(), e); } } /** * Allowed to a node delete if: * Non-docker-container node: iff in state provisioned|failed|parked * Docker-container-node: * If only removing the container node: node in state ready * If also removing the parent node: child is in state provisioned|failed|parked|ready */ private boolean verifyRemovalIsAllowed(Node nodeToRemove, boolean deletingAsChild) { if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER && !deletingAsChild) { if (nodeToRemove.state() != Node.State.ready) { throw new IllegalArgumentException( String.format("Docker container node %s can only be removed when in state ready", nodeToRemove.hostname())); } } else if (nodeToRemove.flavor().getType() == Flavor.Type.DOCKER_CONTAINER) { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked, Node.State.ready); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Child node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } else { List<Node.State> legalStates = Arrays.asList(Node.State.provisioned, Node.State.failed, Node.State.parked); if (! legalStates.contains(nodeToRemove.state())) { throw new IllegalArgumentException(String.format("Node %s can only be removed from following states: %s", nodeToRemove.hostname(), legalStates.stream().map(Node.State::name).collect(Collectors.joining(", ")))); } } return true; } /** * Increases the restart generation of the active nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> restart(NodeFilter filter) { return performOn(StateFilter.from(Node.State.active, filter), node -> write(node.withRestart(node.allocation().get().restartGeneration().withIncreasedWanted()))); } /** * Increases the reboot generation of the nodes matching the filter. * Returns the nodes in their new state. */ public List<Node> reboot(NodeFilter filter) { return performOn(filter, node -> write(node.withReboot(node.status().reboot().withIncreasedWanted()))); } /** * Writes this node after it has changed some internal state but NOT changed its state field. * This does NOT lock the node repository. * * @return the written node for convenience */ public Node write(Node node) { return db.writeTo(node.state(), node, Agent.system, Optional.empty()); } /** * Writes these nodes after they have changed some internal state but NOT changed their state field. * This does NOT lock the node repository. * * @return the written nodes for convenience */ public List<Node> write(List<Node> nodes) { return db.writeTo(nodes, Agent.system, Optional.empty()); } /** * Performs an operation requiring locking on all nodes matching some filter. * * @param filter the filter determining the set of nodes where the operation will be performed * @param action the action to perform * @return the set of nodes on which the action was performed, as they became as a result of the operation */ private List<Node> performOn(NodeFilter filter, UnaryOperator<Node> action) { List<Node> unallocatedNodes = new ArrayList<>(); ListMap<ApplicationId, Node> allocatedNodes = new ListMap<>(); for (Node node : db.getNodes()) { if ( ! filter.matches(node)) continue; if (node.allocation().isPresent()) allocatedNodes.put(node.allocation().get().owner(), node); else unallocatedNodes.add(node); } List<Node> resultingNodes = new ArrayList<>(); try (Mutex lock = lockUnallocated()) { for (Node node : unallocatedNodes) resultingNodes.add(action.apply(node)); } for (Map.Entry<ApplicationId, List<Node>> applicationNodes : allocatedNodes.entrySet()) { try (Mutex lock = lock(applicationNodes.getKey())) { for (Node node : applicationNodes.getValue()) resultingNodes.add(action.apply(node)); } } return resultingNodes; } public List<Node> getConfigNodes() { return Arrays.stream(curator.connectionSpec().split(",")) .map(hostPort -> hostPort.split(":")[0]) .map(host -> createNode(host, host, Optional.empty(), flavors.getFlavorOrThrow("v-4-8-100"), NodeType.config)) .collect(Collectors.toList()); } /** Returns the time keeper of this system */ public Clock clock() { return clock; } /** Create a lock which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application) { return db.lock(application); } /** Create a lock with a timeout which provides exclusive rights to making changes to the given application */ public Mutex lock(ApplicationId application, Duration timeout) { return db.lock(application, timeout); } /** Create a lock which provides exclusive rights to changing the set of ready nodes */ public Mutex lockUnallocated() { return db.lockInactive(); } /** Acquires the appropriate lock for this node */ private Mutex lock(Node node) { return node.allocation().isPresent() ? lock(node.allocation().get().owner()) : lockUnallocated(); } /* * Temporary feature toggle to enable/disable dynamic docker allocation * TODO: Remove when enabled in all zones */ public boolean dynamicAllocationEnabled() { return curator.exists(Path.fromString("/provision/v1/dynamicDockerAllocation")); } }
Forgot to add this to the issue tracking this logging, but this warning was logged roughly once per 20 minutes on the controller yesterday, so it was already ~ once per run . This formatting is better, though.
protected void maintain() { boolean hasWarned = false; for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { if ( ! hasWarned) log.log(Level.WARNING, "Failed talking to YAMAS: " + Exceptions.toMessageString(e) + ". Retrying in " + maintenanceInterval()); hasWarned = true; } } } }
hasWarned = true;
protected void maintain() { boolean hasWarned = false; for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { if ( ! hasWarned) log.log(Level.WARNING, "Failed talking to YAMAS: " + Exceptions.toMessageString(e) + ". Retrying in " + maintenanceInterval()); hasWarned = true; } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
No, it is clear from the code it is not. And from this morning the log contains ``` [2017-10-26 09:02:38.190] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.190] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.190] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.191] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.191] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.191] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.191] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.192] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.192] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.192] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.192] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.193] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.193] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.193] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.194] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.194] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.194] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.194] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.195] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.195] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.195] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.196] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.196] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.196] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.196] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.197] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.197] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.197] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.197] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.198] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed talking to YAMAS: java.net.UnknownHostException: yamas.ops.yahoo.com, retrying in PT10M [2017-10-26 09:02:38.198] WARNING : container Container.com.yahoo.vespa.hosted.controller.maintenance.DeploymentMetricsMaintainer Failed .... ```
protected void maintain() { boolean hasWarned = false; for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { if ( ! hasWarned) log.log(Level.WARNING, "Failed talking to YAMAS: " + Exceptions.toMessageString(e) + ". Retrying in " + maintenanceInterval()); hasWarned = true; } } } }
hasWarned = true;
protected void maintain() { boolean hasWarned = false; for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { if ( ! hasWarned) log.log(Level.WARNING, "Failed talking to YAMAS: " + Exceptions.toMessageString(e) + ". Retrying in " + maintenanceInterval()); hasWarned = true; } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
I mean it was, in practice, once per run. Yesterday. Today: ouch! Change definitely warranted, then.
protected void maintain() { boolean hasWarned = false; for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { if ( ! hasWarned) log.log(Level.WARNING, "Failed talking to YAMAS: " + Exceptions.toMessageString(e) + ". Retrying in " + maintenanceInterval()); hasWarned = true; } } } }
hasWarned = true;
protected void maintain() { boolean hasWarned = false; for (Application application : controller().applications().asList()) { for (Deployment deployment : application.deployments().values()) { try { MetricsService.DeploymentMetrics metrics = controller().metricsService() .getDeploymentMetrics(application.id(), deployment.zone()); DeploymentMetrics appMetrics = new DeploymentMetrics(metrics.queriesPerSecond(), metrics.writesPerSecond(), metrics.documentCount(), metrics.queryLatencyMillis(), metrics.writeLatencyMillis()); try (Lock lock = controller().applications().lock(application.id())) { application = controller().applications().get(application.id()).orElse(null); if (application == null) break; deployment = application.deployments().get(deployment.zone()); if (deployment == null) continue; controller().applications().store(application.with(deployment.withMetrics(appMetrics)), lock); } } catch (UncheckedIOException e) { if ( ! hasWarned) log.log(Level.WARNING, "Failed talking to YAMAS: " + Exceptions.toMessageString(e) + ". Retrying in " + maintenanceInterval()); hasWarned = true; } } } }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
class DeploymentMetricsMaintainer extends Maintainer { private static final Logger log = Logger.getLogger(DeploymentMetricsMaintainer.class.getName()); DeploymentMetricsMaintainer(Controller controller, Duration duration, JobControl jobControl) { super(controller, duration, jobControl); } @Override }
👍
public List<Deployment> sortBy(List<DeploymentSpec.DeclaredZone> zones, Collection<Deployment> deployments) { List<Zone> productionZones = zones.stream() .filter(z -> z.region().isPresent()) .map(z -> new Zone(z.environment(), z.region().get())) .collect(toList()); return deployments.stream() .sorted(comparingInt(deployment -> productionZones.indexOf(deployment.zone()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); }
}
public List<Deployment> sortBy(List<DeploymentSpec.DeclaredZone> zones, Collection<Deployment> deployments) { List<Zone> productionZones = zones.stream() .filter(z -> z.region().isPresent()) .map(z -> new Zone(z.environment(), z.region().get())) .collect(toList()); return deployments.stream() .sorted(comparingInt(deployment -> productionZones.indexOf(deployment.zone()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); }
class DeploymentOrder { private static final Logger log = Logger.getLogger(DeploymentOrder.class.getName()); private final Controller controller; private final Clock clock; public DeploymentOrder(Controller controller) { Objects.requireNonNull(controller, "controller cannot be null"); this.controller = controller; this.clock = controller.clock(); } /** Returns a list of jobs to trigger after the given job */ public List<JobType> nextAfter(JobType job, LockedApplication application) { if ( ! application.deploying().isPresent()) { return Collections.emptyList(); } if (job == JobType.component) { return Collections.singletonList(JobType.systemTest); } List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); Optional<DeploymentSpec.Step> currentStep = fromJob(job, application); if ( ! currentStep.isPresent()) { return Collections.emptyList(); } int currentIndex = deploymentSteps.indexOf(currentStep.get()); if (currentIndex == deploymentSteps.size() - 1) { return Collections.emptyList(); } if ( ! completedSuccessfully(currentStep.get(), application.deploying().get(), application)) { return Collections.emptyList(); } Duration delay = delayAfter(currentStep.get(), application); if (shouldPostponeDeployment(delay, job, application)) { log.info(String.format("Delaying next job after %s of %s by %s", job, application, delay)); return Collections.emptyList(); } DeploymentSpec.Step nextStep = deploymentSteps.get(currentIndex + 1); return nextStep.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether the given job causes an application change */ public boolean givesApplicationChange(JobType job) { return job == JobType.component; } /** Returns whether the given job is last in a deployment */ public boolean isLast(JobType job, Application application) { List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); if (deploymentSteps.isEmpty()) { return false; } DeploymentSpec.Step lastStep = deploymentSteps.get(deploymentSteps.size() - 1); Optional<DeploymentSpec.Step> step = fromJob(job, application); return step.map(s -> s.equals(lastStep)).orElse(false); } /** Returns jobs for given deployment spec, in the order they are declared */ public List<JobType> jobsFrom(DeploymentSpec deploymentSpec) { return deploymentSpec.steps().stream() .flatMap(step -> jobsFrom(step).stream()) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns job status sorted according to deployment spec */ public List<JobStatus> sortBy(DeploymentSpec deploymentSpec, Collection<JobStatus> jobStatus) { List<DeploymentJobs.JobType> sortedJobs = jobsFrom(deploymentSpec); return jobStatus.stream() .sorted(comparingInt(job -> sortedJobs.indexOf(job.type()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns deployments sorted according to declared zones */ /** Returns jobs for the given step */ private List<JobType> jobsFrom(DeploymentSpec.Step step) { return step.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether all jobs have completed successfully for given step */ private boolean completedSuccessfully(DeploymentSpec.Step step, Change change, Application application) { return jobsFrom(step).stream() .allMatch(job -> application.deploymentJobs().isSuccessful(change, job)); } /** Resolve deployment step from job */ private Optional<DeploymentSpec.Step> fromJob(JobType job, Application application) { for (DeploymentSpec.Step step : application.deploymentSpec().steps()) { if (step.deploysTo(job.environment(), job.isProduction() ? job.region(controller.system()) : Optional.empty())) { return Optional.of(step); } } return Optional.empty(); } /** Resolve job from deployment step */ private JobType toJob(DeploymentSpec.DeclaredZone zone) { return JobType.from(controller.system(), zone.environment(), zone.region().orElse(null)) .orElseThrow(() -> new IllegalArgumentException("Invalid zone " + zone)); } /** Returns whether deployment should be postponed according to delay */ private boolean shouldPostponeDeployment(Duration delay, JobType job, Application application) { Optional<Instant> lastSuccess = Optional.ofNullable(application.deploymentJobs().jobStatus().get(job)) .flatMap(JobStatus::lastSuccess) .map(JobStatus.JobRun::at); return lastSuccess.isPresent() && lastSuccess.get().plus(delay).isAfter(clock.instant()); } /** Find all steps that deploy to one or more zones */ private static List<DeploymentSpec.Step> deploymentSteps(Application application) { return application.deploymentSpec().steps().stream() .filter(step -> ! step.zones().isEmpty()) .collect(toList()); } /** Determines the delay that should pass after the given step */ private static Duration delayAfter(DeploymentSpec.Step step, Application application) { int stepIndex = application.deploymentSpec().steps().indexOf(step); if (stepIndex == -1 || stepIndex == application.deploymentSpec().steps().size() - 1) { return Duration.ZERO; } Duration totalDelay = Duration.ZERO; List<DeploymentSpec.Step> remainingSteps = application.deploymentSpec().steps() .subList(stepIndex + 1, application.deploymentSpec().steps().size()); for (DeploymentSpec.Step s : remainingSteps) { if (!(s instanceof DeploymentSpec.Delay)) { break; } totalDelay = totalDelay.plus(((DeploymentSpec.Delay) s).duration()); } return totalDelay; } }
class DeploymentOrder { private static final Logger log = Logger.getLogger(DeploymentOrder.class.getName()); private final Controller controller; private final Clock clock; public DeploymentOrder(Controller controller) { Objects.requireNonNull(controller, "controller cannot be null"); this.controller = controller; this.clock = controller.clock(); } /** Returns a list of jobs to trigger after the given job */ public List<JobType> nextAfter(JobType job, LockedApplication application) { if ( ! application.deploying().isPresent()) { return Collections.emptyList(); } if (job == JobType.component) { return Collections.singletonList(JobType.systemTest); } List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); Optional<DeploymentSpec.Step> currentStep = fromJob(job, application); if ( ! currentStep.isPresent()) { return Collections.emptyList(); } int currentIndex = deploymentSteps.indexOf(currentStep.get()); if (currentIndex == deploymentSteps.size() - 1) { return Collections.emptyList(); } if ( ! completedSuccessfully(currentStep.get(), application.deploying().get(), application)) { return Collections.emptyList(); } Duration delay = delayAfter(currentStep.get(), application); if (shouldPostponeDeployment(delay, job, application)) { log.info(String.format("Delaying next job after %s of %s by %s", job, application, delay)); return Collections.emptyList(); } DeploymentSpec.Step nextStep = deploymentSteps.get(currentIndex + 1); return nextStep.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether the given job causes an application change */ public boolean givesApplicationChange(JobType job) { return job == JobType.component; } /** Returns whether the given job is last in a deployment */ public boolean isLast(JobType job, Application application) { List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); if (deploymentSteps.isEmpty()) { return false; } DeploymentSpec.Step lastStep = deploymentSteps.get(deploymentSteps.size() - 1); Optional<DeploymentSpec.Step> step = fromJob(job, application); return step.map(s -> s.equals(lastStep)).orElse(false); } /** Returns jobs for given deployment spec, in the order they are declared */ public List<JobType> jobsFrom(DeploymentSpec deploymentSpec) { return deploymentSpec.steps().stream() .flatMap(step -> jobsFrom(step).stream()) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns job status sorted according to deployment spec */ public List<JobStatus> sortBy(DeploymentSpec deploymentSpec, Collection<JobStatus> jobStatus) { List<DeploymentJobs.JobType> sortedJobs = jobsFrom(deploymentSpec); return jobStatus.stream() .sorted(comparingInt(job -> sortedJobs.indexOf(job.type()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns deployments sorted according to declared zones */ /** Returns jobs for the given step */ private List<JobType> jobsFrom(DeploymentSpec.Step step) { return step.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether all jobs have completed successfully for given step */ private boolean completedSuccessfully(DeploymentSpec.Step step, Change change, Application application) { return jobsFrom(step).stream() .allMatch(job -> application.deploymentJobs().isSuccessful(change, job)); } /** Resolve deployment step from job */ private Optional<DeploymentSpec.Step> fromJob(JobType job, Application application) { for (DeploymentSpec.Step step : application.deploymentSpec().steps()) { if (step.deploysTo(job.environment(), job.isProduction() ? job.region(controller.system()) : Optional.empty())) { return Optional.of(step); } } return Optional.empty(); } /** Resolve job from deployment step */ private JobType toJob(DeploymentSpec.DeclaredZone zone) { return JobType.from(controller.system(), zone.environment(), zone.region().orElse(null)) .orElseThrow(() -> new IllegalArgumentException("Invalid zone " + zone)); } /** Returns whether deployment should be postponed according to delay */ private boolean shouldPostponeDeployment(Duration delay, JobType job, Application application) { Optional<Instant> lastSuccess = Optional.ofNullable(application.deploymentJobs().jobStatus().get(job)) .flatMap(JobStatus::lastSuccess) .map(JobStatus.JobRun::at); return lastSuccess.isPresent() && lastSuccess.get().plus(delay).isAfter(clock.instant()); } /** Find all steps that deploy to one or more zones */ private static List<DeploymentSpec.Step> deploymentSteps(Application application) { return application.deploymentSpec().steps().stream() .filter(step -> ! step.zones().isEmpty()) .collect(toList()); } /** Determines the delay that should pass after the given step */ private static Duration delayAfter(DeploymentSpec.Step step, Application application) { int stepIndex = application.deploymentSpec().steps().indexOf(step); if (stepIndex == -1 || stepIndex == application.deploymentSpec().steps().size() - 1) { return Duration.ZERO; } Duration totalDelay = Duration.ZERO; List<DeploymentSpec.Step> remainingSteps = application.deploymentSpec().steps() .subList(stepIndex + 1, application.deploymentSpec().steps().size()); for (DeploymentSpec.Step s : remainingSteps) { if (!(s instanceof DeploymentSpec.Delay)) { break; } totalDelay = totalDelay.plus(((DeploymentSpec.Delay) s).duration()); } return totalDelay; } }
Won't this allow application data in the controller to be deleted while there are still active dev or perf deployments? And potentially make config servers and controller out of sync?
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
if ( ! application.get().productionDeployments().isEmpty())
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
It is ok to delete them, but I see the deployments are not deleted here. Nice catch, Incoming PR then.
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
if ( ! application.get().productionDeployments().isEmpty())
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
Deleting and deactivating a deployment is separate code path / API call I think.
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
if ( ! application.get().productionDeployments().isEmpty())
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
You do agree this is easier on the eye, no?
private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); }
&& status.lastCompleted().get().lastCompletedWas(change);
private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
Yes. For non-prod a recursive delete would be nice, but probably not worth the bother.
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
if ( ! application.get().productionDeployments().isEmpty())
public Application deleteApplication(ApplicationId id, Optional<NToken> token) { try (Lock lock = lock(id)) { Optional<Application> application = get(id); if ( ! application.isPresent()) return null; if ( ! application.get().productionDeployments().isEmpty()) throw new IllegalArgumentException("Could not delete '" + application + "': It has active deployments"); Tenant tenant = controller.tenants().tenant(new TenantId(id.tenant().value())).get(); if (tenant.isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not delete '" + application + "': No NToken provided"); if (tenant.isAthensTenant()) zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()) .deleteApplication(tenant.getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); db.deleteApplication(id); log.info("Deleted " + application.get()); return application.get(); } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
class ApplicationController { private static final Logger log = Logger.getLogger(ApplicationController.class.getName()); /** The controller owning this */ private final Controller controller; /** For permanent storage */ private final ControllerDb db; /** For working memory storage and sharing between controllers */ private final CuratorDb curator; private final RotationRepository rotationRepository; private final AthenzClientFactory zmsClientFactory; private final NameService nameService; private final ConfigServerClient configserverClient; private final RoutingGenerator routingGenerator; private final Clock clock; private final DeploymentTrigger deploymentTrigger; ApplicationController(Controller controller, ControllerDb db, CuratorDb curator, RotationRepository rotationRepository, AthenzClientFactory zmsClientFactory, NameService nameService, ConfigServerClient configserverClient, RoutingGenerator routingGenerator, Clock clock) { this.controller = controller; this.db = db; this.curator = curator; this.rotationRepository = rotationRepository; this.zmsClientFactory = zmsClientFactory; this.nameService = nameService; this.configserverClient = configserverClient; this.routingGenerator = routingGenerator; this.clock = clock; this.deploymentTrigger = new DeploymentTrigger(controller, curator, clock); for (Application application : db.listApplications()) { try (Lock lock = lock(application.id())) { Optional<Application> optionalApplication = db.getApplication(application.id()); if ( ! optionalApplication.isPresent()) continue; store(optionalApplication.get(), lock); } } } /** Returns the application with the given id, or null if it is not present */ public Optional<Application> get(ApplicationId id) { return db.getApplication(id); } /** * Returns the application with the given id * * @throws IllegalArgumentException if it does not exist */ public Application require(ApplicationId id) { return get(id).orElseThrow(() -> new IllegalArgumentException(id + " not found")); } /** Returns a snapshot of all applications */ public List<Application> asList() { return db.listApplications(); } /** Returns all applications of a tenant */ public List<Application> asList(TenantName tenant) { return db.listApplications(new TenantId(tenant.value())); } /** * Set the rotations marked as 'global' either 'in' or 'out of' service. * * @return The canonical endpoint altered if any * @throws IOException if rotation status cannot be updated */ public List<String> setGlobalRotationStatus(DeploymentId deploymentId, EndpointStatus status) throws IOException { List<String> rotations = new ArrayList<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { configserverClient.setGlobalRotationStatus(deploymentId, endpoint.get(), status); rotations.add(endpoint.get()); } return rotations; } /** * Get the endpoint status for the global endpoint of this application * * @return Map between the endpoint and the rotation status * @throws IOException if global rotation status cannot be determined */ public Map<String, EndpointStatus> getGlobalRotationStatus(DeploymentId deploymentId) throws IOException { Map<String, EndpointStatus> result = new HashMap<>(); Optional<String> endpoint = getCanonicalGlobalEndpoint(deploymentId); if (endpoint.isPresent()) { EndpointStatus status = configserverClient.getGlobalRotationStatus(deploymentId, endpoint.get()); result.put(endpoint.get(), status); } return result; } /** * Global rotations (plural as we can have aliases) map to exactly one service endpoint. * This method finds that one service endpoint and strips the URI part that * the routingGenerator is wrapping around the endpoint. * * @param deploymentId The deployment to retrieve global service endpoint for * @return Empty if no global endpoint exist, otherwise the service endpoint ([clustername.]app.tenant.region.env) */ Optional<String> getCanonicalGlobalEndpoint(DeploymentId deploymentId) throws IOException { Map<String, RoutingEndpoint> hostToGlobalEndpoint = new HashMap<>(); Map<String, String> hostToCanonicalEndpoint = new HashMap<>(); for (RoutingEndpoint endpoint : routingGenerator.endpoints(deploymentId)) { try { URI uri = new URI(endpoint.getEndpoint()); String serviceEndpoint = uri.getHost(); if (serviceEndpoint == null) { throw new IOException("Unexpected endpoints returned from the Routing Generator"); } String canonicalEndpoint = serviceEndpoint.replaceAll(".vespa.yahooapis.com", ""); String hostname = endpoint.getHostname(); if (hostname != null) { if (endpoint.isGlobal()) { hostToGlobalEndpoint.put(hostname, endpoint); } else { hostToCanonicalEndpoint.put(hostname, canonicalEndpoint); } if (hostToGlobalEndpoint.containsKey(hostname) && hostToCanonicalEndpoint.containsKey(hostname)) { return Optional.of(hostToCanonicalEndpoint.get(hostname)); } } } catch (URISyntaxException use) { throw new IOException(use); } } return Optional.empty(); } /** * Creates a new application for an existing tenant. * * @throws IllegalArgumentException if the application already exists */ public Application createApplication(ApplicationId id, Optional<NToken> token) { if ( ! (id.instance().value().equals("default") || id.instance().value().startsWith("default-pr"))) throw new UnsupportedOperationException("Only the instance names 'default' and names starting with 'default-pr' are supported at the moment"); try (Lock lock = lock(id)) { if (get(id).isPresent()) throw new IllegalArgumentException("An application with id '" + id + "' already exists"); com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId.validate(id.application().value()); Optional<Tenant> tenant = controller.tenants().tenant(new TenantId(id.tenant().value())); if ( ! tenant.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': This tenant does not exist"); if (get(id).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application already exists"); if (get(dashToUnderscore(id)).isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': Application " + dashToUnderscore(id) + " already exists"); if (tenant.get().isAthensTenant() && ! token.isPresent()) throw new IllegalArgumentException("Could not create '" + id + "': No NToken provided"); if (tenant.get().isAthensTenant()) { ZmsClient zmsClient = zmsClientFactory.createZmsClientWithAuthorizedServiceToken(token.get()); try { zmsClient.deleteApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } catch (ZmsException ignored) { } zmsClient.addApplication(tenant.get().getAthensDomain().get(), new com.yahoo.vespa.hosted.controller.api.identifiers.ApplicationId(id.application().value())); } Application application = new Application(id); store(application, lock); log.info("Created " + application); return application; } } /** Deploys an application. If the application does not exist it is created. */ public ActivateResult deployApplication(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage, DeployOptions options) { try (Lock lock = lock(applicationId)) { Application application = get(applicationId).orElse(new Application(applicationId)); Version version; if (options.deployCurrentVersion) version = application.currentVersion(controller, zone); else if (canDeployDirectlyTo(zone, options)) version = options.vespaVersion.map(Version::new).orElse(controller.systemVersion()); else if ( ! application.deploying().isPresent() && ! zone.environment().isManuallyDeployed()) return unexpectedDeployment(applicationId, zone, applicationPackage); else version = application.currentDeployVersion(controller, zone); DeploymentJobs.JobType jobType = DeploymentJobs.JobType.from(controller.zoneRegistry().system(), zone); ApplicationRevision revision = toApplicationPackageRevision(applicationPackage, options.screwdriverBuildJob); if ( ! options.deployCurrentVersion) { application = application.with(applicationPackage.deploymentSpec()); application = application.with(applicationPackage.validationOverrides()); if (options.screwdriverBuildJob.isPresent() && options.screwdriverBuildJob.get().screwdriverId != null) application = application.withProjectId(options.screwdriverBuildJob.get().screwdriverId.value()); if (application.deploying().isPresent() && application.deploying().get() instanceof Change.ApplicationChange) application = application.withDeploying(Optional.of(Change.ApplicationChange.of(revision))); if ( ! triggeredWith(revision, application, jobType) && !canDeployDirectlyTo(zone, options) && jobType != null) { application = application.with(application.deploymentJobs() .withTriggering(jobType, application.deploying(), version, Optional.of(revision), clock.instant())); } application = deleteRemovedDeployments(application, lock); application = deleteUnreferencedDeploymentJobs(application); store(application, lock); } if (! canDeployDirectlyTo(zone, options) && ! application.deploymentJobs().isDeployableTo(zone.environment(), application.deploying())) throw new IllegalArgumentException("Rejecting deployment of " + application + " to " + zone + " as " + application.deploying().get() + " is not tested"); DeploymentId deploymentId = new DeploymentId(applicationId, zone); ApplicationRotation rotationInDns = registerRotationInDns(deploymentId, getOrAssignRotation(deploymentId, applicationPackage)); options = withVersion(version, options); ConfigServerClient.PreparedApplication preparedApplication = configserverClient.prepare(deploymentId, options, rotationInDns.cnames(), rotationInDns.rotations(), applicationPackage.zippedContent()); preparedApplication.activate(); Deployment previousDeployment = application.deployments().getOrDefault(zone, new Deployment(zone, revision, version, clock.instant())); Deployment newDeployment = new Deployment(zone, revision, version, clock.instant(), previousDeployment.clusterUtils(), previousDeployment.clusterInfo(), previousDeployment.metrics()); application = application.with(newDeployment); store(application, lock); return new ActivateResult(new RevisionId(applicationPackage.hash()), preparedApplication.prepareResponse()); } } private ActivateResult unexpectedDeployment(ApplicationId applicationId, Zone zone, ApplicationPackage applicationPackage) { Log logEntry = new Log(); logEntry.level = "WARNING"; logEntry.time = clock.instant().toEpochMilli(); logEntry.message = "Ignoring deployment of " + get(applicationId) + " to " + zone + " as a deployment is not currently expected"; PrepareResponse prepareResponse = new PrepareResponse(); prepareResponse.log = Collections.singletonList(logEntry); prepareResponse.configChangeActions = new ConfigChangeActions(Collections.emptyList(), Collections.emptyList()); return new ActivateResult(new RevisionId(applicationPackage.hash()), prepareResponse); } private Application deleteRemovedDeployments(Application application, Lock lock) { List<Deployment> deploymentsToRemove = application.productionDeployments().values().stream() .filter(deployment -> ! application.deploymentSpec().includes(deployment.zone().environment(), Optional.of(deployment.zone().region()))) .collect(Collectors.toList()); if (deploymentsToRemove.isEmpty()) return application; if ( ! application.validationOverrides().allows(ValidationId.deploymentRemoval, clock.instant())) throw new IllegalArgumentException(ValidationId.deploymentRemoval.value() + ": " + application + " is deployed in " + deploymentsToRemove.stream() .map(deployment -> deployment.zone().region().value()) .collect(Collectors.joining(", ")) + ", but does not include " + (deploymentsToRemove.size() > 1 ? "these zones" : "this zone") + " in deployment.xml"); Application applicationWithRemoval = application; for (Deployment deployment : deploymentsToRemove) applicationWithRemoval = deactivate(applicationWithRemoval, deployment.zone(), lock); return applicationWithRemoval; } private Application deleteUnreferencedDeploymentJobs(Application application) { for (DeploymentJobs.JobType job : application.deploymentJobs().jobStatus().keySet()) { Optional<Zone> zone = job.zone(controller.system()); if ( ! job.isProduction() || (zone.isPresent() && application.deploymentSpec().includes(zone.get().environment(), zone.map(Zone::region)))) continue; application = application.withoutDeploymentJob(job); } return application; } private boolean triggeredWith(ApplicationRevision revision, Application application, DeploymentJobs.JobType jobType) { if (jobType == null) return false; JobStatus status = application.deploymentJobs().jobStatus().get(jobType); if (status == null) return false; if ( ! status.lastTriggered().isPresent()) return false; JobStatus.JobRun triggered = status.lastTriggered().get(); if ( ! triggered.revision().isPresent()) return false; return triggered.revision().get().equals(revision); } private DeployOptions withVersion(Version version, DeployOptions options) { return new DeployOptions(options.screwdriverBuildJob, Optional.of(version), options.ignoreValidationErrors, options.deployCurrentVersion); } private ApplicationRevision toApplicationPackageRevision(ApplicationPackage applicationPackage, Optional<ScrewdriverBuildJob> screwDriverBuildJob) { if ( ! screwDriverBuildJob.isPresent()) return ApplicationRevision.from(applicationPackage.hash()); GitRevision gitRevision = screwDriverBuildJob.get().gitRevision; if (gitRevision.repository == null || gitRevision.branch == null || gitRevision.commit == null) return ApplicationRevision.from(applicationPackage.hash()); return ApplicationRevision.from(applicationPackage.hash(), new SourceRevision(gitRevision.repository.id(), gitRevision.branch.id(), gitRevision.commit.id())); } private ApplicationRotation registerRotationInDns(DeploymentId deploymentId, ApplicationRotation applicationRotation) { ApplicationAlias alias = new ApplicationAlias(deploymentId.applicationId()); if (applicationRotation.rotations().isEmpty()) return applicationRotation; Rotation rotation = applicationRotation.rotations().iterator().next(); String endpointName = alias.toString(); try { Optional<Record> record = nameService.findRecord(Record.Type.CNAME, endpointName); if (!record.isPresent()) { RecordId recordId = nameService.createCname(endpointName, rotation.rotationName); log.info("Registered mapping with record ID " + recordId.id() + ": " + endpointName + " -> " + rotation.rotationName); } } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to register CNAME", e); } return new ApplicationRotation(Collections.singleton(endpointName), Collections.singleton(rotation)); } private ApplicationRotation getOrAssignRotation(DeploymentId deploymentId, ApplicationPackage applicationPackage) { if (deploymentId.zone().environment().equals(Environment.prod)) { return new ApplicationRotation(Collections.emptySet(), rotationRepository.getOrAssignRotation(deploymentId.applicationId(), applicationPackage.deploymentSpec())); } else { return new ApplicationRotation(Collections.emptySet(), Collections.emptySet()); } } /** Returns the endpoints of the deployment, or empty if obtaining them failed */ public Optional<InstanceEndpoints> getDeploymentEndpoints(DeploymentId deploymentId) { try { List<RoutingEndpoint> endpoints = routingGenerator.endpoints(deploymentId); List<URI> endPointUrls = new ArrayList<>(); for (RoutingEndpoint endpoint : endpoints) { try { endPointUrls.add(new URI(endpoint.getEndpoint())); } catch (URISyntaxException e) { throw new RuntimeException("Routing generator returned illegal url's", e); } } return Optional.of(new InstanceEndpoints(endPointUrls)); } catch (RuntimeException e) { log.log(Level.WARNING, "Failed to get endpoint information for " + deploymentId, e); return Optional.empty(); } } /** * Deletes the application with this id * * @return the deleted application, or null if it did not exist * @throws IllegalArgumentException if the application has deployments or the caller is not authorized */ public void setJiraIssueId(ApplicationId id, Optional<String> jiraIssueId) { try (Lock lock = lock(id)) { get(id).ifPresent(application -> store(application.withJiraIssueId(jiraIssueId), lock)); } } /** * Replace any previous version of this application by this instance * * @param application the application version to store * @param lock the lock held on this application since before modification started */ @SuppressWarnings("unused") public void store(Application application, Lock lock) { db.store(application); } public void notifyJobCompletion(JobReport report) { if ( ! get(report.applicationId()).isPresent()) { log.log(Level.WARNING, "Ignoring completion of job of project '" + report.projectId() + "': Unknown application '" + report.applicationId() + "'"); return; } deploymentTrigger.triggerFromCompletion(report); } public void restart(DeploymentId deploymentId) { try { configserverClient.restart(deploymentId, Optional.empty()); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } public void restartHost(DeploymentId deploymentId, Hostname hostname) { try { configserverClient.restart(deploymentId, Optional.of(hostname)); } catch (NoInstanceException e) { throw new IllegalArgumentException("Could not restart " + deploymentId + ": No such deployment"); } } /** Deactivate application in the given zone */ public Application deactivate(Application application, Zone zone) { return deactivate(application, zone, Optional.empty(), false); } /** Deactivate a known deployment of the given application */ public Application deactivate(Application application, Deployment deployment, boolean requireThatDeploymentHasExpired) { return deactivate(application, deployment.zone(), Optional.of(deployment), requireThatDeploymentHasExpired); } private Application deactivate(Application application, Zone zone, Optional<Deployment> deployment, boolean requireThatDeploymentHasExpired) { try (Lock lock = lock(application.id())) { application = controller.applications().require(application.id()); if (deployment.isPresent() && requireThatDeploymentHasExpired && ! DeploymentExpirer.hasExpired(controller.zoneRegistry(), deployment.get(), clock.instant())) { return application; } application = deactivate(application, zone, lock); store(application, lock); return application; } } /** * Deactivates a locked application without storing it * * @return the application with the deployment in the given zone removed */ private Application deactivate(Application application, Zone zone, Lock lock) { try { configserverClient.deactivate(new DeploymentId(application.id(), zone)); } catch (NoInstanceException ignored) { } return application.withoutDeploymentIn(zone); } public DeploymentTrigger deploymentTrigger() { return deploymentTrigger; } private ApplicationId dashToUnderscore(ApplicationId id) { return ApplicationId.from(id.tenant().value(), id.application().value().replaceAll("-", "_"), id.instance().value()); } public ConfigServerClient configserverClient() { return configserverClient; } /** * Returns a lock which provides exclusive rights to changing this application. * Any operation which stores an application need to first acquire this lock, then read, modify * and store the application, and finally release (close) the lock. */ public Lock lock(ApplicationId application) { return curator.lock(application, Duration.ofMinutes(10)); } /** Returns whether a direct deployment to given zone is allowed */ private static boolean canDeployDirectlyTo(Zone zone, DeployOptions options) { return !options.screwdriverBuildJob.isPresent() || options.screwdriverBuildJob.get().screwdriverId == null || zone.environment().isManuallyDeployed(); } private static final class ApplicationRotation { private final ImmutableSet<String> cnames; private final ImmutableSet<Rotation> rotations; public ApplicationRotation(Set<String> cnames, Set<Rotation> rotations) { this.cnames = ImmutableSet.copyOf(cnames); this.rotations = ImmutableSet.copyOf(rotations); } public Set<String> cnames() { return cnames; } public Set<Rotation> rotations() { return rotations; } } }
You don't need to do this for logging - just do log.log(Level.WARNING, "Could not initialize policy", e);
public void run() { try { init(); } catch (Exception e) { log.warning("Init threw exception" + exceptionMessageWithTrace(e)); initException = e; } synchronized (this) { initState = InitState.DONE; this.notifyAll(); } }
log.warning("Init threw exception" + exceptionMessageWithTrace(e));
public void run() { try { init(); } catch (Exception e) { log.log(LogLevel.WARNING,"Init threw exception",e); initException = e; } synchronized (this) { initState = InitState.DONE; this.notifyAll(); } }
class AsyncInitializationPolicy implements DocumentProtocolRoutingPolicy, Runnable { protected enum InitState { NOT_STARTED, RUNNING, DONE }; private static final Logger log = Logger.getLogger(AsyncInitializationPolicy.class.getName()); InitState initState; ScheduledThreadPoolExecutor executor; Exception initException; boolean syncInit = true; public static Map<String, String> parse(String param) { Map<String, String> map = new TreeMap<String, String>(); if (param != null) { String[] p = param.split(";"); for (String s : p) { String[] keyValue = s.split("="); if (keyValue.length == 1) { map.put(keyValue[0], "true"); } else if (keyValue.length == 2) { map.put(keyValue[0], keyValue[1]); } } } return map; } public AsyncInitializationPolicy(Map<String, String> params) { initState = InitState.NOT_STARTED; } public void needAsynchronousInitialization() { syncInit = false; } public abstract void init(); public abstract void doSelect(RoutingContext routingContext); private synchronized void checkStartInit() { if (initState == InitState.NOT_STARTED) { if (syncInit) { init(); initState = InitState.DONE; } else { executor = new ScheduledThreadPoolExecutor(1); executor.execute(this); initState = InitState.RUNNING; } } } @Override public void select(RoutingContext routingContext) { synchronized (this) { if (initException != null) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.POLICY_ERROR, "Policy threw exception during init:" + exceptionMessageWithTrace(initException))); routingContext.setReply(reply); return; } checkStartInit(); if (initState == InitState.RUNNING) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.SESSION_BUSY, "Policy is waiting to be initialized.")); routingContext.setReply(reply); return; } } doSelect(routingContext); } @Override public void destroy() { if (executor != null) { executor.shutdownNow(); } } private static String exceptionMessageWithTrace(Exception e) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); pw.flush(); } return sw.toString(); } }
class AsyncInitializationPolicy implements DocumentProtocolRoutingPolicy, Runnable { protected enum InitState { NOT_STARTED, RUNNING, DONE }; private static final Logger log = Logger.getLogger(AsyncInitializationPolicy.class.getName()); InitState initState; ScheduledThreadPoolExecutor executor; Exception initException; boolean syncInit = true; public static Map<String, String> parse(String param) { Map<String, String> map = new TreeMap<String, String>(); if (param != null) { String[] p = param.split(";"); for (String s : p) { String[] keyValue = s.split("="); if (keyValue.length == 1) { map.put(keyValue[0], "true"); } else if (keyValue.length == 2) { map.put(keyValue[0], keyValue[1]); } } } return map; } public AsyncInitializationPolicy(Map<String, String> params) { initState = InitState.NOT_STARTED; } public void needAsynchronousInitialization() { syncInit = false; } public abstract void init(); public abstract void doSelect(RoutingContext routingContext); private synchronized void checkStartInit() { if (initState == InitState.NOT_STARTED) { if (syncInit) { init(); initState = InitState.DONE; } else { executor = new ScheduledThreadPoolExecutor(1); executor.execute(this); initState = InitState.RUNNING; } } } @Override public void select(RoutingContext routingContext) { synchronized (this) { if (initException != null) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.POLICY_ERROR, "Policy threw exception during init:" + exceptionMessageWithTrace(initException))); routingContext.setReply(reply); return; } checkStartInit(); if (initState == InitState.RUNNING) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.SESSION_BUSY, "Policy is waiting to be initialized.")); routingContext.setReply(reply); return; } } doSelect(routingContext); } @Override public void destroy() { if (executor != null) { executor.shutdownNow(); } } private static String exceptionMessageWithTrace(Exception e) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); pw.flush(); } return sw.toString(); } }
Great. Changed it.
public void run() { try { init(); } catch (Exception e) { log.warning("Init threw exception" + exceptionMessageWithTrace(e)); initException = e; } synchronized (this) { initState = InitState.DONE; this.notifyAll(); } }
log.warning("Init threw exception" + exceptionMessageWithTrace(e));
public void run() { try { init(); } catch (Exception e) { log.log(LogLevel.WARNING,"Init threw exception",e); initException = e; } synchronized (this) { initState = InitState.DONE; this.notifyAll(); } }
class AsyncInitializationPolicy implements DocumentProtocolRoutingPolicy, Runnable { protected enum InitState { NOT_STARTED, RUNNING, DONE }; private static final Logger log = Logger.getLogger(AsyncInitializationPolicy.class.getName()); InitState initState; ScheduledThreadPoolExecutor executor; Exception initException; boolean syncInit = true; public static Map<String, String> parse(String param) { Map<String, String> map = new TreeMap<String, String>(); if (param != null) { String[] p = param.split(";"); for (String s : p) { String[] keyValue = s.split("="); if (keyValue.length == 1) { map.put(keyValue[0], "true"); } else if (keyValue.length == 2) { map.put(keyValue[0], keyValue[1]); } } } return map; } public AsyncInitializationPolicy(Map<String, String> params) { initState = InitState.NOT_STARTED; } public void needAsynchronousInitialization() { syncInit = false; } public abstract void init(); public abstract void doSelect(RoutingContext routingContext); private synchronized void checkStartInit() { if (initState == InitState.NOT_STARTED) { if (syncInit) { init(); initState = InitState.DONE; } else { executor = new ScheduledThreadPoolExecutor(1); executor.execute(this); initState = InitState.RUNNING; } } } @Override public void select(RoutingContext routingContext) { synchronized (this) { if (initException != null) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.POLICY_ERROR, "Policy threw exception during init:" + exceptionMessageWithTrace(initException))); routingContext.setReply(reply); return; } checkStartInit(); if (initState == InitState.RUNNING) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.SESSION_BUSY, "Policy is waiting to be initialized.")); routingContext.setReply(reply); return; } } doSelect(routingContext); } @Override public void destroy() { if (executor != null) { executor.shutdownNow(); } } private static String exceptionMessageWithTrace(Exception e) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); pw.flush(); } return sw.toString(); } }
class AsyncInitializationPolicy implements DocumentProtocolRoutingPolicy, Runnable { protected enum InitState { NOT_STARTED, RUNNING, DONE }; private static final Logger log = Logger.getLogger(AsyncInitializationPolicy.class.getName()); InitState initState; ScheduledThreadPoolExecutor executor; Exception initException; boolean syncInit = true; public static Map<String, String> parse(String param) { Map<String, String> map = new TreeMap<String, String>(); if (param != null) { String[] p = param.split(";"); for (String s : p) { String[] keyValue = s.split("="); if (keyValue.length == 1) { map.put(keyValue[0], "true"); } else if (keyValue.length == 2) { map.put(keyValue[0], keyValue[1]); } } } return map; } public AsyncInitializationPolicy(Map<String, String> params) { initState = InitState.NOT_STARTED; } public void needAsynchronousInitialization() { syncInit = false; } public abstract void init(); public abstract void doSelect(RoutingContext routingContext); private synchronized void checkStartInit() { if (initState == InitState.NOT_STARTED) { if (syncInit) { init(); initState = InitState.DONE; } else { executor = new ScheduledThreadPoolExecutor(1); executor.execute(this); initState = InitState.RUNNING; } } } @Override public void select(RoutingContext routingContext) { synchronized (this) { if (initException != null) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.POLICY_ERROR, "Policy threw exception during init:" + exceptionMessageWithTrace(initException))); routingContext.setReply(reply); return; } checkStartInit(); if (initState == InitState.RUNNING) { Reply reply = new EmptyReply(); reply.addError(new com.yahoo.messagebus.Error(ErrorCode.SESSION_BUSY, "Policy is waiting to be initialized.")); routingContext.setReply(reply); return; } } doSelect(routingContext); } @Override public void destroy() { if (executor != null) { executor.shutdownNow(); } } private static String exceptionMessageWithTrace(Exception e) { StringWriter sw = new StringWriter(); try (PrintWriter pw = new PrintWriter(sw)) { e.printStackTrace(pw); pw.flush(); } return sw.toString(); } }
Consider having each argument to `metric.set()` on separate lines or all on same lines. Now it is easy to mistake `context` as an argument to `getOrDefault`.
private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "app", toApp(applicationId), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().current(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); metric.set("hardwareFailure", node.status().hardwareFailureDescription().isPresent() ? 1 : 0, context); metric.set("hardwareDivergence", node.status().hardwareDivergence().isPresent() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } long numberOfServices; HostName hostName = new HostName(node.hostname()); List<ServiceInstance> services = servicesByHost.get(hostName); if (services == null) { numberOfServices = 0; } else { Map<ServiceStatus, Long> servicesCount = services.stream().collect( Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting())); numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum(); metric.set( "numberOfServicesUp", servicesCount.getOrDefault(ServiceStatus.UP, 0L), context); metric.set( "numberOfServicesNotChecked", servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L), context); long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L); metric.set("numberOfServicesDown", numberOfServicesDown, context); metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context); } metric.set("numberOfServices", numberOfServices, context); }
servicesCount.getOrDefault(ServiceStatus.UP, 0L), context);
private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "app", toApp(applicationId), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().current(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); metric.set("hardwareFailure", node.status().hardwareFailureDescription().isPresent() ? 1 : 0, context); metric.set("hardwareDivergence", node.status().hardwareDivergence().isPresent() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } long numberOfServices; HostName hostName = new HostName(node.hostname()); List<ServiceInstance> services = servicesByHost.get(hostName); if (services == null) { numberOfServices = 0; } else { Map<ServiceStatus, Long> servicesCount = services.stream().collect( Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting())); numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum(); metric.set( "numberOfServicesUp", servicesCount.getOrDefault(ServiceStatus.UP, 0L), context); metric.set( "numberOfServicesNotChecked", servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L), context); long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L); metric.set("numberOfServicesDown", numberOfServicesDown, context); metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context); } metric.set("numberOfServices", numberOfServices, context); }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final ServiceMonitor serviceMonitor; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, ServiceMonitor serviceMonitor, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; this.serviceMonitor = serviceMonitor; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); Map<HostName, List<ServiceInstance>> servicesByHost = serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName(); nodes.forEach(node -> updateNodeMetrics(node, servicesByHost)); updateStateMetrics(nodes); updateDockerMetrics(nodes); } private static String toApp(ApplicationId applicationId) { return applicationId.application().value() + "." + applicationId.instance().value(); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final ServiceMonitor serviceMonitor; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, ServiceMonitor serviceMonitor, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; this.serviceMonitor = serviceMonitor; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); Map<HostName, List<ServiceInstance>> servicesByHost = serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName(); nodes.forEach(node -> updateNodeMetrics(node, servicesByHost)); updateStateMetrics(nodes); updateDockerMetrics(nodes); } private static String toApp(ApplicationId applicationId) { return applicationId.application().value() + "." + applicationId.instance().value(); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Thanks, that's usually what I do. Fixed.
private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "app", toApp(applicationId), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().current(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); metric.set("hardwareFailure", node.status().hardwareFailureDescription().isPresent() ? 1 : 0, context); metric.set("hardwareDivergence", node.status().hardwareDivergence().isPresent() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } long numberOfServices; HostName hostName = new HostName(node.hostname()); List<ServiceInstance> services = servicesByHost.get(hostName); if (services == null) { numberOfServices = 0; } else { Map<ServiceStatus, Long> servicesCount = services.stream().collect( Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting())); numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum(); metric.set( "numberOfServicesUp", servicesCount.getOrDefault(ServiceStatus.UP, 0L), context); metric.set( "numberOfServicesNotChecked", servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L), context); long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L); metric.set("numberOfServicesDown", numberOfServicesDown, context); metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context); } metric.set("numberOfServices", numberOfServices, context); }
servicesCount.getOrDefault(ServiceStatus.UP, 0L), context);
private void updateNodeMetrics(Node node, Map<HostName, List<ServiceInstance>> servicesByHost) { Metric.Context context; Optional<Allocation> allocation = node.allocation(); if (allocation.isPresent()) { ApplicationId applicationId = allocation.get().owner(); context = getContextAt( "state", node.state().name(), "hostname", node.hostname(), "tenantName", applicationId.tenant().value(), "applicationId", applicationId.serializedForm().replace(':', '.'), "app", toApp(applicationId), "clustertype", allocation.get().membership().cluster().type().name(), "clusterid", allocation.get().membership().cluster().id().value()); long wantedRestartGeneration = allocation.get().restartGeneration().wanted(); metric.set("wantedRestartGeneration", wantedRestartGeneration, context); long currentRestartGeneration = allocation.get().restartGeneration().current(); metric.set("currentRestartGeneration", currentRestartGeneration, context); boolean wantToRestart = currentRestartGeneration < wantedRestartGeneration; metric.set("wantToRestart", wantToRestart ? 1 : 0, context); Version wantedVersion = allocation.get().membership().cluster().vespaVersion(); double wantedVersionNumber = getVersionAsNumber(wantedVersion); metric.set("wantedVespaVersion", wantedVersionNumber, context); Optional<Version> currentVersion = node.status().vespaVersion(); boolean converged = currentVersion.isPresent() && currentVersion.get().equals(wantedVersion); metric.set("wantToChangeVespaVersion", converged ? 0 : 1, context); } else { context = getContextAt( "state", node.state().name(), "hostname", node.hostname()); } Optional<Version> currentVersion = node.status().vespaVersion(); if (currentVersion.isPresent() && !currentVersion.get().isEmpty()) { double currentVersionNumber = getVersionAsNumber(currentVersion.get()); metric.set("currentVespaVersion", currentVersionNumber, context); } long wantedRebootGeneration = node.status().reboot().wanted(); metric.set("wantedRebootGeneration", wantedRebootGeneration, context); long currentRebootGeneration = node.status().reboot().current(); metric.set("currentRebootGeneration", currentRebootGeneration, context); boolean wantToReboot = currentRebootGeneration < wantedRebootGeneration; metric.set("wantToReboot", wantToReboot ? 1 : 0, context); metric.set("wantToRetire", node.status().wantToRetire() ? 1 : 0, context); metric.set("wantToDeprovision", node.status().wantToDeprovision() ? 1 : 0, context); metric.set("hardwareFailure", node.status().hardwareFailureDescription().isPresent() ? 1 : 0, context); metric.set("hardwareDivergence", node.status().hardwareDivergence().isPresent() ? 1 : 0, context); try { HostStatus status = orchestrator.getNodeStatus(new HostName(node.hostname())); boolean allowedToBeDown = status == HostStatus.ALLOWED_TO_BE_DOWN; metric.set("allowedToBeDown", allowedToBeDown ? 1 : 0, context); } catch (HostNameNotFoundException e) { } long numberOfServices; HostName hostName = new HostName(node.hostname()); List<ServiceInstance> services = servicesByHost.get(hostName); if (services == null) { numberOfServices = 0; } else { Map<ServiceStatus, Long> servicesCount = services.stream().collect( Collectors.groupingBy(ServiceInstance::serviceStatus, Collectors.counting())); numberOfServices = servicesCount.values().stream().mapToLong(Long::longValue).sum(); metric.set( "numberOfServicesUp", servicesCount.getOrDefault(ServiceStatus.UP, 0L), context); metric.set( "numberOfServicesNotChecked", servicesCount.getOrDefault(ServiceStatus.NOT_CHECKED, 0L), context); long numberOfServicesDown = servicesCount.getOrDefault(ServiceStatus.DOWN, 0L); metric.set("numberOfServicesDown", numberOfServicesDown, context); metric.set("someServicesDown", (numberOfServicesDown > 0 ? 1 : 0), context); } metric.set("numberOfServices", numberOfServices, context); }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final ServiceMonitor serviceMonitor; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, ServiceMonitor serviceMonitor, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; this.serviceMonitor = serviceMonitor; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); Map<HostName, List<ServiceInstance>> servicesByHost = serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName(); nodes.forEach(node -> updateNodeMetrics(node, servicesByHost)); updateStateMetrics(nodes); updateDockerMetrics(nodes); } private static String toApp(ApplicationId applicationId) { return applicationId.application().value() + "." + applicationId.instance().value(); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
class MetricsReporter extends Maintainer { private final Metric metric; private final Orchestrator orchestrator; private final ServiceMonitor serviceMonitor; private final Map<Map<String, String>, Metric.Context> contextMap = new HashMap<>(); public MetricsReporter(NodeRepository nodeRepository, Metric metric, Orchestrator orchestrator, ServiceMonitor serviceMonitor, Duration interval, JobControl jobControl) { super(nodeRepository, interval, jobControl); this.metric = metric; this.orchestrator = orchestrator; this.serviceMonitor = serviceMonitor; } @Override public void maintain() { List<Node> nodes = nodeRepository().getNodes(); Map<HostName, List<ServiceInstance>> servicesByHost = serviceMonitor.getServiceModelSnapshot().getServiceInstancesByHostName(); nodes.forEach(node -> updateNodeMetrics(node, servicesByHost)); updateStateMetrics(nodes); updateDockerMetrics(nodes); } private static String toApp(ApplicationId applicationId) { return applicationId.application().value() + "." + applicationId.instance().value(); } /** * A version 6.163.20 will be returned as a number 163.020. The major * version can normally be inferred. As long as the micro version stays * below 1000 these numbers sort like Version. */ private static double getVersionAsNumber(Version version) { return version.getMinor() + version.getMicro() / 1000.0; } private Metric.Context getContextAt(String... point) { if (point.length % 2 != 0) { throw new IllegalArgumentException("Dimension specification comes in pairs"); } Map<String, String> dimensions = new HashMap<>(); for (int i = 0; i < point.length; i += 2) { dimensions.put(point[i], point[i + 1]); } Metric.Context context = contextMap.get(dimensions); if (context != null) { return context; } context = metric.createContext(dimensions); contextMap.put(dimensions, context); return context; } private void updateStateMetrics(List<Node> nodes) { Map<Node.State, List<Node>> nodesByState = nodes.stream() .collect(Collectors.groupingBy(Node::state)); for (Node.State state : Node.State.values()) { List<Node> nodesInState = nodesByState.getOrDefault(state, new ArrayList<>()); long size = nodesInState.stream().filter(node -> node.type() == NodeType.tenant).count(); metric.set("hostedVespa." + state.name() + "Hosts", size, null); } } private void updateDockerMetrics(List<Node> nodes) { DockerHostCapacity capacity = new DockerHostCapacity(nodes); metric.set("hostedVespa.docker.totalCapacityCpu", capacity.getCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.totalCapacityMem", capacity.getCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.totalCapacityDisk", capacity.getCapacityTotal().getDisk(), null); metric.set("hostedVespa.docker.freeCapacityCpu", capacity.getFreeCapacityTotal().getCpu(), null); metric.set("hostedVespa.docker.freeCapacityMem", capacity.getFreeCapacityTotal().getMemory(), null); metric.set("hostedVespa.docker.freeCapacityDisk", capacity.getFreeCapacityTotal().getDisk(), null); List<Flavor> dockerFlavors = nodeRepository().getAvailableFlavors().getFlavors().stream() .filter(f -> f.getType().equals(Flavor.Type.DOCKER_CONTAINER)) .collect(Collectors.toList()); for (Flavor flavor : dockerFlavors) { Metric.Context context = getContextAt("flavor", flavor.name()); metric.set("hostedVespa.docker.freeCapacityFlavor", capacity.freeCapacityInFlavorEquivalence(flavor), context); metric.set("hostedVespa.docker.idealHeadroomFlavor", flavor.getIdealHeadroom(), context); metric.set("hostedVespa.docker.hostsAvailableFlavor", capacity.getNofHostsAvailableFor(flavor), context); } } }
Consider removing `instanceId` variable and return result from `parseAppInstanceReference` directly.
private ApplicationInstanceReference parseInstanceId(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId; try { instanceId = parseAppInstanceReference(instanceIdString); } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build()); } return instanceId; }
instanceId = parseAppInstanceReference(instanceIdString);
private ApplicationInstanceReference parseInstanceId(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId; try { instanceId = parseAppInstanceReference(instanceIdString); } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build()); } return instanceId; }
class InstanceResource { private final StatusService statusService; private final SlobrokMonitorManager slobrokMonitorManager; private final InstanceLookupService instanceLookupService; @Inject public InstanceResource(@Component InstanceLookupService instanceLookupService, @Component StatusService statusService, @Component SlobrokMonitorManager slobrokMonitorManager) { this.instanceLookupService = instanceLookupService; this.statusService = statusService; this.slobrokMonitorManager = slobrokMonitorManager; } @GET @Produces(MediaType.APPLICATION_JSON) public Set<ApplicationInstanceReference> getAllInstances() { return instanceLookupService.knownInstances(); } @GET @Path("/{instanceId}") @Produces(MediaType.APPLICATION_JSON) public InstanceStatusResponse getInstance(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId = parseInstanceId(instanceIdString); ApplicationInstance applicationInstance = instanceLookupService.findInstanceById(instanceId) .orElseThrow(() -> new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build())); Set<HostName> hostsUsedByApplicationInstance = getHostsUsedByApplicationInstance(applicationInstance); Map<HostName, HostStatus> hostStatusMap = getHostStatusMap(hostsUsedByApplicationInstance, statusService.forApplicationInstance(instanceId)); Map<HostName, String> hostStatusStringMap = OrchestratorUtil.mapValues(hostStatusMap, HostStatus::name); return InstanceStatusResponse.create(applicationInstance, hostStatusStringMap); } @GET @Path("/{instanceId}/slobrok") @Produces(MediaType.APPLICATION_JSON) public List<SlobrokEntryResponse> getSlobrokEntries( @PathParam("instanceId") String instanceId, @QueryParam("pattern") String pattern) { ApplicationInstanceReference reference = parseInstanceId(instanceId); ApplicationId applicationId = OrchestratorUtil.toApplicationId(reference); if (pattern == null) { pattern = "**"; } List<Mirror.Entry> entries = slobrokMonitorManager.lookup(applicationId, pattern); return entries.stream().map(SlobrokEntryResponse::fromMirrorEntry) .collect(Collectors.toList()); } }
class InstanceResource { private final StatusService statusService; private final SlobrokMonitorManager slobrokMonitorManager; private final InstanceLookupService instanceLookupService; @Inject public InstanceResource(@Component InstanceLookupService instanceLookupService, @Component StatusService statusService, @Component SlobrokMonitorManager slobrokMonitorManager) { this.instanceLookupService = instanceLookupService; this.statusService = statusService; this.slobrokMonitorManager = slobrokMonitorManager; } @GET @Produces(MediaType.APPLICATION_JSON) public Set<ApplicationInstanceReference> getAllInstances() { return instanceLookupService.knownInstances(); } @GET @Path("/{instanceId}") @Produces(MediaType.APPLICATION_JSON) public InstanceStatusResponse getInstance(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId = parseInstanceId(instanceIdString); ApplicationInstance applicationInstance = instanceLookupService.findInstanceById(instanceId) .orElseThrow(() -> new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build())); Set<HostName> hostsUsedByApplicationInstance = getHostsUsedByApplicationInstance(applicationInstance); Map<HostName, HostStatus> hostStatusMap = getHostStatusMap(hostsUsedByApplicationInstance, statusService.forApplicationInstance(instanceId)); Map<HostName, String> hostStatusStringMap = OrchestratorUtil.mapValues(hostStatusMap, HostStatus::name); return InstanceStatusResponse.create(applicationInstance, hostStatusStringMap); } @GET @Path("/{instanceId}/slobrok") @Produces(MediaType.APPLICATION_JSON) public List<SlobrokEntryResponse> getSlobrokEntries( @PathParam("instanceId") String instanceId, @QueryParam("pattern") String pattern) { ApplicationInstanceReference reference = parseInstanceId(instanceId); ApplicationId applicationId = OrchestratorUtil.toApplicationId(reference); if (pattern == null) { pattern = "**"; } List<Mirror.Entry> entries = slobrokMonitorManager.lookup(applicationId, pattern); return entries.stream().map(SlobrokEntryResponse::fromMirrorEntry) .collect(Collectors.toList()); } }
Done
private ApplicationInstanceReference parseInstanceId(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId; try { instanceId = parseAppInstanceReference(instanceIdString); } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build()); } return instanceId; }
instanceId = parseAppInstanceReference(instanceIdString);
private ApplicationInstanceReference parseInstanceId(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId; try { instanceId = parseAppInstanceReference(instanceIdString); } catch (IllegalArgumentException e) { throw new WebApplicationException(Response.status(Response.Status.BAD_REQUEST).build()); } return instanceId; }
class InstanceResource { private final StatusService statusService; private final SlobrokMonitorManager slobrokMonitorManager; private final InstanceLookupService instanceLookupService; @Inject public InstanceResource(@Component InstanceLookupService instanceLookupService, @Component StatusService statusService, @Component SlobrokMonitorManager slobrokMonitorManager) { this.instanceLookupService = instanceLookupService; this.statusService = statusService; this.slobrokMonitorManager = slobrokMonitorManager; } @GET @Produces(MediaType.APPLICATION_JSON) public Set<ApplicationInstanceReference> getAllInstances() { return instanceLookupService.knownInstances(); } @GET @Path("/{instanceId}") @Produces(MediaType.APPLICATION_JSON) public InstanceStatusResponse getInstance(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId = parseInstanceId(instanceIdString); ApplicationInstance applicationInstance = instanceLookupService.findInstanceById(instanceId) .orElseThrow(() -> new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build())); Set<HostName> hostsUsedByApplicationInstance = getHostsUsedByApplicationInstance(applicationInstance); Map<HostName, HostStatus> hostStatusMap = getHostStatusMap(hostsUsedByApplicationInstance, statusService.forApplicationInstance(instanceId)); Map<HostName, String> hostStatusStringMap = OrchestratorUtil.mapValues(hostStatusMap, HostStatus::name); return InstanceStatusResponse.create(applicationInstance, hostStatusStringMap); } @GET @Path("/{instanceId}/slobrok") @Produces(MediaType.APPLICATION_JSON) public List<SlobrokEntryResponse> getSlobrokEntries( @PathParam("instanceId") String instanceId, @QueryParam("pattern") String pattern) { ApplicationInstanceReference reference = parseInstanceId(instanceId); ApplicationId applicationId = OrchestratorUtil.toApplicationId(reference); if (pattern == null) { pattern = "**"; } List<Mirror.Entry> entries = slobrokMonitorManager.lookup(applicationId, pattern); return entries.stream().map(SlobrokEntryResponse::fromMirrorEntry) .collect(Collectors.toList()); } }
class InstanceResource { private final StatusService statusService; private final SlobrokMonitorManager slobrokMonitorManager; private final InstanceLookupService instanceLookupService; @Inject public InstanceResource(@Component InstanceLookupService instanceLookupService, @Component StatusService statusService, @Component SlobrokMonitorManager slobrokMonitorManager) { this.instanceLookupService = instanceLookupService; this.statusService = statusService; this.slobrokMonitorManager = slobrokMonitorManager; } @GET @Produces(MediaType.APPLICATION_JSON) public Set<ApplicationInstanceReference> getAllInstances() { return instanceLookupService.knownInstances(); } @GET @Path("/{instanceId}") @Produces(MediaType.APPLICATION_JSON) public InstanceStatusResponse getInstance(@PathParam("instanceId") String instanceIdString) { ApplicationInstanceReference instanceId = parseInstanceId(instanceIdString); ApplicationInstance applicationInstance = instanceLookupService.findInstanceById(instanceId) .orElseThrow(() -> new WebApplicationException(Response.status(Response.Status.NOT_FOUND).build())); Set<HostName> hostsUsedByApplicationInstance = getHostsUsedByApplicationInstance(applicationInstance); Map<HostName, HostStatus> hostStatusMap = getHostStatusMap(hostsUsedByApplicationInstance, statusService.forApplicationInstance(instanceId)); Map<HostName, String> hostStatusStringMap = OrchestratorUtil.mapValues(hostStatusMap, HostStatus::name); return InstanceStatusResponse.create(applicationInstance, hostStatusStringMap); } @GET @Path("/{instanceId}/slobrok") @Produces(MediaType.APPLICATION_JSON) public List<SlobrokEntryResponse> getSlobrokEntries( @PathParam("instanceId") String instanceId, @QueryParam("pattern") String pattern) { ApplicationInstanceReference reference = parseInstanceId(instanceId); ApplicationId applicationId = OrchestratorUtil.toApplicationId(reference); if (pattern == null) { pattern = "**"; } List<Mirror.Entry> entries = slobrokMonitorManager.lookup(applicationId, pattern); return entries.stream().map(SlobrokEntryResponse::fromMirrorEntry) .collect(Collectors.toList()); } }
It can't but you are right!
private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.isSuccess() && ! productionUpgradeHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (next != null && isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().equals(nextSuccess.revision())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; }
if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().equals(nextSuccess.revision()))
private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent()) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (next != null && isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().equals(nextSuccess.revision())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (deploymentComplete(application)) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application, report.jobType())) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** Returns whether all production zones listed in deployment spec last were successful on the currently deploying change. */ private boolean deploymentComplete(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; return order.jobsFrom(application.deploymentSpec()).stream() .filter(JobType::isProduction) .allMatch(jobType -> application.deploymentJobs().isSuccessful(application.deploying().get(), jobType)); } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, (change instanceof Change.VersionChange ? "Upgrading to " + ((Change.VersionChange)change).version() : "Deploying " + change)); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().isPresent() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this job just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application, JobType jobType) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); return (jobStatus != null && jobStatus.firstFailing().get().at().isAfter(clock.instant().minus(Duration.ofSeconds(10)))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to put the job at the front of the build system queue (or the back) * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (jobType.isProduction() && isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (jobs.stream().anyMatch(JobType::isProduction) && isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionUpgradeHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (deploymentComplete(application)) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application, report.jobType())) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** Returns whether all production zones listed in deployment spec last were successful on the currently deploying change. */ private boolean deploymentComplete(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; return order.jobsFrom(application.deploymentSpec()).stream() .filter(JobType::isProduction) .allMatch(jobType -> application.deploymentJobs().isSuccessful(application.deploying().get(), jobType)); } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, (change instanceof Change.VersionChange ? "Upgrading to " + ((Change.VersionChange)change).version() : "Deploying " + change)); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().isPresent() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this job just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application, JobType jobType) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); return (jobStatus != null && jobStatus.firstFailing().get().at().isAfter(clock.instant().minus(Duration.ofSeconds(10)))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to put the job at the front of the build system queue (or the back) * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (jobType.isProduction() && isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (jobs.stream().anyMatch(JobType::isProduction) && isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
It's a bit ugly to propagate the full deploy properties. Please limit the scope of the arguments as much as possible.
private void addClusterContent(ContainerCluster cluster, Element spec, ConfigModelContext context) { DocumentFactoryBuilder.buildDocumentFactories(cluster, spec); addConfiguredComponents(cluster, spec); addHandlers(cluster, spec); addRestApis(spec, cluster); addServlets(spec, cluster); addProcessing(spec, cluster); addSearch(spec, cluster, context.getDeployState().getQueryProfiles(), context.getDeployState().getSemanticRules()); addDocproc(spec, cluster); addDocumentApi(spec, cluster); addDefaultHandlers(cluster); addStatusHandlers(cluster, context); addDefaultComponents(cluster); setDefaultMetricConsumerFactory(cluster); addHttp(spec, cluster); addAccessLogs(cluster, spec); addRoutingAliases(cluster, spec, context.getDeployState().zone().environment()); addNodes(cluster, spec, context); addClientProviders(spec, cluster); addServerProviders(spec, cluster); addLegacyFilters(spec, cluster); addIdentity(spec, cluster, context.getDeployState().getProperties()); }
addIdentity(spec, cluster, context.getDeployState().getProperties());
private void addClusterContent(ContainerCluster cluster, Element spec, ConfigModelContext context) { DocumentFactoryBuilder.buildDocumentFactories(cluster, spec); addConfiguredComponents(cluster, spec); addHandlers(cluster, spec); addRestApis(spec, cluster); addServlets(spec, cluster); addProcessing(spec, cluster); addSearch(spec, cluster, context.getDeployState().getQueryProfiles(), context.getDeployState().getSemanticRules()); addDocproc(spec, cluster); addDocumentApi(spec, cluster); addDefaultHandlers(cluster); addStatusHandlers(cluster, context); addDefaultComponents(cluster); setDefaultMetricConsumerFactory(cluster); addHttp(spec, cluster); addAccessLogs(cluster, spec); addRoutingAliases(cluster, spec, context.getDeployState().zone().environment()); addNodes(cluster, spec, context); addClientProviders(spec, cluster); addServerProviders(spec, cluster); addLegacyFilters(spec, cluster); addIdentity(spec, cluster, context.getDeployState().getProperties().configServerSpecs(), context.getDeployState().getProperties().loadBalancerAddress()); }
class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> { /** * Default path to vip status file for container in Hosted Vespa. */ static final String HOSTED_VESPA_STATUS_FILE = Defaults.getDefaults().underVespaHome("var/mediasearch/oor/status.html"); /** * Path to vip status file for container in Hosted Vespa. Only used if set, else use HOSTED_VESPA_STATUS_FILE */ static final String HOSTED_VESPA_STATUS_FILE_YINST_SETTING = "cloudconfig_server__tenant_vip_status_file"; public enum Networking { disable, enable } private ApplicationPackage app; private final boolean standaloneBuilder; private final Networking networking; protected DeployLogger log; public static final List<ConfigModelId> configModelIds = ImmutableList.of(ConfigModelId.fromName("container"), ConfigModelId.fromName("jdisc")); private static final String xmlRendererId = RendererRegistry.xmlRendererId.getName(); private static final String jsonRendererId = RendererRegistry.jsonRendererId.getName(); private static final Logger logger = Logger.getLogger(ContainerCluster.class.getName()); public ContainerModelBuilder(boolean standaloneBuilder, Networking networking) { super(ContainerModel.class); this.standaloneBuilder = standaloneBuilder; this.networking = networking; } @Override public List<ConfigModelId> handlesElements() { return configModelIds; } @Override public void doBuild(ContainerModel model, Element spec, ConfigModelContext modelContext) { app = modelContext.getApplicationPackage(); checkVersion(spec); this.log = modelContext.getDeployLogger(); ContainerCluster cluster = createContainerCluster(spec, modelContext); addClusterContent(cluster, spec, modelContext); addBundlesForPlatformComponents(cluster); model.setCluster(cluster); } protected void addBundlesForPlatformComponents(ContainerCluster cluster) { for (Component<?, ?> component : cluster.getAllComponents()) { String componentClass = component.model.bundleInstantiationSpec.getClassName(); BundleMapper.getBundlePath(componentClass). ifPresent(cluster::addPlatformBundle); } } private ContainerCluster createContainerCluster(Element spec, final ConfigModelContext modelContext) { return new VespaDomBuilder.DomConfigProducerBuilder<ContainerCluster>() { @Override protected ContainerCluster doBuild(AbstractConfigProducer ancestor, Element producerSpec) { return new ContainerCluster(ancestor, modelContext.getProducerId(), modelContext.getProducerId()); } }.build(modelContext.getParentProducer(), spec); } private void addRoutingAliases(ContainerCluster cluster, Element spec, Environment environment) { if (environment != Environment.prod) return; Element aliases = XML.getChild(spec, "aliases"); for (Element alias : XML.getChildren(aliases, "service-alias")) { cluster.serviceAliases().add(XML.getValue(alias)); } for (Element alias : XML.getChildren(aliases, "endpoint-alias")) { cluster.endpointAliases().add(XML.getValue(alias)); } } private void addConfiguredComponents(ContainerCluster cluster, Element spec) { for (Element components : XML.getChildren(spec, "components")) { addIncludes(components); addConfiguredComponents(cluster, components, "component"); } addConfiguredComponents(cluster, spec, "component"); } protected void addDefaultComponents(ContainerCluster cluster) { } protected void setDefaultMetricConsumerFactory(ContainerCluster cluster) { cluster.setDefaultMetricConsumerFactory(MetricDefaultsConfig.Factory.Enum.STATE_MONITOR); } protected void addDefaultHandlers(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); } protected void addStatusHandlers(ContainerCluster cluster, ConfigModelContext configModelContext) { if (configModelContext.getDeployState().isHosted()) { String name = "status.html"; Optional<String> statusFile = Optional.ofNullable(System.getenv(HOSTED_VESPA_STATUS_FILE_YINST_SETTING)); cluster.addComponent( new FileStatusHandlerComponent(name + "-status-handler", statusFile.orElse(HOSTED_VESPA_STATUS_FILE), "http: } else { cluster.addVipHandler(); } } /** * Intended for use by legacy builders only. * Will be called during building when using ContainerModelBuilder. */ public static void addDefaultHandler_legacyBuilder(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); cluster.addVipHandler(); } protected static void addDefaultHandlersExceptStatus(ContainerCluster cluster) { cluster.addDefaultRootHandler(); cluster.addMetricStateHandler(); cluster.addApplicationStatusHandler(); cluster.addStatisticsHandler(); } private void addClientProviders(Element spec, ContainerCluster cluster) { for (Element clientSpec: XML.getChildren(spec, "client")) { cluster.addComponent(new DomClientProviderBuilder().build(cluster, clientSpec)); } } private void addServerProviders(Element spec, ContainerCluster cluster) { addConfiguredComponents(cluster, spec, "server"); } private void addLegacyFilters(Element spec, ContainerCluster cluster) { for (Component component : buildLegacyFilters(cluster, spec)) { cluster.addComponent(component); } } private List<Component> buildLegacyFilters(AbstractConfigProducer ancestor, Element spec) { List<Component> components = new ArrayList<>(); for (Element node : XML.getChildren(spec, "filter")) { components.add(new DomFilterBuilder().build(ancestor, node)); } return components; } protected void addAccessLogs(ContainerCluster cluster, Element spec) { List<Element> accessLogElements = getAccessLogElements(spec); for (Element accessLog : accessLogElements) { AccessLogBuilder.buildIfNotDisabled(cluster, accessLog).ifPresent(cluster::addComponent); } if (accessLogElements.isEmpty() && cluster.getSearch() != null) cluster.addDefaultSearchAccessLog(); } protected final List<Element> getAccessLogElements(Element spec) { return XML.getChildren(spec, "accesslog"); } protected void addHttp(Element spec, ContainerCluster cluster) { Element httpElement = XML.getChild(spec, "http"); if (httpElement != null) { cluster.setHttp(buildHttp(cluster, httpElement)); } } private Http buildHttp(ContainerCluster cluster, Element httpElement) { Http http = new HttpBuilder().build(cluster, httpElement); if (networking == Networking.disable) http.removeAllServers(); return http; } protected void addRestApis(Element spec, ContainerCluster cluster) { for (Element restApiElem : XML.getChildren(spec, "rest-api")) { cluster.addRestApi( new RestApiBuilder().build(cluster, restApiElem)); } } private void addServlets(Element spec, ContainerCluster cluster) { for (Element servletElem : XML.getChildren(spec, "servlet")) { cluster.addServlet( new ServletBuilder().build(cluster, servletElem)); } } private void addDocumentApi(Element spec, ContainerCluster cluster) { ContainerDocumentApi containerDocumentApi = buildDocumentApi(cluster, spec); if (containerDocumentApi != null) { cluster.setDocumentApi(containerDocumentApi); } } private void addDocproc(Element spec, ContainerCluster cluster) { ContainerDocproc containerDocproc = buildDocproc(cluster, spec); if (containerDocproc != null) { cluster.setDocproc(containerDocproc); ContainerDocproc.Options docprocOptions = containerDocproc.options; cluster.setMbusParams(new ContainerCluster.MbusParams( docprocOptions.maxConcurrentFactor, docprocOptions.documentExpansionFactor, docprocOptions.containerCoreMemory)); } } private void addSearch(Element spec, ContainerCluster cluster, QueryProfiles queryProfiles, SemanticRules semanticRules) { Element searchElement = XML.getChild(spec, "search"); if (searchElement != null) { addIncludes(searchElement); cluster.setSearch(buildSearch(cluster, searchElement, queryProfiles, semanticRules)); addSearchHandler(cluster, searchElement); validateAndAddConfiguredComponents(cluster, searchElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private void addProcessing(Element spec, ContainerCluster cluster) { Element processingElement = XML.getChild(spec, "processing"); if (processingElement != null) { addIncludes(processingElement); cluster.setProcessingChains(new DomProcessingBuilder(null).build(cluster, processingElement), serverBindings(processingElement, ProcessingChains.defaultBindings)); validateAndAddConfiguredComponents(cluster, processingElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private ContainerSearch buildSearch(ContainerCluster containerCluster, Element producerSpec, QueryProfiles queryProfiles, SemanticRules semanticRules) { SearchChains searchChains = new DomSearchChainsBuilder(null, false).build(containerCluster, producerSpec); ContainerSearch containerSearch = new ContainerSearch(containerCluster, searchChains, new ContainerSearch.Options()); applyApplicationPackageDirectoryConfigs(containerCluster.getRoot().getDeployState().getApplicationPackage(), containerSearch); containerSearch.setQueryProfiles(queryProfiles); containerSearch.setSemanticRules(semanticRules); return containerSearch; } private void applyApplicationPackageDirectoryConfigs(ApplicationPackage applicationPackage,ContainerSearch containerSearch) { PageTemplates.validate(applicationPackage); containerSearch.setPageTemplates(PageTemplates.create(applicationPackage)); } private void addHandlers(ContainerCluster cluster, Element spec) { for (Element component: XML.getChildren(spec, "handler")) { cluster.addComponent( new DomHandlerBuilder().build(cluster, component)); } } private void checkVersion(Element spec) { String version = spec.getAttribute("version"); if ( ! Version.fromString(version).equals(new Version(1))) { throw new RuntimeException("Expected container version to be 1.0, but got " + version); } } private void addNodes(ContainerCluster cluster, Element spec, ConfigModelContext context) { if (standaloneBuilder) addStandaloneNode(cluster); else addNodesFromXml(cluster, spec, context); } private void addStandaloneNode(ContainerCluster cluster) { Container container = new Container(cluster, "standalone", cluster.getContainers().size()); cluster.addContainers(Collections.singleton(container)); } private void addNodesFromXml(ContainerCluster cluster, Element containerElement, ConfigModelContext context) { Element nodesElement = XML.getChild(containerElement, "nodes"); if (nodesElement == null) { Container node = new Container(cluster, "container.0", 0); HostResource host = allocateSingleNodeHost(cluster, log, containerElement, context); node.setHostResource(host); if ( ! node.isInitialized() ) node.initService(); cluster.addContainers(Collections.singleton(node)); } else { List<Container> nodes = createNodes(cluster, nodesElement, context); applyNodesTagJvmArgs(nodes, nodesElement.getAttribute(VespaDomBuilder.JVMARGS_ATTRIB_NAME)); applyRoutingAliasProperties(nodes, cluster); applyDefaultPreload(nodes, nodesElement); applyMemoryPercentage(cluster, nodesElement.getAttribute(VespaDomBuilder.Allocated_MEMORY_ATTRIB_NAME)); if (useCpuSocketAffinity(nodesElement)) AbstractService.distributeCpuSocketAffinity(nodes); cluster.addContainers(nodes); } } private List<Container> createNodes(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { if (nodesElement.hasAttribute("count")) return createNodesFromNodeCount(cluster, nodesElement, context); else if (nodesElement.hasAttribute("type")) return createNodesFromNodeType(cluster, nodesElement, context); else if (nodesElement.hasAttribute("of")) return createNodesFromContentServiceReference(cluster, nodesElement, context); else return createNodesFromNodeList(cluster, nodesElement); } private void applyRoutingAliasProperties(List<Container> result, ContainerCluster cluster) { if (!cluster.serviceAliases().isEmpty()) { result.forEach(container -> { container.setProp("servicealiases", cluster.serviceAliases().stream().collect(Collectors.joining(","))); }); } if (!cluster.endpointAliases().isEmpty()) { result.forEach(container -> { container.setProp("endpointaliases", cluster.endpointAliases().stream().collect(Collectors.joining(","))); }); } } private void applyMemoryPercentage(ContainerCluster cluster, String memoryPercentage) { if (memoryPercentage == null || memoryPercentage.isEmpty()) return; memoryPercentage = memoryPercentage.trim(); if ( ! memoryPercentage.endsWith("%")) throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); memoryPercentage = memoryPercentage.substring(0, memoryPercentage.length()-1).trim(); try { cluster.setMemoryPercentage(Optional.of(Integer.parseInt(memoryPercentage))); } catch (NumberFormatException e) { throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); } } /** Creates a single host when there is no nodes tag */ private HostResource allocateSingleNodeHost(ContainerCluster cluster, DeployLogger logger, Element containerElement, ConfigModelContext context) { if (cluster.getRoot().getDeployState().isHosted()) { Optional<HostResource> singleContentHost = getHostResourceFromContentClusters(cluster, containerElement, context); if (singleContentHost.isPresent()) { return singleContentHost.get(); } else { ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); return cluster.getHostSystem().allocateHosts(clusterSpec, Capacity.fromNodeCount(1), 1, logger).keySet().iterator().next(); } } else { return cluster.getHostSystem().getHost(Container.SINGLENODE_CONTAINER_SERVICESPEC); } } private List<Container> createNodesFromNodeCount(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodesSpecification nodesSpecification = NodesSpecification.from(new ModelElement(nodesElement), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = nodesSpecification.provision(cluster.getRoot().getHostSystem(), ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromNodeType(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodeType type = NodeType.valueOf(nodesElement.getAttribute("type")); ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = cluster.getRoot().getHostSystem().allocateHosts(clusterSpec, Capacity.fromRequiredNodeType(type), 1, log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromContentServiceReference(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { String referenceId = nodesElement.getAttribute("of"); Element services = servicesRootOf(nodesElement).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); Element referencedService = findChildById(services, referenceId).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); if ( ! referencedService.getTagName().equals("content")) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "', " + "but that is not a content service"); Element referencedNodesElement = XML.getChild(referencedService, "nodes"); if (referencedNodesElement == null) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "' to supply nodes, " + "but that service has no <nodes> element"); cluster.setHostClusterId(referenceId); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(NodesSpecification.from(new ModelElement(referencedNodesElement), context.getDeployState().getWantedNodeVespaVersion()), referenceId, cluster.getRoot().getHostSystem(), context.getDeployLogger()); return createNodesFromHosts(hosts, cluster); } /** * This is used in case we are on hosted Vespa and no nodes tag is supplied: * If there are content clusters this will pick the first host in the first cluster as the container node. * If there are no content clusters this will return empty (such that the node can be created by the container here). */ private Optional<HostResource> getHostResourceFromContentClusters(ContainerCluster cluster, Element containersElement, ConfigModelContext context) { Optional<Element> services = servicesRootOf(containersElement); if ( ! services.isPresent()) return Optional.empty(); List<Element> contentServices = XML.getChildren(services.get(), "content"); if ( contentServices.isEmpty() ) return Optional.empty(); Element contentNodesElementOrNull = XML.getChild(contentServices.get(0), "nodes"); NodesSpecification nodesSpec; if (contentNodesElementOrNull == null) nodesSpec = NodesSpecification.nonDedicated(1, context.getDeployState().getWantedNodeVespaVersion()); else nodesSpec = NodesSpecification.from(new ModelElement(contentNodesElementOrNull), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(nodesSpec, contentServices.get(0).getAttribute("id"), cluster.getRoot().getHostSystem(), context.getDeployLogger()); return Optional.of(hosts.keySet().iterator().next()); } /** Returns the services element above the given Element, or empty if there is no services element */ private Optional<Element> servicesRootOf(Element element) { Node parent = element.getParentNode(); if (parent == null) return Optional.empty(); if ( ! (parent instanceof Element)) return Optional.empty(); Element parentElement = (Element)parent; if (parentElement.getTagName().equals("services")) return Optional.of(parentElement); return servicesRootOf(parentElement); } private List<Container> createNodesFromHosts(Map<HostResource, ClusterMembership> hosts, ContainerCluster cluster) { List<Container> nodes = new ArrayList<>(); for (Map.Entry<HostResource, ClusterMembership> entry : hosts.entrySet()) { String id = "container." + entry.getValue().index(); Container container = new Container(cluster, id, entry.getValue().retired(), entry.getValue().index()); container.setHostResource(entry.getKey()); container.initService(); nodes.add(container); } return nodes; } private List<Container> createNodesFromNodeList(ContainerCluster cluster, Element nodesElement) { List<Container> nodes = new ArrayList<>(); int nodeIndex = 0; for (Element nodeElem: XML.getChildren(nodesElement, "node")) { nodes.add(new ContainerServiceBuilder("container." + nodeIndex, nodeIndex).build(cluster, nodeElem)); nodeIndex++; } return nodes; } private IllegalArgumentException clusterReferenceNotFoundException(ContainerCluster cluster, String referenceId) { return new IllegalArgumentException(cluster + " references service '" + referenceId + "' but this service is not defined"); } private Optional<Element> findChildById(Element parent, String id) { for (Element child : XML.getChildren(parent)) if (id.equals(child.getAttribute("id"))) return Optional.of(child); return Optional.empty(); } private boolean useCpuSocketAffinity(Element nodesElement) { if (nodesElement.hasAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)) return Boolean.parseBoolean(nodesElement.getAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)); else return false; } private void applyNodesTagJvmArgs(List<Container> containers, String nodesTagJvnArgs) { for (Container container: containers) { if (container.getAssignedJvmArgs().isEmpty()) container.prependJvmArgs(nodesTagJvnArgs); } } private void applyDefaultPreload(List<Container> containers, Element nodesElement) { if (! nodesElement.hasAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)) return; for (Container container: containers) container.setPreLoad(nodesElement.getAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)); } private void addSearchHandler(ContainerCluster cluster, Element searchElement) { ProcessingHandler<SearchChains> searchHandler = new ProcessingHandler<>( cluster.getSearch().getChains(), "com.yahoo.search.handler.SearchHandler"); String[] defaultBindings = {"http: for (String binding: serverBindings(searchElement, defaultBindings)) { searchHandler.addServerBindings(binding); } cluster.addComponent(searchHandler); } private String[] serverBindings(Element searchElement, String... defaultBindings) { List<Element> bindings = XML.getChildren(searchElement, "binding"); if (bindings.isEmpty()) return defaultBindings; return toBindingList(bindings); } private String[] toBindingList(List<Element> bindingElements) { List<String> result = new ArrayList<>(); for (Element element: bindingElements) { String text = element.getTextContent().trim(); if (!text.isEmpty()) result.add(text); } return result.toArray(new String[result.size()]); } private ContainerDocumentApi buildDocumentApi(ContainerCluster cluster, Element spec) { Element documentApiElement = XML.getChild(spec, "document-api"); if (documentApiElement == null) return null; ContainerDocumentApi.Options documentApiOptions = DocumentApiOptionsBuilder.build(documentApiElement); return new ContainerDocumentApi(cluster, documentApiOptions); } private ContainerDocproc buildDocproc(ContainerCluster cluster, Element spec) { Element docprocElement = XML.getChild(spec, "document-processing"); if (docprocElement == null) return null; addIncludes(docprocElement); DocprocChains chains = new DomDocprocChainsBuilder(null, false).build(cluster, docprocElement); ContainerDocproc.Options docprocOptions = DocprocOptionsBuilder.build(docprocElement); return new ContainerDocproc(cluster, chains, docprocOptions, !standaloneBuilder); } private void addIncludes(Element parentElement) { List<Element> includes = XML.getChildren(parentElement, IncludeDirs.INCLUDE); if (includes == null || includes.isEmpty()) { return; } if (app == null) { throw new IllegalArgumentException("Element <include> given in XML config, but no application package given."); } for (Element include : includes) { addInclude(parentElement, include); } } private void addInclude(Element parentElement, Element include) { String dirName = include.getAttribute(IncludeDirs.DIR); app.validateIncludeDir(dirName); List<Element> includedFiles = Xml.allElemsFromPath(app, dirName); for (Element includedFile : includedFiles) { List<Element> includedSubElements = XML.getChildren(includedFile); for (Element includedSubElement : includedSubElements) { Node copiedNode = parentElement.getOwnerDocument().importNode(includedSubElement, true); parentElement.appendChild(copiedNode); } } } public static void addConfiguredComponents(ContainerCluster cluster, Element spec, String componentName) { for (Element node : XML.getChildren(spec, componentName)) { cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } public static void validateAndAddConfiguredComponents(ContainerCluster cluster, Element spec, String componentName, Consumer<Element> elementValidator) { for (Element node : XML.getChildren(spec, componentName)) { elementValidator.accept(node); cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } private void addIdentity(Element element, ContainerCluster cluster, DeployProperties deployProperties) { Element identityElement = XML.getChild(element, "identity"); if(identityElement != null) { String domain = XML.getValue(XML.getChild(identityElement, "domain")); String service = XML.getValue(XML.getChild(identityElement, "service")); logger.log(LogLevel.INFO, String.format("loadBalancerAddress: %s", deployProperties.loadBalancerAddress())); String cfgHostName = deployProperties.configServerSpecs().stream().findFirst().map(ConfigServerSpec::getHostName) .orElse(""); Identity identity = new Identity(domain.trim(), service.trim(), cfgHostName); cluster.addComponent(identity); } } /** * Disallow renderers named "DefaultRenderer" or "JsonRenderer" */ private static void validateRendererElement(Element element) { String idAttr = element.getAttribute("id"); if (idAttr.equals(xmlRendererId) || idAttr.equals(jsonRendererId)) { throw new IllegalArgumentException(String.format("Renderer id %s is reserved for internal use", idAttr)); } } }
class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> { /** * Default path to vip status file for container in Hosted Vespa. */ static final String HOSTED_VESPA_STATUS_FILE = Defaults.getDefaults().underVespaHome("var/mediasearch/oor/status.html"); /** * Path to vip status file for container in Hosted Vespa. Only used if set, else use HOSTED_VESPA_STATUS_FILE */ static final String HOSTED_VESPA_STATUS_FILE_YINST_SETTING = "cloudconfig_server__tenant_vip_status_file"; public enum Networking { disable, enable } private ApplicationPackage app; private final boolean standaloneBuilder; private final Networking networking; protected DeployLogger log; public static final List<ConfigModelId> configModelIds = ImmutableList.of(ConfigModelId.fromName("container"), ConfigModelId.fromName("jdisc")); private static final String xmlRendererId = RendererRegistry.xmlRendererId.getName(); private static final String jsonRendererId = RendererRegistry.jsonRendererId.getName(); private static final Logger logger = Logger.getLogger(ContainerModelBuilder.class.getName()); public ContainerModelBuilder(boolean standaloneBuilder, Networking networking) { super(ContainerModel.class); this.standaloneBuilder = standaloneBuilder; this.networking = networking; } @Override public List<ConfigModelId> handlesElements() { return configModelIds; } @Override public void doBuild(ContainerModel model, Element spec, ConfigModelContext modelContext) { app = modelContext.getApplicationPackage(); checkVersion(spec); this.log = modelContext.getDeployLogger(); ContainerCluster cluster = createContainerCluster(spec, modelContext); addClusterContent(cluster, spec, modelContext); addBundlesForPlatformComponents(cluster); model.setCluster(cluster); } protected void addBundlesForPlatformComponents(ContainerCluster cluster) { for (Component<?, ?> component : cluster.getAllComponents()) { String componentClass = component.model.bundleInstantiationSpec.getClassName(); BundleMapper.getBundlePath(componentClass). ifPresent(cluster::addPlatformBundle); } } private ContainerCluster createContainerCluster(Element spec, final ConfigModelContext modelContext) { return new VespaDomBuilder.DomConfigProducerBuilder<ContainerCluster>() { @Override protected ContainerCluster doBuild(AbstractConfigProducer ancestor, Element producerSpec) { return new ContainerCluster(ancestor, modelContext.getProducerId(), modelContext.getProducerId()); } }.build(modelContext.getParentProducer(), spec); } private void addRoutingAliases(ContainerCluster cluster, Element spec, Environment environment) { if (environment != Environment.prod) return; Element aliases = XML.getChild(spec, "aliases"); for (Element alias : XML.getChildren(aliases, "service-alias")) { cluster.serviceAliases().add(XML.getValue(alias)); } for (Element alias : XML.getChildren(aliases, "endpoint-alias")) { cluster.endpointAliases().add(XML.getValue(alias)); } } private void addConfiguredComponents(ContainerCluster cluster, Element spec) { for (Element components : XML.getChildren(spec, "components")) { addIncludes(components); addConfiguredComponents(cluster, components, "component"); } addConfiguredComponents(cluster, spec, "component"); } protected void addDefaultComponents(ContainerCluster cluster) { } protected void setDefaultMetricConsumerFactory(ContainerCluster cluster) { cluster.setDefaultMetricConsumerFactory(MetricDefaultsConfig.Factory.Enum.STATE_MONITOR); } protected void addDefaultHandlers(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); } protected void addStatusHandlers(ContainerCluster cluster, ConfigModelContext configModelContext) { if (configModelContext.getDeployState().isHosted()) { String name = "status.html"; Optional<String> statusFile = Optional.ofNullable(System.getenv(HOSTED_VESPA_STATUS_FILE_YINST_SETTING)); cluster.addComponent( new FileStatusHandlerComponent(name + "-status-handler", statusFile.orElse(HOSTED_VESPA_STATUS_FILE), "http: } else { cluster.addVipHandler(); } } /** * Intended for use by legacy builders only. * Will be called during building when using ContainerModelBuilder. */ public static void addDefaultHandler_legacyBuilder(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); cluster.addVipHandler(); } protected static void addDefaultHandlersExceptStatus(ContainerCluster cluster) { cluster.addDefaultRootHandler(); cluster.addMetricStateHandler(); cluster.addApplicationStatusHandler(); cluster.addStatisticsHandler(); } private void addClientProviders(Element spec, ContainerCluster cluster) { for (Element clientSpec: XML.getChildren(spec, "client")) { cluster.addComponent(new DomClientProviderBuilder().build(cluster, clientSpec)); } } private void addServerProviders(Element spec, ContainerCluster cluster) { addConfiguredComponents(cluster, spec, "server"); } private void addLegacyFilters(Element spec, ContainerCluster cluster) { for (Component component : buildLegacyFilters(cluster, spec)) { cluster.addComponent(component); } } private List<Component> buildLegacyFilters(AbstractConfigProducer ancestor, Element spec) { List<Component> components = new ArrayList<>(); for (Element node : XML.getChildren(spec, "filter")) { components.add(new DomFilterBuilder().build(ancestor, node)); } return components; } protected void addAccessLogs(ContainerCluster cluster, Element spec) { List<Element> accessLogElements = getAccessLogElements(spec); for (Element accessLog : accessLogElements) { AccessLogBuilder.buildIfNotDisabled(cluster, accessLog).ifPresent(cluster::addComponent); } if (accessLogElements.isEmpty() && cluster.getSearch() != null) cluster.addDefaultSearchAccessLog(); } protected final List<Element> getAccessLogElements(Element spec) { return XML.getChildren(spec, "accesslog"); } protected void addHttp(Element spec, ContainerCluster cluster) { Element httpElement = XML.getChild(spec, "http"); if (httpElement != null) { cluster.setHttp(buildHttp(cluster, httpElement)); } } private Http buildHttp(ContainerCluster cluster, Element httpElement) { Http http = new HttpBuilder().build(cluster, httpElement); if (networking == Networking.disable) http.removeAllServers(); return http; } protected void addRestApis(Element spec, ContainerCluster cluster) { for (Element restApiElem : XML.getChildren(spec, "rest-api")) { cluster.addRestApi( new RestApiBuilder().build(cluster, restApiElem)); } } private void addServlets(Element spec, ContainerCluster cluster) { for (Element servletElem : XML.getChildren(spec, "servlet")) { cluster.addServlet( new ServletBuilder().build(cluster, servletElem)); } } private void addDocumentApi(Element spec, ContainerCluster cluster) { ContainerDocumentApi containerDocumentApi = buildDocumentApi(cluster, spec); if (containerDocumentApi != null) { cluster.setDocumentApi(containerDocumentApi); } } private void addDocproc(Element spec, ContainerCluster cluster) { ContainerDocproc containerDocproc = buildDocproc(cluster, spec); if (containerDocproc != null) { cluster.setDocproc(containerDocproc); ContainerDocproc.Options docprocOptions = containerDocproc.options; cluster.setMbusParams(new ContainerCluster.MbusParams( docprocOptions.maxConcurrentFactor, docprocOptions.documentExpansionFactor, docprocOptions.containerCoreMemory)); } } private void addSearch(Element spec, ContainerCluster cluster, QueryProfiles queryProfiles, SemanticRules semanticRules) { Element searchElement = XML.getChild(spec, "search"); if (searchElement != null) { addIncludes(searchElement); cluster.setSearch(buildSearch(cluster, searchElement, queryProfiles, semanticRules)); addSearchHandler(cluster, searchElement); validateAndAddConfiguredComponents(cluster, searchElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private void addProcessing(Element spec, ContainerCluster cluster) { Element processingElement = XML.getChild(spec, "processing"); if (processingElement != null) { addIncludes(processingElement); cluster.setProcessingChains(new DomProcessingBuilder(null).build(cluster, processingElement), serverBindings(processingElement, ProcessingChains.defaultBindings)); validateAndAddConfiguredComponents(cluster, processingElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private ContainerSearch buildSearch(ContainerCluster containerCluster, Element producerSpec, QueryProfiles queryProfiles, SemanticRules semanticRules) { SearchChains searchChains = new DomSearchChainsBuilder(null, false).build(containerCluster, producerSpec); ContainerSearch containerSearch = new ContainerSearch(containerCluster, searchChains, new ContainerSearch.Options()); applyApplicationPackageDirectoryConfigs(containerCluster.getRoot().getDeployState().getApplicationPackage(), containerSearch); containerSearch.setQueryProfiles(queryProfiles); containerSearch.setSemanticRules(semanticRules); return containerSearch; } private void applyApplicationPackageDirectoryConfigs(ApplicationPackage applicationPackage,ContainerSearch containerSearch) { PageTemplates.validate(applicationPackage); containerSearch.setPageTemplates(PageTemplates.create(applicationPackage)); } private void addHandlers(ContainerCluster cluster, Element spec) { for (Element component: XML.getChildren(spec, "handler")) { cluster.addComponent( new DomHandlerBuilder().build(cluster, component)); } } private void checkVersion(Element spec) { String version = spec.getAttribute("version"); if ( ! Version.fromString(version).equals(new Version(1))) { throw new RuntimeException("Expected container version to be 1.0, but got " + version); } } private void addNodes(ContainerCluster cluster, Element spec, ConfigModelContext context) { if (standaloneBuilder) addStandaloneNode(cluster); else addNodesFromXml(cluster, spec, context); } private void addStandaloneNode(ContainerCluster cluster) { Container container = new Container(cluster, "standalone", cluster.getContainers().size()); cluster.addContainers(Collections.singleton(container)); } private void addNodesFromXml(ContainerCluster cluster, Element containerElement, ConfigModelContext context) { Element nodesElement = XML.getChild(containerElement, "nodes"); if (nodesElement == null) { Container node = new Container(cluster, "container.0", 0); HostResource host = allocateSingleNodeHost(cluster, log, containerElement, context); node.setHostResource(host); if ( ! node.isInitialized() ) node.initService(); cluster.addContainers(Collections.singleton(node)); } else { List<Container> nodes = createNodes(cluster, nodesElement, context); applyNodesTagJvmArgs(nodes, nodesElement.getAttribute(VespaDomBuilder.JVMARGS_ATTRIB_NAME)); applyRoutingAliasProperties(nodes, cluster); applyDefaultPreload(nodes, nodesElement); applyMemoryPercentage(cluster, nodesElement.getAttribute(VespaDomBuilder.Allocated_MEMORY_ATTRIB_NAME)); if (useCpuSocketAffinity(nodesElement)) AbstractService.distributeCpuSocketAffinity(nodes); cluster.addContainers(nodes); } } private List<Container> createNodes(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { if (nodesElement.hasAttribute("count")) return createNodesFromNodeCount(cluster, nodesElement, context); else if (nodesElement.hasAttribute("type")) return createNodesFromNodeType(cluster, nodesElement, context); else if (nodesElement.hasAttribute("of")) return createNodesFromContentServiceReference(cluster, nodesElement, context); else return createNodesFromNodeList(cluster, nodesElement); } private void applyRoutingAliasProperties(List<Container> result, ContainerCluster cluster) { if (!cluster.serviceAliases().isEmpty()) { result.forEach(container -> { container.setProp("servicealiases", cluster.serviceAliases().stream().collect(Collectors.joining(","))); }); } if (!cluster.endpointAliases().isEmpty()) { result.forEach(container -> { container.setProp("endpointaliases", cluster.endpointAliases().stream().collect(Collectors.joining(","))); }); } } private void applyMemoryPercentage(ContainerCluster cluster, String memoryPercentage) { if (memoryPercentage == null || memoryPercentage.isEmpty()) return; memoryPercentage = memoryPercentage.trim(); if ( ! memoryPercentage.endsWith("%")) throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); memoryPercentage = memoryPercentage.substring(0, memoryPercentage.length()-1).trim(); try { cluster.setMemoryPercentage(Optional.of(Integer.parseInt(memoryPercentage))); } catch (NumberFormatException e) { throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); } } /** Creates a single host when there is no nodes tag */ private HostResource allocateSingleNodeHost(ContainerCluster cluster, DeployLogger logger, Element containerElement, ConfigModelContext context) { if (cluster.getRoot().getDeployState().isHosted()) { Optional<HostResource> singleContentHost = getHostResourceFromContentClusters(cluster, containerElement, context); if (singleContentHost.isPresent()) { return singleContentHost.get(); } else { ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); return cluster.getHostSystem().allocateHosts(clusterSpec, Capacity.fromNodeCount(1), 1, logger).keySet().iterator().next(); } } else { return cluster.getHostSystem().getHost(Container.SINGLENODE_CONTAINER_SERVICESPEC); } } private List<Container> createNodesFromNodeCount(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodesSpecification nodesSpecification = NodesSpecification.from(new ModelElement(nodesElement), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = nodesSpecification.provision(cluster.getRoot().getHostSystem(), ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromNodeType(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodeType type = NodeType.valueOf(nodesElement.getAttribute("type")); ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = cluster.getRoot().getHostSystem().allocateHosts(clusterSpec, Capacity.fromRequiredNodeType(type), 1, log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromContentServiceReference(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { String referenceId = nodesElement.getAttribute("of"); Element services = servicesRootOf(nodesElement).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); Element referencedService = findChildById(services, referenceId).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); if ( ! referencedService.getTagName().equals("content")) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "', " + "but that is not a content service"); Element referencedNodesElement = XML.getChild(referencedService, "nodes"); if (referencedNodesElement == null) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "' to supply nodes, " + "but that service has no <nodes> element"); cluster.setHostClusterId(referenceId); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(NodesSpecification.from(new ModelElement(referencedNodesElement), context.getDeployState().getWantedNodeVespaVersion()), referenceId, cluster.getRoot().getHostSystem(), context.getDeployLogger()); return createNodesFromHosts(hosts, cluster); } /** * This is used in case we are on hosted Vespa and no nodes tag is supplied: * If there are content clusters this will pick the first host in the first cluster as the container node. * If there are no content clusters this will return empty (such that the node can be created by the container here). */ private Optional<HostResource> getHostResourceFromContentClusters(ContainerCluster cluster, Element containersElement, ConfigModelContext context) { Optional<Element> services = servicesRootOf(containersElement); if ( ! services.isPresent()) return Optional.empty(); List<Element> contentServices = XML.getChildren(services.get(), "content"); if ( contentServices.isEmpty() ) return Optional.empty(); Element contentNodesElementOrNull = XML.getChild(contentServices.get(0), "nodes"); NodesSpecification nodesSpec; if (contentNodesElementOrNull == null) nodesSpec = NodesSpecification.nonDedicated(1, context.getDeployState().getWantedNodeVespaVersion()); else nodesSpec = NodesSpecification.from(new ModelElement(contentNodesElementOrNull), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(nodesSpec, contentServices.get(0).getAttribute("id"), cluster.getRoot().getHostSystem(), context.getDeployLogger()); return Optional.of(hosts.keySet().iterator().next()); } /** Returns the services element above the given Element, or empty if there is no services element */ private Optional<Element> servicesRootOf(Element element) { Node parent = element.getParentNode(); if (parent == null) return Optional.empty(); if ( ! (parent instanceof Element)) return Optional.empty(); Element parentElement = (Element)parent; if (parentElement.getTagName().equals("services")) return Optional.of(parentElement); return servicesRootOf(parentElement); } private List<Container> createNodesFromHosts(Map<HostResource, ClusterMembership> hosts, ContainerCluster cluster) { List<Container> nodes = new ArrayList<>(); for (Map.Entry<HostResource, ClusterMembership> entry : hosts.entrySet()) { String id = "container." + entry.getValue().index(); Container container = new Container(cluster, id, entry.getValue().retired(), entry.getValue().index()); container.setHostResource(entry.getKey()); container.initService(); nodes.add(container); } return nodes; } private List<Container> createNodesFromNodeList(ContainerCluster cluster, Element nodesElement) { List<Container> nodes = new ArrayList<>(); int nodeIndex = 0; for (Element nodeElem: XML.getChildren(nodesElement, "node")) { nodes.add(new ContainerServiceBuilder("container." + nodeIndex, nodeIndex).build(cluster, nodeElem)); nodeIndex++; } return nodes; } private IllegalArgumentException clusterReferenceNotFoundException(ContainerCluster cluster, String referenceId) { return new IllegalArgumentException(cluster + " references service '" + referenceId + "' but this service is not defined"); } private Optional<Element> findChildById(Element parent, String id) { for (Element child : XML.getChildren(parent)) if (id.equals(child.getAttribute("id"))) return Optional.of(child); return Optional.empty(); } private boolean useCpuSocketAffinity(Element nodesElement) { if (nodesElement.hasAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)) return Boolean.parseBoolean(nodesElement.getAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)); else return false; } private void applyNodesTagJvmArgs(List<Container> containers, String nodesTagJvnArgs) { for (Container container: containers) { if (container.getAssignedJvmArgs().isEmpty()) container.prependJvmArgs(nodesTagJvnArgs); } } private void applyDefaultPreload(List<Container> containers, Element nodesElement) { if (! nodesElement.hasAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)) return; for (Container container: containers) container.setPreLoad(nodesElement.getAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)); } private void addSearchHandler(ContainerCluster cluster, Element searchElement) { ProcessingHandler<SearchChains> searchHandler = new ProcessingHandler<>( cluster.getSearch().getChains(), "com.yahoo.search.handler.SearchHandler"); String[] defaultBindings = {"http: for (String binding: serverBindings(searchElement, defaultBindings)) { searchHandler.addServerBindings(binding); } cluster.addComponent(searchHandler); } private String[] serverBindings(Element searchElement, String... defaultBindings) { List<Element> bindings = XML.getChildren(searchElement, "binding"); if (bindings.isEmpty()) return defaultBindings; return toBindingList(bindings); } private String[] toBindingList(List<Element> bindingElements) { List<String> result = new ArrayList<>(); for (Element element: bindingElements) { String text = element.getTextContent().trim(); if (!text.isEmpty()) result.add(text); } return result.toArray(new String[result.size()]); } private ContainerDocumentApi buildDocumentApi(ContainerCluster cluster, Element spec) { Element documentApiElement = XML.getChild(spec, "document-api"); if (documentApiElement == null) return null; ContainerDocumentApi.Options documentApiOptions = DocumentApiOptionsBuilder.build(documentApiElement); return new ContainerDocumentApi(cluster, documentApiOptions); } private ContainerDocproc buildDocproc(ContainerCluster cluster, Element spec) { Element docprocElement = XML.getChild(spec, "document-processing"); if (docprocElement == null) return null; addIncludes(docprocElement); DocprocChains chains = new DomDocprocChainsBuilder(null, false).build(cluster, docprocElement); ContainerDocproc.Options docprocOptions = DocprocOptionsBuilder.build(docprocElement); return new ContainerDocproc(cluster, chains, docprocOptions, !standaloneBuilder); } private void addIncludes(Element parentElement) { List<Element> includes = XML.getChildren(parentElement, IncludeDirs.INCLUDE); if (includes == null || includes.isEmpty()) { return; } if (app == null) { throw new IllegalArgumentException("Element <include> given in XML config, but no application package given."); } for (Element include : includes) { addInclude(parentElement, include); } } private void addInclude(Element parentElement, Element include) { String dirName = include.getAttribute(IncludeDirs.DIR); app.validateIncludeDir(dirName); List<Element> includedFiles = Xml.allElemsFromPath(app, dirName); for (Element includedFile : includedFiles) { List<Element> includedSubElements = XML.getChildren(includedFile); for (Element includedSubElement : includedSubElements) { Node copiedNode = parentElement.getOwnerDocument().importNode(includedSubElement, true); parentElement.appendChild(copiedNode); } } } public static void addConfiguredComponents(ContainerCluster cluster, Element spec, String componentName) { for (Element node : XML.getChildren(spec, componentName)) { cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } public static void validateAndAddConfiguredComponents(ContainerCluster cluster, Element spec, String componentName, Consumer<Element> elementValidator) { for (Element node : XML.getChildren(spec, componentName)) { elementValidator.accept(node); cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } private void addIdentity(Element element, ContainerCluster cluster, List<ConfigServerSpec> configServerSpecs, URI loadBalancerAddress) { Element identityElement = XML.getChild(element, "identity"); if(identityElement != null) { String domain = XML.getValue(XML.getChild(identityElement, "domain")); String service = XML.getValue(XML.getChild(identityElement, "service")); logger.log(LogLevel.INFO, String.format("loadBalancerAddress: %s", loadBalancerAddress)); String cfgHostName = configServerSpecs.stream().findFirst().map(ConfigServerSpec::getHostName) .orElse(""); Identity identity = new Identity(domain.trim(), service.trim(), cfgHostName); cluster.addComponent(identity); cluster.getContainers().forEach(container -> { container.setProp("identity.domain", domain); container.setProp("identity.service", service); }); } } /** * Disallow renderers named "DefaultRenderer" or "JsonRenderer" */ private static void validateRendererElement(Element element) { String idAttr = element.getAttribute("id"); if (idAttr.equals(xmlRendererId) || idAttr.equals(jsonRendererId)) { throw new IllegalArgumentException(String.format("Renderer id %s is reserved for internal use", idAttr)); } } }
fixed
private void addClusterContent(ContainerCluster cluster, Element spec, ConfigModelContext context) { DocumentFactoryBuilder.buildDocumentFactories(cluster, spec); addConfiguredComponents(cluster, spec); addHandlers(cluster, spec); addRestApis(spec, cluster); addServlets(spec, cluster); addProcessing(spec, cluster); addSearch(spec, cluster, context.getDeployState().getQueryProfiles(), context.getDeployState().getSemanticRules()); addDocproc(spec, cluster); addDocumentApi(spec, cluster); addDefaultHandlers(cluster); addStatusHandlers(cluster, context); addDefaultComponents(cluster); setDefaultMetricConsumerFactory(cluster); addHttp(spec, cluster); addAccessLogs(cluster, spec); addRoutingAliases(cluster, spec, context.getDeployState().zone().environment()); addNodes(cluster, spec, context); addClientProviders(spec, cluster); addServerProviders(spec, cluster); addLegacyFilters(spec, cluster); addIdentity(spec, cluster, context.getDeployState().getProperties()); }
addIdentity(spec, cluster, context.getDeployState().getProperties());
private void addClusterContent(ContainerCluster cluster, Element spec, ConfigModelContext context) { DocumentFactoryBuilder.buildDocumentFactories(cluster, spec); addConfiguredComponents(cluster, spec); addHandlers(cluster, spec); addRestApis(spec, cluster); addServlets(spec, cluster); addProcessing(spec, cluster); addSearch(spec, cluster, context.getDeployState().getQueryProfiles(), context.getDeployState().getSemanticRules()); addDocproc(spec, cluster); addDocumentApi(spec, cluster); addDefaultHandlers(cluster); addStatusHandlers(cluster, context); addDefaultComponents(cluster); setDefaultMetricConsumerFactory(cluster); addHttp(spec, cluster); addAccessLogs(cluster, spec); addRoutingAliases(cluster, spec, context.getDeployState().zone().environment()); addNodes(cluster, spec, context); addClientProviders(spec, cluster); addServerProviders(spec, cluster); addLegacyFilters(spec, cluster); addIdentity(spec, cluster, context.getDeployState().getProperties().configServerSpecs(), context.getDeployState().getProperties().loadBalancerAddress()); }
class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> { /** * Default path to vip status file for container in Hosted Vespa. */ static final String HOSTED_VESPA_STATUS_FILE = Defaults.getDefaults().underVespaHome("var/mediasearch/oor/status.html"); /** * Path to vip status file for container in Hosted Vespa. Only used if set, else use HOSTED_VESPA_STATUS_FILE */ static final String HOSTED_VESPA_STATUS_FILE_YINST_SETTING = "cloudconfig_server__tenant_vip_status_file"; public enum Networking { disable, enable } private ApplicationPackage app; private final boolean standaloneBuilder; private final Networking networking; protected DeployLogger log; public static final List<ConfigModelId> configModelIds = ImmutableList.of(ConfigModelId.fromName("container"), ConfigModelId.fromName("jdisc")); private static final String xmlRendererId = RendererRegistry.xmlRendererId.getName(); private static final String jsonRendererId = RendererRegistry.jsonRendererId.getName(); private static final Logger logger = Logger.getLogger(ContainerCluster.class.getName()); public ContainerModelBuilder(boolean standaloneBuilder, Networking networking) { super(ContainerModel.class); this.standaloneBuilder = standaloneBuilder; this.networking = networking; } @Override public List<ConfigModelId> handlesElements() { return configModelIds; } @Override public void doBuild(ContainerModel model, Element spec, ConfigModelContext modelContext) { app = modelContext.getApplicationPackage(); checkVersion(spec); this.log = modelContext.getDeployLogger(); ContainerCluster cluster = createContainerCluster(spec, modelContext); addClusterContent(cluster, spec, modelContext); addBundlesForPlatformComponents(cluster); model.setCluster(cluster); } protected void addBundlesForPlatformComponents(ContainerCluster cluster) { for (Component<?, ?> component : cluster.getAllComponents()) { String componentClass = component.model.bundleInstantiationSpec.getClassName(); BundleMapper.getBundlePath(componentClass). ifPresent(cluster::addPlatformBundle); } } private ContainerCluster createContainerCluster(Element spec, final ConfigModelContext modelContext) { return new VespaDomBuilder.DomConfigProducerBuilder<ContainerCluster>() { @Override protected ContainerCluster doBuild(AbstractConfigProducer ancestor, Element producerSpec) { return new ContainerCluster(ancestor, modelContext.getProducerId(), modelContext.getProducerId()); } }.build(modelContext.getParentProducer(), spec); } private void addRoutingAliases(ContainerCluster cluster, Element spec, Environment environment) { if (environment != Environment.prod) return; Element aliases = XML.getChild(spec, "aliases"); for (Element alias : XML.getChildren(aliases, "service-alias")) { cluster.serviceAliases().add(XML.getValue(alias)); } for (Element alias : XML.getChildren(aliases, "endpoint-alias")) { cluster.endpointAliases().add(XML.getValue(alias)); } } private void addConfiguredComponents(ContainerCluster cluster, Element spec) { for (Element components : XML.getChildren(spec, "components")) { addIncludes(components); addConfiguredComponents(cluster, components, "component"); } addConfiguredComponents(cluster, spec, "component"); } protected void addDefaultComponents(ContainerCluster cluster) { } protected void setDefaultMetricConsumerFactory(ContainerCluster cluster) { cluster.setDefaultMetricConsumerFactory(MetricDefaultsConfig.Factory.Enum.STATE_MONITOR); } protected void addDefaultHandlers(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); } protected void addStatusHandlers(ContainerCluster cluster, ConfigModelContext configModelContext) { if (configModelContext.getDeployState().isHosted()) { String name = "status.html"; Optional<String> statusFile = Optional.ofNullable(System.getenv(HOSTED_VESPA_STATUS_FILE_YINST_SETTING)); cluster.addComponent( new FileStatusHandlerComponent(name + "-status-handler", statusFile.orElse(HOSTED_VESPA_STATUS_FILE), "http: } else { cluster.addVipHandler(); } } /** * Intended for use by legacy builders only. * Will be called during building when using ContainerModelBuilder. */ public static void addDefaultHandler_legacyBuilder(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); cluster.addVipHandler(); } protected static void addDefaultHandlersExceptStatus(ContainerCluster cluster) { cluster.addDefaultRootHandler(); cluster.addMetricStateHandler(); cluster.addApplicationStatusHandler(); cluster.addStatisticsHandler(); } private void addClientProviders(Element spec, ContainerCluster cluster) { for (Element clientSpec: XML.getChildren(spec, "client")) { cluster.addComponent(new DomClientProviderBuilder().build(cluster, clientSpec)); } } private void addServerProviders(Element spec, ContainerCluster cluster) { addConfiguredComponents(cluster, spec, "server"); } private void addLegacyFilters(Element spec, ContainerCluster cluster) { for (Component component : buildLegacyFilters(cluster, spec)) { cluster.addComponent(component); } } private List<Component> buildLegacyFilters(AbstractConfigProducer ancestor, Element spec) { List<Component> components = new ArrayList<>(); for (Element node : XML.getChildren(spec, "filter")) { components.add(new DomFilterBuilder().build(ancestor, node)); } return components; } protected void addAccessLogs(ContainerCluster cluster, Element spec) { List<Element> accessLogElements = getAccessLogElements(spec); for (Element accessLog : accessLogElements) { AccessLogBuilder.buildIfNotDisabled(cluster, accessLog).ifPresent(cluster::addComponent); } if (accessLogElements.isEmpty() && cluster.getSearch() != null) cluster.addDefaultSearchAccessLog(); } protected final List<Element> getAccessLogElements(Element spec) { return XML.getChildren(spec, "accesslog"); } protected void addHttp(Element spec, ContainerCluster cluster) { Element httpElement = XML.getChild(spec, "http"); if (httpElement != null) { cluster.setHttp(buildHttp(cluster, httpElement)); } } private Http buildHttp(ContainerCluster cluster, Element httpElement) { Http http = new HttpBuilder().build(cluster, httpElement); if (networking == Networking.disable) http.removeAllServers(); return http; } protected void addRestApis(Element spec, ContainerCluster cluster) { for (Element restApiElem : XML.getChildren(spec, "rest-api")) { cluster.addRestApi( new RestApiBuilder().build(cluster, restApiElem)); } } private void addServlets(Element spec, ContainerCluster cluster) { for (Element servletElem : XML.getChildren(spec, "servlet")) { cluster.addServlet( new ServletBuilder().build(cluster, servletElem)); } } private void addDocumentApi(Element spec, ContainerCluster cluster) { ContainerDocumentApi containerDocumentApi = buildDocumentApi(cluster, spec); if (containerDocumentApi != null) { cluster.setDocumentApi(containerDocumentApi); } } private void addDocproc(Element spec, ContainerCluster cluster) { ContainerDocproc containerDocproc = buildDocproc(cluster, spec); if (containerDocproc != null) { cluster.setDocproc(containerDocproc); ContainerDocproc.Options docprocOptions = containerDocproc.options; cluster.setMbusParams(new ContainerCluster.MbusParams( docprocOptions.maxConcurrentFactor, docprocOptions.documentExpansionFactor, docprocOptions.containerCoreMemory)); } } private void addSearch(Element spec, ContainerCluster cluster, QueryProfiles queryProfiles, SemanticRules semanticRules) { Element searchElement = XML.getChild(spec, "search"); if (searchElement != null) { addIncludes(searchElement); cluster.setSearch(buildSearch(cluster, searchElement, queryProfiles, semanticRules)); addSearchHandler(cluster, searchElement); validateAndAddConfiguredComponents(cluster, searchElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private void addProcessing(Element spec, ContainerCluster cluster) { Element processingElement = XML.getChild(spec, "processing"); if (processingElement != null) { addIncludes(processingElement); cluster.setProcessingChains(new DomProcessingBuilder(null).build(cluster, processingElement), serverBindings(processingElement, ProcessingChains.defaultBindings)); validateAndAddConfiguredComponents(cluster, processingElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private ContainerSearch buildSearch(ContainerCluster containerCluster, Element producerSpec, QueryProfiles queryProfiles, SemanticRules semanticRules) { SearchChains searchChains = new DomSearchChainsBuilder(null, false).build(containerCluster, producerSpec); ContainerSearch containerSearch = new ContainerSearch(containerCluster, searchChains, new ContainerSearch.Options()); applyApplicationPackageDirectoryConfigs(containerCluster.getRoot().getDeployState().getApplicationPackage(), containerSearch); containerSearch.setQueryProfiles(queryProfiles); containerSearch.setSemanticRules(semanticRules); return containerSearch; } private void applyApplicationPackageDirectoryConfigs(ApplicationPackage applicationPackage,ContainerSearch containerSearch) { PageTemplates.validate(applicationPackage); containerSearch.setPageTemplates(PageTemplates.create(applicationPackage)); } private void addHandlers(ContainerCluster cluster, Element spec) { for (Element component: XML.getChildren(spec, "handler")) { cluster.addComponent( new DomHandlerBuilder().build(cluster, component)); } } private void checkVersion(Element spec) { String version = spec.getAttribute("version"); if ( ! Version.fromString(version).equals(new Version(1))) { throw new RuntimeException("Expected container version to be 1.0, but got " + version); } } private void addNodes(ContainerCluster cluster, Element spec, ConfigModelContext context) { if (standaloneBuilder) addStandaloneNode(cluster); else addNodesFromXml(cluster, spec, context); } private void addStandaloneNode(ContainerCluster cluster) { Container container = new Container(cluster, "standalone", cluster.getContainers().size()); cluster.addContainers(Collections.singleton(container)); } private void addNodesFromXml(ContainerCluster cluster, Element containerElement, ConfigModelContext context) { Element nodesElement = XML.getChild(containerElement, "nodes"); if (nodesElement == null) { Container node = new Container(cluster, "container.0", 0); HostResource host = allocateSingleNodeHost(cluster, log, containerElement, context); node.setHostResource(host); if ( ! node.isInitialized() ) node.initService(); cluster.addContainers(Collections.singleton(node)); } else { List<Container> nodes = createNodes(cluster, nodesElement, context); applyNodesTagJvmArgs(nodes, nodesElement.getAttribute(VespaDomBuilder.JVMARGS_ATTRIB_NAME)); applyRoutingAliasProperties(nodes, cluster); applyDefaultPreload(nodes, nodesElement); applyMemoryPercentage(cluster, nodesElement.getAttribute(VespaDomBuilder.Allocated_MEMORY_ATTRIB_NAME)); if (useCpuSocketAffinity(nodesElement)) AbstractService.distributeCpuSocketAffinity(nodes); cluster.addContainers(nodes); } } private List<Container> createNodes(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { if (nodesElement.hasAttribute("count")) return createNodesFromNodeCount(cluster, nodesElement, context); else if (nodesElement.hasAttribute("type")) return createNodesFromNodeType(cluster, nodesElement, context); else if (nodesElement.hasAttribute("of")) return createNodesFromContentServiceReference(cluster, nodesElement, context); else return createNodesFromNodeList(cluster, nodesElement); } private void applyRoutingAliasProperties(List<Container> result, ContainerCluster cluster) { if (!cluster.serviceAliases().isEmpty()) { result.forEach(container -> { container.setProp("servicealiases", cluster.serviceAliases().stream().collect(Collectors.joining(","))); }); } if (!cluster.endpointAliases().isEmpty()) { result.forEach(container -> { container.setProp("endpointaliases", cluster.endpointAliases().stream().collect(Collectors.joining(","))); }); } } private void applyMemoryPercentage(ContainerCluster cluster, String memoryPercentage) { if (memoryPercentage == null || memoryPercentage.isEmpty()) return; memoryPercentage = memoryPercentage.trim(); if ( ! memoryPercentage.endsWith("%")) throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); memoryPercentage = memoryPercentage.substring(0, memoryPercentage.length()-1).trim(); try { cluster.setMemoryPercentage(Optional.of(Integer.parseInt(memoryPercentage))); } catch (NumberFormatException e) { throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); } } /** Creates a single host when there is no nodes tag */ private HostResource allocateSingleNodeHost(ContainerCluster cluster, DeployLogger logger, Element containerElement, ConfigModelContext context) { if (cluster.getRoot().getDeployState().isHosted()) { Optional<HostResource> singleContentHost = getHostResourceFromContentClusters(cluster, containerElement, context); if (singleContentHost.isPresent()) { return singleContentHost.get(); } else { ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); return cluster.getHostSystem().allocateHosts(clusterSpec, Capacity.fromNodeCount(1), 1, logger).keySet().iterator().next(); } } else { return cluster.getHostSystem().getHost(Container.SINGLENODE_CONTAINER_SERVICESPEC); } } private List<Container> createNodesFromNodeCount(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodesSpecification nodesSpecification = NodesSpecification.from(new ModelElement(nodesElement), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = nodesSpecification.provision(cluster.getRoot().getHostSystem(), ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromNodeType(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodeType type = NodeType.valueOf(nodesElement.getAttribute("type")); ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = cluster.getRoot().getHostSystem().allocateHosts(clusterSpec, Capacity.fromRequiredNodeType(type), 1, log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromContentServiceReference(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { String referenceId = nodesElement.getAttribute("of"); Element services = servicesRootOf(nodesElement).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); Element referencedService = findChildById(services, referenceId).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); if ( ! referencedService.getTagName().equals("content")) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "', " + "but that is not a content service"); Element referencedNodesElement = XML.getChild(referencedService, "nodes"); if (referencedNodesElement == null) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "' to supply nodes, " + "but that service has no <nodes> element"); cluster.setHostClusterId(referenceId); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(NodesSpecification.from(new ModelElement(referencedNodesElement), context.getDeployState().getWantedNodeVespaVersion()), referenceId, cluster.getRoot().getHostSystem(), context.getDeployLogger()); return createNodesFromHosts(hosts, cluster); } /** * This is used in case we are on hosted Vespa and no nodes tag is supplied: * If there are content clusters this will pick the first host in the first cluster as the container node. * If there are no content clusters this will return empty (such that the node can be created by the container here). */ private Optional<HostResource> getHostResourceFromContentClusters(ContainerCluster cluster, Element containersElement, ConfigModelContext context) { Optional<Element> services = servicesRootOf(containersElement); if ( ! services.isPresent()) return Optional.empty(); List<Element> contentServices = XML.getChildren(services.get(), "content"); if ( contentServices.isEmpty() ) return Optional.empty(); Element contentNodesElementOrNull = XML.getChild(contentServices.get(0), "nodes"); NodesSpecification nodesSpec; if (contentNodesElementOrNull == null) nodesSpec = NodesSpecification.nonDedicated(1, context.getDeployState().getWantedNodeVespaVersion()); else nodesSpec = NodesSpecification.from(new ModelElement(contentNodesElementOrNull), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(nodesSpec, contentServices.get(0).getAttribute("id"), cluster.getRoot().getHostSystem(), context.getDeployLogger()); return Optional.of(hosts.keySet().iterator().next()); } /** Returns the services element above the given Element, or empty if there is no services element */ private Optional<Element> servicesRootOf(Element element) { Node parent = element.getParentNode(); if (parent == null) return Optional.empty(); if ( ! (parent instanceof Element)) return Optional.empty(); Element parentElement = (Element)parent; if (parentElement.getTagName().equals("services")) return Optional.of(parentElement); return servicesRootOf(parentElement); } private List<Container> createNodesFromHosts(Map<HostResource, ClusterMembership> hosts, ContainerCluster cluster) { List<Container> nodes = new ArrayList<>(); for (Map.Entry<HostResource, ClusterMembership> entry : hosts.entrySet()) { String id = "container." + entry.getValue().index(); Container container = new Container(cluster, id, entry.getValue().retired(), entry.getValue().index()); container.setHostResource(entry.getKey()); container.initService(); nodes.add(container); } return nodes; } private List<Container> createNodesFromNodeList(ContainerCluster cluster, Element nodesElement) { List<Container> nodes = new ArrayList<>(); int nodeIndex = 0; for (Element nodeElem: XML.getChildren(nodesElement, "node")) { nodes.add(new ContainerServiceBuilder("container." + nodeIndex, nodeIndex).build(cluster, nodeElem)); nodeIndex++; } return nodes; } private IllegalArgumentException clusterReferenceNotFoundException(ContainerCluster cluster, String referenceId) { return new IllegalArgumentException(cluster + " references service '" + referenceId + "' but this service is not defined"); } private Optional<Element> findChildById(Element parent, String id) { for (Element child : XML.getChildren(parent)) if (id.equals(child.getAttribute("id"))) return Optional.of(child); return Optional.empty(); } private boolean useCpuSocketAffinity(Element nodesElement) { if (nodesElement.hasAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)) return Boolean.parseBoolean(nodesElement.getAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)); else return false; } private void applyNodesTagJvmArgs(List<Container> containers, String nodesTagJvnArgs) { for (Container container: containers) { if (container.getAssignedJvmArgs().isEmpty()) container.prependJvmArgs(nodesTagJvnArgs); } } private void applyDefaultPreload(List<Container> containers, Element nodesElement) { if (! nodesElement.hasAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)) return; for (Container container: containers) container.setPreLoad(nodesElement.getAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)); } private void addSearchHandler(ContainerCluster cluster, Element searchElement) { ProcessingHandler<SearchChains> searchHandler = new ProcessingHandler<>( cluster.getSearch().getChains(), "com.yahoo.search.handler.SearchHandler"); String[] defaultBindings = {"http: for (String binding: serverBindings(searchElement, defaultBindings)) { searchHandler.addServerBindings(binding); } cluster.addComponent(searchHandler); } private String[] serverBindings(Element searchElement, String... defaultBindings) { List<Element> bindings = XML.getChildren(searchElement, "binding"); if (bindings.isEmpty()) return defaultBindings; return toBindingList(bindings); } private String[] toBindingList(List<Element> bindingElements) { List<String> result = new ArrayList<>(); for (Element element: bindingElements) { String text = element.getTextContent().trim(); if (!text.isEmpty()) result.add(text); } return result.toArray(new String[result.size()]); } private ContainerDocumentApi buildDocumentApi(ContainerCluster cluster, Element spec) { Element documentApiElement = XML.getChild(spec, "document-api"); if (documentApiElement == null) return null; ContainerDocumentApi.Options documentApiOptions = DocumentApiOptionsBuilder.build(documentApiElement); return new ContainerDocumentApi(cluster, documentApiOptions); } private ContainerDocproc buildDocproc(ContainerCluster cluster, Element spec) { Element docprocElement = XML.getChild(spec, "document-processing"); if (docprocElement == null) return null; addIncludes(docprocElement); DocprocChains chains = new DomDocprocChainsBuilder(null, false).build(cluster, docprocElement); ContainerDocproc.Options docprocOptions = DocprocOptionsBuilder.build(docprocElement); return new ContainerDocproc(cluster, chains, docprocOptions, !standaloneBuilder); } private void addIncludes(Element parentElement) { List<Element> includes = XML.getChildren(parentElement, IncludeDirs.INCLUDE); if (includes == null || includes.isEmpty()) { return; } if (app == null) { throw new IllegalArgumentException("Element <include> given in XML config, but no application package given."); } for (Element include : includes) { addInclude(parentElement, include); } } private void addInclude(Element parentElement, Element include) { String dirName = include.getAttribute(IncludeDirs.DIR); app.validateIncludeDir(dirName); List<Element> includedFiles = Xml.allElemsFromPath(app, dirName); for (Element includedFile : includedFiles) { List<Element> includedSubElements = XML.getChildren(includedFile); for (Element includedSubElement : includedSubElements) { Node copiedNode = parentElement.getOwnerDocument().importNode(includedSubElement, true); parentElement.appendChild(copiedNode); } } } public static void addConfiguredComponents(ContainerCluster cluster, Element spec, String componentName) { for (Element node : XML.getChildren(spec, componentName)) { cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } public static void validateAndAddConfiguredComponents(ContainerCluster cluster, Element spec, String componentName, Consumer<Element> elementValidator) { for (Element node : XML.getChildren(spec, componentName)) { elementValidator.accept(node); cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } private void addIdentity(Element element, ContainerCluster cluster, DeployProperties deployProperties) { Element identityElement = XML.getChild(element, "identity"); if(identityElement != null) { String domain = XML.getValue(XML.getChild(identityElement, "domain")); String service = XML.getValue(XML.getChild(identityElement, "service")); logger.log(LogLevel.INFO, String.format("loadBalancerAddress: %s", deployProperties.loadBalancerAddress())); String cfgHostName = deployProperties.configServerSpecs().stream().findFirst().map(ConfigServerSpec::getHostName) .orElse(""); Identity identity = new Identity(domain.trim(), service.trim(), cfgHostName); cluster.addComponent(identity); } } /** * Disallow renderers named "DefaultRenderer" or "JsonRenderer" */ private static void validateRendererElement(Element element) { String idAttr = element.getAttribute("id"); if (idAttr.equals(xmlRendererId) || idAttr.equals(jsonRendererId)) { throw new IllegalArgumentException(String.format("Renderer id %s is reserved for internal use", idAttr)); } } }
class ContainerModelBuilder extends ConfigModelBuilder<ContainerModel> { /** * Default path to vip status file for container in Hosted Vespa. */ static final String HOSTED_VESPA_STATUS_FILE = Defaults.getDefaults().underVespaHome("var/mediasearch/oor/status.html"); /** * Path to vip status file for container in Hosted Vespa. Only used if set, else use HOSTED_VESPA_STATUS_FILE */ static final String HOSTED_VESPA_STATUS_FILE_YINST_SETTING = "cloudconfig_server__tenant_vip_status_file"; public enum Networking { disable, enable } private ApplicationPackage app; private final boolean standaloneBuilder; private final Networking networking; protected DeployLogger log; public static final List<ConfigModelId> configModelIds = ImmutableList.of(ConfigModelId.fromName("container"), ConfigModelId.fromName("jdisc")); private static final String xmlRendererId = RendererRegistry.xmlRendererId.getName(); private static final String jsonRendererId = RendererRegistry.jsonRendererId.getName(); private static final Logger logger = Logger.getLogger(ContainerModelBuilder.class.getName()); public ContainerModelBuilder(boolean standaloneBuilder, Networking networking) { super(ContainerModel.class); this.standaloneBuilder = standaloneBuilder; this.networking = networking; } @Override public List<ConfigModelId> handlesElements() { return configModelIds; } @Override public void doBuild(ContainerModel model, Element spec, ConfigModelContext modelContext) { app = modelContext.getApplicationPackage(); checkVersion(spec); this.log = modelContext.getDeployLogger(); ContainerCluster cluster = createContainerCluster(spec, modelContext); addClusterContent(cluster, spec, modelContext); addBundlesForPlatformComponents(cluster); model.setCluster(cluster); } protected void addBundlesForPlatformComponents(ContainerCluster cluster) { for (Component<?, ?> component : cluster.getAllComponents()) { String componentClass = component.model.bundleInstantiationSpec.getClassName(); BundleMapper.getBundlePath(componentClass). ifPresent(cluster::addPlatformBundle); } } private ContainerCluster createContainerCluster(Element spec, final ConfigModelContext modelContext) { return new VespaDomBuilder.DomConfigProducerBuilder<ContainerCluster>() { @Override protected ContainerCluster doBuild(AbstractConfigProducer ancestor, Element producerSpec) { return new ContainerCluster(ancestor, modelContext.getProducerId(), modelContext.getProducerId()); } }.build(modelContext.getParentProducer(), spec); } private void addRoutingAliases(ContainerCluster cluster, Element spec, Environment environment) { if (environment != Environment.prod) return; Element aliases = XML.getChild(spec, "aliases"); for (Element alias : XML.getChildren(aliases, "service-alias")) { cluster.serviceAliases().add(XML.getValue(alias)); } for (Element alias : XML.getChildren(aliases, "endpoint-alias")) { cluster.endpointAliases().add(XML.getValue(alias)); } } private void addConfiguredComponents(ContainerCluster cluster, Element spec) { for (Element components : XML.getChildren(spec, "components")) { addIncludes(components); addConfiguredComponents(cluster, components, "component"); } addConfiguredComponents(cluster, spec, "component"); } protected void addDefaultComponents(ContainerCluster cluster) { } protected void setDefaultMetricConsumerFactory(ContainerCluster cluster) { cluster.setDefaultMetricConsumerFactory(MetricDefaultsConfig.Factory.Enum.STATE_MONITOR); } protected void addDefaultHandlers(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); } protected void addStatusHandlers(ContainerCluster cluster, ConfigModelContext configModelContext) { if (configModelContext.getDeployState().isHosted()) { String name = "status.html"; Optional<String> statusFile = Optional.ofNullable(System.getenv(HOSTED_VESPA_STATUS_FILE_YINST_SETTING)); cluster.addComponent( new FileStatusHandlerComponent(name + "-status-handler", statusFile.orElse(HOSTED_VESPA_STATUS_FILE), "http: } else { cluster.addVipHandler(); } } /** * Intended for use by legacy builders only. * Will be called during building when using ContainerModelBuilder. */ public static void addDefaultHandler_legacyBuilder(ContainerCluster cluster) { addDefaultHandlersExceptStatus(cluster); cluster.addVipHandler(); } protected static void addDefaultHandlersExceptStatus(ContainerCluster cluster) { cluster.addDefaultRootHandler(); cluster.addMetricStateHandler(); cluster.addApplicationStatusHandler(); cluster.addStatisticsHandler(); } private void addClientProviders(Element spec, ContainerCluster cluster) { for (Element clientSpec: XML.getChildren(spec, "client")) { cluster.addComponent(new DomClientProviderBuilder().build(cluster, clientSpec)); } } private void addServerProviders(Element spec, ContainerCluster cluster) { addConfiguredComponents(cluster, spec, "server"); } private void addLegacyFilters(Element spec, ContainerCluster cluster) { for (Component component : buildLegacyFilters(cluster, spec)) { cluster.addComponent(component); } } private List<Component> buildLegacyFilters(AbstractConfigProducer ancestor, Element spec) { List<Component> components = new ArrayList<>(); for (Element node : XML.getChildren(spec, "filter")) { components.add(new DomFilterBuilder().build(ancestor, node)); } return components; } protected void addAccessLogs(ContainerCluster cluster, Element spec) { List<Element> accessLogElements = getAccessLogElements(spec); for (Element accessLog : accessLogElements) { AccessLogBuilder.buildIfNotDisabled(cluster, accessLog).ifPresent(cluster::addComponent); } if (accessLogElements.isEmpty() && cluster.getSearch() != null) cluster.addDefaultSearchAccessLog(); } protected final List<Element> getAccessLogElements(Element spec) { return XML.getChildren(spec, "accesslog"); } protected void addHttp(Element spec, ContainerCluster cluster) { Element httpElement = XML.getChild(spec, "http"); if (httpElement != null) { cluster.setHttp(buildHttp(cluster, httpElement)); } } private Http buildHttp(ContainerCluster cluster, Element httpElement) { Http http = new HttpBuilder().build(cluster, httpElement); if (networking == Networking.disable) http.removeAllServers(); return http; } protected void addRestApis(Element spec, ContainerCluster cluster) { for (Element restApiElem : XML.getChildren(spec, "rest-api")) { cluster.addRestApi( new RestApiBuilder().build(cluster, restApiElem)); } } private void addServlets(Element spec, ContainerCluster cluster) { for (Element servletElem : XML.getChildren(spec, "servlet")) { cluster.addServlet( new ServletBuilder().build(cluster, servletElem)); } } private void addDocumentApi(Element spec, ContainerCluster cluster) { ContainerDocumentApi containerDocumentApi = buildDocumentApi(cluster, spec); if (containerDocumentApi != null) { cluster.setDocumentApi(containerDocumentApi); } } private void addDocproc(Element spec, ContainerCluster cluster) { ContainerDocproc containerDocproc = buildDocproc(cluster, spec); if (containerDocproc != null) { cluster.setDocproc(containerDocproc); ContainerDocproc.Options docprocOptions = containerDocproc.options; cluster.setMbusParams(new ContainerCluster.MbusParams( docprocOptions.maxConcurrentFactor, docprocOptions.documentExpansionFactor, docprocOptions.containerCoreMemory)); } } private void addSearch(Element spec, ContainerCluster cluster, QueryProfiles queryProfiles, SemanticRules semanticRules) { Element searchElement = XML.getChild(spec, "search"); if (searchElement != null) { addIncludes(searchElement); cluster.setSearch(buildSearch(cluster, searchElement, queryProfiles, semanticRules)); addSearchHandler(cluster, searchElement); validateAndAddConfiguredComponents(cluster, searchElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private void addProcessing(Element spec, ContainerCluster cluster) { Element processingElement = XML.getChild(spec, "processing"); if (processingElement != null) { addIncludes(processingElement); cluster.setProcessingChains(new DomProcessingBuilder(null).build(cluster, processingElement), serverBindings(processingElement, ProcessingChains.defaultBindings)); validateAndAddConfiguredComponents(cluster, processingElement, "renderer", ContainerModelBuilder::validateRendererElement); } } private ContainerSearch buildSearch(ContainerCluster containerCluster, Element producerSpec, QueryProfiles queryProfiles, SemanticRules semanticRules) { SearchChains searchChains = new DomSearchChainsBuilder(null, false).build(containerCluster, producerSpec); ContainerSearch containerSearch = new ContainerSearch(containerCluster, searchChains, new ContainerSearch.Options()); applyApplicationPackageDirectoryConfigs(containerCluster.getRoot().getDeployState().getApplicationPackage(), containerSearch); containerSearch.setQueryProfiles(queryProfiles); containerSearch.setSemanticRules(semanticRules); return containerSearch; } private void applyApplicationPackageDirectoryConfigs(ApplicationPackage applicationPackage,ContainerSearch containerSearch) { PageTemplates.validate(applicationPackage); containerSearch.setPageTemplates(PageTemplates.create(applicationPackage)); } private void addHandlers(ContainerCluster cluster, Element spec) { for (Element component: XML.getChildren(spec, "handler")) { cluster.addComponent( new DomHandlerBuilder().build(cluster, component)); } } private void checkVersion(Element spec) { String version = spec.getAttribute("version"); if ( ! Version.fromString(version).equals(new Version(1))) { throw new RuntimeException("Expected container version to be 1.0, but got " + version); } } private void addNodes(ContainerCluster cluster, Element spec, ConfigModelContext context) { if (standaloneBuilder) addStandaloneNode(cluster); else addNodesFromXml(cluster, spec, context); } private void addStandaloneNode(ContainerCluster cluster) { Container container = new Container(cluster, "standalone", cluster.getContainers().size()); cluster.addContainers(Collections.singleton(container)); } private void addNodesFromXml(ContainerCluster cluster, Element containerElement, ConfigModelContext context) { Element nodesElement = XML.getChild(containerElement, "nodes"); if (nodesElement == null) { Container node = new Container(cluster, "container.0", 0); HostResource host = allocateSingleNodeHost(cluster, log, containerElement, context); node.setHostResource(host); if ( ! node.isInitialized() ) node.initService(); cluster.addContainers(Collections.singleton(node)); } else { List<Container> nodes = createNodes(cluster, nodesElement, context); applyNodesTagJvmArgs(nodes, nodesElement.getAttribute(VespaDomBuilder.JVMARGS_ATTRIB_NAME)); applyRoutingAliasProperties(nodes, cluster); applyDefaultPreload(nodes, nodesElement); applyMemoryPercentage(cluster, nodesElement.getAttribute(VespaDomBuilder.Allocated_MEMORY_ATTRIB_NAME)); if (useCpuSocketAffinity(nodesElement)) AbstractService.distributeCpuSocketAffinity(nodes); cluster.addContainers(nodes); } } private List<Container> createNodes(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { if (nodesElement.hasAttribute("count")) return createNodesFromNodeCount(cluster, nodesElement, context); else if (nodesElement.hasAttribute("type")) return createNodesFromNodeType(cluster, nodesElement, context); else if (nodesElement.hasAttribute("of")) return createNodesFromContentServiceReference(cluster, nodesElement, context); else return createNodesFromNodeList(cluster, nodesElement); } private void applyRoutingAliasProperties(List<Container> result, ContainerCluster cluster) { if (!cluster.serviceAliases().isEmpty()) { result.forEach(container -> { container.setProp("servicealiases", cluster.serviceAliases().stream().collect(Collectors.joining(","))); }); } if (!cluster.endpointAliases().isEmpty()) { result.forEach(container -> { container.setProp("endpointaliases", cluster.endpointAliases().stream().collect(Collectors.joining(","))); }); } } private void applyMemoryPercentage(ContainerCluster cluster, String memoryPercentage) { if (memoryPercentage == null || memoryPercentage.isEmpty()) return; memoryPercentage = memoryPercentage.trim(); if ( ! memoryPercentage.endsWith("%")) throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); memoryPercentage = memoryPercentage.substring(0, memoryPercentage.length()-1).trim(); try { cluster.setMemoryPercentage(Optional.of(Integer.parseInt(memoryPercentage))); } catch (NumberFormatException e) { throw new IllegalArgumentException("The memory percentage given for nodes in " + cluster + " must be an integer percentage ending by the '%' sign"); } } /** Creates a single host when there is no nodes tag */ private HostResource allocateSingleNodeHost(ContainerCluster cluster, DeployLogger logger, Element containerElement, ConfigModelContext context) { if (cluster.getRoot().getDeployState().isHosted()) { Optional<HostResource> singleContentHost = getHostResourceFromContentClusters(cluster, containerElement, context); if (singleContentHost.isPresent()) { return singleContentHost.get(); } else { ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); return cluster.getHostSystem().allocateHosts(clusterSpec, Capacity.fromNodeCount(1), 1, logger).keySet().iterator().next(); } } else { return cluster.getHostSystem().getHost(Container.SINGLENODE_CONTAINER_SERVICESPEC); } } private List<Container> createNodesFromNodeCount(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodesSpecification nodesSpecification = NodesSpecification.from(new ModelElement(nodesElement), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = nodesSpecification.provision(cluster.getRoot().getHostSystem(), ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromNodeType(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { NodeType type = NodeType.valueOf(nodesElement.getAttribute("type")); ClusterSpec clusterSpec = ClusterSpec.request(ClusterSpec.Type.container, ClusterSpec.Id.from(cluster.getName()), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = cluster.getRoot().getHostSystem().allocateHosts(clusterSpec, Capacity.fromRequiredNodeType(type), 1, log); return createNodesFromHosts(hosts, cluster); } private List<Container> createNodesFromContentServiceReference(ContainerCluster cluster, Element nodesElement, ConfigModelContext context) { String referenceId = nodesElement.getAttribute("of"); Element services = servicesRootOf(nodesElement).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); Element referencedService = findChildById(services, referenceId).orElseThrow(() -> clusterReferenceNotFoundException(cluster, referenceId)); if ( ! referencedService.getTagName().equals("content")) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "', " + "but that is not a content service"); Element referencedNodesElement = XML.getChild(referencedService, "nodes"); if (referencedNodesElement == null) throw new IllegalArgumentException(cluster + " references service '" + referenceId + "' to supply nodes, " + "but that service has no <nodes> element"); cluster.setHostClusterId(referenceId); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(NodesSpecification.from(new ModelElement(referencedNodesElement), context.getDeployState().getWantedNodeVespaVersion()), referenceId, cluster.getRoot().getHostSystem(), context.getDeployLogger()); return createNodesFromHosts(hosts, cluster); } /** * This is used in case we are on hosted Vespa and no nodes tag is supplied: * If there are content clusters this will pick the first host in the first cluster as the container node. * If there are no content clusters this will return empty (such that the node can be created by the container here). */ private Optional<HostResource> getHostResourceFromContentClusters(ContainerCluster cluster, Element containersElement, ConfigModelContext context) { Optional<Element> services = servicesRootOf(containersElement); if ( ! services.isPresent()) return Optional.empty(); List<Element> contentServices = XML.getChildren(services.get(), "content"); if ( contentServices.isEmpty() ) return Optional.empty(); Element contentNodesElementOrNull = XML.getChild(contentServices.get(0), "nodes"); NodesSpecification nodesSpec; if (contentNodesElementOrNull == null) nodesSpec = NodesSpecification.nonDedicated(1, context.getDeployState().getWantedNodeVespaVersion()); else nodesSpec = NodesSpecification.from(new ModelElement(contentNodesElementOrNull), context.getDeployState().getWantedNodeVespaVersion()); Map<HostResource, ClusterMembership> hosts = StorageGroup.provisionHosts(nodesSpec, contentServices.get(0).getAttribute("id"), cluster.getRoot().getHostSystem(), context.getDeployLogger()); return Optional.of(hosts.keySet().iterator().next()); } /** Returns the services element above the given Element, or empty if there is no services element */ private Optional<Element> servicesRootOf(Element element) { Node parent = element.getParentNode(); if (parent == null) return Optional.empty(); if ( ! (parent instanceof Element)) return Optional.empty(); Element parentElement = (Element)parent; if (parentElement.getTagName().equals("services")) return Optional.of(parentElement); return servicesRootOf(parentElement); } private List<Container> createNodesFromHosts(Map<HostResource, ClusterMembership> hosts, ContainerCluster cluster) { List<Container> nodes = new ArrayList<>(); for (Map.Entry<HostResource, ClusterMembership> entry : hosts.entrySet()) { String id = "container." + entry.getValue().index(); Container container = new Container(cluster, id, entry.getValue().retired(), entry.getValue().index()); container.setHostResource(entry.getKey()); container.initService(); nodes.add(container); } return nodes; } private List<Container> createNodesFromNodeList(ContainerCluster cluster, Element nodesElement) { List<Container> nodes = new ArrayList<>(); int nodeIndex = 0; for (Element nodeElem: XML.getChildren(nodesElement, "node")) { nodes.add(new ContainerServiceBuilder("container." + nodeIndex, nodeIndex).build(cluster, nodeElem)); nodeIndex++; } return nodes; } private IllegalArgumentException clusterReferenceNotFoundException(ContainerCluster cluster, String referenceId) { return new IllegalArgumentException(cluster + " references service '" + referenceId + "' but this service is not defined"); } private Optional<Element> findChildById(Element parent, String id) { for (Element child : XML.getChildren(parent)) if (id.equals(child.getAttribute("id"))) return Optional.of(child); return Optional.empty(); } private boolean useCpuSocketAffinity(Element nodesElement) { if (nodesElement.hasAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)) return Boolean.parseBoolean(nodesElement.getAttribute(VespaDomBuilder.CPU_SOCKET_AFFINITY_ATTRIB_NAME)); else return false; } private void applyNodesTagJvmArgs(List<Container> containers, String nodesTagJvnArgs) { for (Container container: containers) { if (container.getAssignedJvmArgs().isEmpty()) container.prependJvmArgs(nodesTagJvnArgs); } } private void applyDefaultPreload(List<Container> containers, Element nodesElement) { if (! nodesElement.hasAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)) return; for (Container container: containers) container.setPreLoad(nodesElement.getAttribute(VespaDomBuilder.PRELOAD_ATTRIB_NAME)); } private void addSearchHandler(ContainerCluster cluster, Element searchElement) { ProcessingHandler<SearchChains> searchHandler = new ProcessingHandler<>( cluster.getSearch().getChains(), "com.yahoo.search.handler.SearchHandler"); String[] defaultBindings = {"http: for (String binding: serverBindings(searchElement, defaultBindings)) { searchHandler.addServerBindings(binding); } cluster.addComponent(searchHandler); } private String[] serverBindings(Element searchElement, String... defaultBindings) { List<Element> bindings = XML.getChildren(searchElement, "binding"); if (bindings.isEmpty()) return defaultBindings; return toBindingList(bindings); } private String[] toBindingList(List<Element> bindingElements) { List<String> result = new ArrayList<>(); for (Element element: bindingElements) { String text = element.getTextContent().trim(); if (!text.isEmpty()) result.add(text); } return result.toArray(new String[result.size()]); } private ContainerDocumentApi buildDocumentApi(ContainerCluster cluster, Element spec) { Element documentApiElement = XML.getChild(spec, "document-api"); if (documentApiElement == null) return null; ContainerDocumentApi.Options documentApiOptions = DocumentApiOptionsBuilder.build(documentApiElement); return new ContainerDocumentApi(cluster, documentApiOptions); } private ContainerDocproc buildDocproc(ContainerCluster cluster, Element spec) { Element docprocElement = XML.getChild(spec, "document-processing"); if (docprocElement == null) return null; addIncludes(docprocElement); DocprocChains chains = new DomDocprocChainsBuilder(null, false).build(cluster, docprocElement); ContainerDocproc.Options docprocOptions = DocprocOptionsBuilder.build(docprocElement); return new ContainerDocproc(cluster, chains, docprocOptions, !standaloneBuilder); } private void addIncludes(Element parentElement) { List<Element> includes = XML.getChildren(parentElement, IncludeDirs.INCLUDE); if (includes == null || includes.isEmpty()) { return; } if (app == null) { throw new IllegalArgumentException("Element <include> given in XML config, but no application package given."); } for (Element include : includes) { addInclude(parentElement, include); } } private void addInclude(Element parentElement, Element include) { String dirName = include.getAttribute(IncludeDirs.DIR); app.validateIncludeDir(dirName); List<Element> includedFiles = Xml.allElemsFromPath(app, dirName); for (Element includedFile : includedFiles) { List<Element> includedSubElements = XML.getChildren(includedFile); for (Element includedSubElement : includedSubElements) { Node copiedNode = parentElement.getOwnerDocument().importNode(includedSubElement, true); parentElement.appendChild(copiedNode); } } } public static void addConfiguredComponents(ContainerCluster cluster, Element spec, String componentName) { for (Element node : XML.getChildren(spec, componentName)) { cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } public static void validateAndAddConfiguredComponents(ContainerCluster cluster, Element spec, String componentName, Consumer<Element> elementValidator) { for (Element node : XML.getChildren(spec, componentName)) { elementValidator.accept(node); cluster.addComponent(new DomComponentBuilder().build(cluster, node)); } } private void addIdentity(Element element, ContainerCluster cluster, List<ConfigServerSpec> configServerSpecs, URI loadBalancerAddress) { Element identityElement = XML.getChild(element, "identity"); if(identityElement != null) { String domain = XML.getValue(XML.getChild(identityElement, "domain")); String service = XML.getValue(XML.getChild(identityElement, "service")); logger.log(LogLevel.INFO, String.format("loadBalancerAddress: %s", loadBalancerAddress)); String cfgHostName = configServerSpecs.stream().findFirst().map(ConfigServerSpec::getHostName) .orElse(""); Identity identity = new Identity(domain.trim(), service.trim(), cfgHostName); cluster.addComponent(identity); cluster.getContainers().forEach(container -> { container.setProp("identity.domain", domain); container.setProp("identity.service", service); }); } } /** * Disallow renderers named "DefaultRenderer" or "JsonRenderer" */ private static void validateRendererElement(Element element) { String idAttr = element.getAttribute("id"); if (idAttr.equals(xmlRendererId) || idAttr.equals(jsonRendererId)) { throw new IllegalArgumentException(String.format("Renderer id %s is reserved for internal use", idAttr)); } } }
You should put these things in ApplicationList.
private void maintainPlatformIssue(List<Application> applications) { if ( ! (controller().versionStatus().version(controller().systemVersion()).confidence() == VespaVersion.Confidence.broken)) return; List<ApplicationId> failingApplications = new ArrayList<>(); for (Application application : ApplicationList.from(applications).upgradingTo(controller().systemVersion()).asList()) if (oldFailuresIn(application.deploymentJobs(), job -> ! causedByApplicationChange(job), upgradeGracePeriod)) failingApplications.add(application.id()); if ( ! failingApplications.isEmpty()) deploymentIssues.fileUnlessOpen(failingApplications, controller().systemVersion()); }
if (oldFailuresIn(application.deploymentJobs(), job -> ! causedByApplicationChange(job), upgradeGracePeriod))
private void maintainPlatformIssue(List<Application> applications) { if ( ! (controller().versionStatus().version(controller().systemVersion()).confidence() == broken)) return; List<ApplicationId> failingApplications = ApplicationList.from(applications) .failingUpgradeToVersionSince(controller().systemVersion(), controller().clock().instant().minus(upgradeGracePeriod)) .asList().stream() .map(Application::id) .collect(Collectors.toList()); if ( ! failingApplications.isEmpty()) deploymentIssues.fileUnlessOpen(failingApplications, controller().systemVersion()); }
class DeploymentIssueReporter extends Maintainer { static final Duration maxFailureAge = Duration.ofDays(2); static final Duration maxInactivity = Duration.ofDays(4); static final Duration upgradeGracePeriod = Duration.ofHours(2); private final DeploymentIssues deploymentIssues; DeploymentIssueReporter(Controller controller, DeploymentIssues deploymentIssues, Duration maintenanceInterval, JobControl jobControl) { super(controller, maintenanceInterval, jobControl); this.deploymentIssues = deploymentIssues; } @Override protected void maintain() { maintainDeploymentIssues(controller().applications().asList()); maintainPlatformIssue(controller().applications().asList()); escalateInactiveDeploymentIssues(controller().applications().asList()); } /** * File issues for applications which have failed deployment for longer than maxFailureAge * and store the issue id for the filed issues. Also, clear the issueIds of applications * where deployment has not failed for this amount of time. */ private void maintainDeploymentIssues(List<Application> applications) { List<ApplicationId> failingApplications = new ArrayList<>(); for (Application application : applications) if (oldFailuresIn(application.deploymentJobs(), this::causedByApplicationChange, maxFailureAge)) failingApplications.add(application.id()); else storeIssueId(application.id(), null); failingApplications.forEach(this::fileDeploymentIssueFor); } /** * When the confidence for the system version is BROKEN, file an issue listing the * applications that have been failing the upgrade to the system version for * longer than the set grace period, or update this list if the issue already exists. */ /** Return whether the given deployment jobs contain failures due to the given cause, past the given age. */ private boolean oldFailuresIn(DeploymentJobs jobs, Predicate<JobStatus> failureCause, Duration maxAge) { if ( ! jobs.hasFailures()) return false; Optional<Instant> oldestApplicationChangeFailure = jobs.jobStatus().values().stream() .filter(job -> ! job.isSuccess()) .filter(failureCause) .map(job -> job.firstFailing().get().at()) .min(Comparator.naturalOrder()); return oldestApplicationChangeFailure.isPresent() && oldestApplicationChangeFailure.get().isBefore(controller().clock().instant().minus(maxAge)); } private boolean causedByApplicationChange(JobStatus job) { if ( ! job.lastSuccess().isPresent()) return true; if ( ! job.firstFailing().get().version().equals(job.lastSuccess().get().version())) return false; if ( ! job.lastSuccess().get().revision().isPresent()) return true; return ! job.firstFailing().get().revision().equals(job.lastSuccess().get().revision()); } private Tenant ownerOf(ApplicationId applicationId) { return controller().tenants().tenant(new TenantId(applicationId.tenant().value())) .orElseThrow(() -> new IllegalStateException("No tenant found for application " + applicationId)); } private User userFor(Tenant tenant) { return User.from(tenant.getId().id().replaceFirst("by-", "")); } private PropertyId propertyIdFor(Tenant tenant) { return tenant.getPropertyId() .orElseThrow(() -> new NoSuchElementException("No PropertyId is listed for non-user tenant " + tenant)); } /** File an issue for applicationId, if it doesn't already have an open issue associated with it. */ private void fileDeploymentIssueFor(ApplicationId applicationId) { try { Tenant tenant = ownerOf(applicationId); Optional<IssueId> ourIssueId = controller().applications().require(applicationId).deploymentJobs().issueId(); IssueId issueId = tenant.tenantType() == TenantType.USER ? deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, userFor(tenant)) : deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, propertyIdFor(tenant)); storeIssueId(applicationId, issueId); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to file an issue for " + applicationId, e); } } /** Escalate issues for which there has been no activity for a certain amount of time. */ private void escalateInactiveDeploymentIssues(Collection<Application> applications) { applications.forEach(application -> application.deploymentJobs().issueId().ifPresent(issueId -> { try { deploymentIssues.escalateIfInactive(issueId, ownerOf(application.id()).getPropertyId(), maxInactivity); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to escalate issue with id " + issueId, e); } })); } private void storeIssueId(ApplicationId id, IssueId issueId) { try (Lock lock = controller().applications().lock(id)) { controller().applications().get(id, lock).ifPresent( application -> controller().applications().store(application.with(issueId)) ); } } }
class DeploymentIssueReporter extends Maintainer { static final Duration maxFailureAge = Duration.ofDays(2); static final Duration maxInactivity = Duration.ofDays(4); static final Duration upgradeGracePeriod = Duration.ofHours(4); private final DeploymentIssues deploymentIssues; DeploymentIssueReporter(Controller controller, DeploymentIssues deploymentIssues, Duration maintenanceInterval, JobControl jobControl) { super(controller, maintenanceInterval, jobControl); this.deploymentIssues = deploymentIssues; } @Override protected void maintain() { maintainDeploymentIssues(controller().applications().asList()); maintainPlatformIssue(controller().applications().asList()); escalateInactiveDeploymentIssues(controller().applications().asList()); } /** * File issues for applications which have failed deployment for longer than maxFailureAge * and store the issue id for the filed issues. Also, clear the issueIds of applications * where deployment has not failed for this amount of time. */ private void maintainDeploymentIssues(List<Application> applications) { Set<ApplicationId> failingApplications = ApplicationList.from(applications) .failingApplicationChangeSince(controller().clock().instant().minus(maxFailureAge)) .asList().stream() .map(Application::id) .collect(Collectors.toSet()); for (Application application : applications) if (failingApplications.contains(application.id())) fileDeploymentIssueFor(application.id()); else storeIssueId(application.id(), null); } /** * When the confidence for the system version is BROKEN, file an issue listing the * applications that have been failing the upgrade to the system version for * longer than the set grace period, or update this list if the issue already exists. */ private Tenant ownerOf(ApplicationId applicationId) { return controller().tenants().tenant(new TenantId(applicationId.tenant().value())) .orElseThrow(() -> new IllegalStateException("No tenant found for application " + applicationId)); } private User userFor(Tenant tenant) { return User.from(tenant.getId().id().replaceFirst("by-", "")); } private PropertyId propertyIdFor(Tenant tenant) { return tenant.getPropertyId() .orElseThrow(() -> new NoSuchElementException("No PropertyId is listed for non-user tenant " + tenant)); } /** File an issue for applicationId, if it doesn't already have an open issue associated with it. */ private void fileDeploymentIssueFor(ApplicationId applicationId) { try { Tenant tenant = ownerOf(applicationId); Optional<IssueId> ourIssueId = controller().applications().require(applicationId).deploymentJobs().issueId(); IssueId issueId = tenant.tenantType() == TenantType.USER ? deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, userFor(tenant)) : deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, propertyIdFor(tenant)); storeIssueId(applicationId, issueId); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to file an issue for " + applicationId, e); } } /** Escalate issues for which there has been no activity for a certain amount of time. */ private void escalateInactiveDeploymentIssues(Collection<Application> applications) { applications.forEach(application -> application.deploymentJobs().issueId().ifPresent(issueId -> { try { deploymentIssues.escalateIfInactive(issueId, ownerOf(application.id()).getPropertyId(), maxInactivity); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to escalate issue with id " + issueId, e); } })); } private void storeIssueId(ApplicationId id, IssueId issueId) { try (Lock lock = controller().applications().lock(id)) { controller().applications().get(id, lock).ifPresent( application -> controller().applications().store(application.with(issueId)) ); } } }
I hesitated because I didn't think the code would be general and nice at the same time. Take a look and see what you think.
private void maintainPlatformIssue(List<Application> applications) { if ( ! (controller().versionStatus().version(controller().systemVersion()).confidence() == VespaVersion.Confidence.broken)) return; List<ApplicationId> failingApplications = new ArrayList<>(); for (Application application : ApplicationList.from(applications).upgradingTo(controller().systemVersion()).asList()) if (oldFailuresIn(application.deploymentJobs(), job -> ! causedByApplicationChange(job), upgradeGracePeriod)) failingApplications.add(application.id()); if ( ! failingApplications.isEmpty()) deploymentIssues.fileUnlessOpen(failingApplications, controller().systemVersion()); }
if (oldFailuresIn(application.deploymentJobs(), job -> ! causedByApplicationChange(job), upgradeGracePeriod))
private void maintainPlatformIssue(List<Application> applications) { if ( ! (controller().versionStatus().version(controller().systemVersion()).confidence() == broken)) return; List<ApplicationId> failingApplications = ApplicationList.from(applications) .failingUpgradeToVersionSince(controller().systemVersion(), controller().clock().instant().minus(upgradeGracePeriod)) .asList().stream() .map(Application::id) .collect(Collectors.toList()); if ( ! failingApplications.isEmpty()) deploymentIssues.fileUnlessOpen(failingApplications, controller().systemVersion()); }
class DeploymentIssueReporter extends Maintainer { static final Duration maxFailureAge = Duration.ofDays(2); static final Duration maxInactivity = Duration.ofDays(4); static final Duration upgradeGracePeriod = Duration.ofHours(2); private final DeploymentIssues deploymentIssues; DeploymentIssueReporter(Controller controller, DeploymentIssues deploymentIssues, Duration maintenanceInterval, JobControl jobControl) { super(controller, maintenanceInterval, jobControl); this.deploymentIssues = deploymentIssues; } @Override protected void maintain() { maintainDeploymentIssues(controller().applications().asList()); maintainPlatformIssue(controller().applications().asList()); escalateInactiveDeploymentIssues(controller().applications().asList()); } /** * File issues for applications which have failed deployment for longer than maxFailureAge * and store the issue id for the filed issues. Also, clear the issueIds of applications * where deployment has not failed for this amount of time. */ private void maintainDeploymentIssues(List<Application> applications) { List<ApplicationId> failingApplications = new ArrayList<>(); for (Application application : applications) if (oldFailuresIn(application.deploymentJobs(), this::causedByApplicationChange, maxFailureAge)) failingApplications.add(application.id()); else storeIssueId(application.id(), null); failingApplications.forEach(this::fileDeploymentIssueFor); } /** * When the confidence for the system version is BROKEN, file an issue listing the * applications that have been failing the upgrade to the system version for * longer than the set grace period, or update this list if the issue already exists. */ /** Return whether the given deployment jobs contain failures due to the given cause, past the given age. */ private boolean oldFailuresIn(DeploymentJobs jobs, Predicate<JobStatus> failureCause, Duration maxAge) { if ( ! jobs.hasFailures()) return false; Optional<Instant> oldestApplicationChangeFailure = jobs.jobStatus().values().stream() .filter(job -> ! job.isSuccess()) .filter(failureCause) .map(job -> job.firstFailing().get().at()) .min(Comparator.naturalOrder()); return oldestApplicationChangeFailure.isPresent() && oldestApplicationChangeFailure.get().isBefore(controller().clock().instant().minus(maxAge)); } private boolean causedByApplicationChange(JobStatus job) { if ( ! job.lastSuccess().isPresent()) return true; if ( ! job.firstFailing().get().version().equals(job.lastSuccess().get().version())) return false; if ( ! job.lastSuccess().get().revision().isPresent()) return true; return ! job.firstFailing().get().revision().equals(job.lastSuccess().get().revision()); } private Tenant ownerOf(ApplicationId applicationId) { return controller().tenants().tenant(new TenantId(applicationId.tenant().value())) .orElseThrow(() -> new IllegalStateException("No tenant found for application " + applicationId)); } private User userFor(Tenant tenant) { return User.from(tenant.getId().id().replaceFirst("by-", "")); } private PropertyId propertyIdFor(Tenant tenant) { return tenant.getPropertyId() .orElseThrow(() -> new NoSuchElementException("No PropertyId is listed for non-user tenant " + tenant)); } /** File an issue for applicationId, if it doesn't already have an open issue associated with it. */ private void fileDeploymentIssueFor(ApplicationId applicationId) { try { Tenant tenant = ownerOf(applicationId); Optional<IssueId> ourIssueId = controller().applications().require(applicationId).deploymentJobs().issueId(); IssueId issueId = tenant.tenantType() == TenantType.USER ? deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, userFor(tenant)) : deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, propertyIdFor(tenant)); storeIssueId(applicationId, issueId); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to file an issue for " + applicationId, e); } } /** Escalate issues for which there has been no activity for a certain amount of time. */ private void escalateInactiveDeploymentIssues(Collection<Application> applications) { applications.forEach(application -> application.deploymentJobs().issueId().ifPresent(issueId -> { try { deploymentIssues.escalateIfInactive(issueId, ownerOf(application.id()).getPropertyId(), maxInactivity); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to escalate issue with id " + issueId, e); } })); } private void storeIssueId(ApplicationId id, IssueId issueId) { try (Lock lock = controller().applications().lock(id)) { controller().applications().get(id, lock).ifPresent( application -> controller().applications().store(application.with(issueId)) ); } } }
class DeploymentIssueReporter extends Maintainer { static final Duration maxFailureAge = Duration.ofDays(2); static final Duration maxInactivity = Duration.ofDays(4); static final Duration upgradeGracePeriod = Duration.ofHours(4); private final DeploymentIssues deploymentIssues; DeploymentIssueReporter(Controller controller, DeploymentIssues deploymentIssues, Duration maintenanceInterval, JobControl jobControl) { super(controller, maintenanceInterval, jobControl); this.deploymentIssues = deploymentIssues; } @Override protected void maintain() { maintainDeploymentIssues(controller().applications().asList()); maintainPlatformIssue(controller().applications().asList()); escalateInactiveDeploymentIssues(controller().applications().asList()); } /** * File issues for applications which have failed deployment for longer than maxFailureAge * and store the issue id for the filed issues. Also, clear the issueIds of applications * where deployment has not failed for this amount of time. */ private void maintainDeploymentIssues(List<Application> applications) { Set<ApplicationId> failingApplications = ApplicationList.from(applications) .failingApplicationChangeSince(controller().clock().instant().minus(maxFailureAge)) .asList().stream() .map(Application::id) .collect(Collectors.toSet()); for (Application application : applications) if (failingApplications.contains(application.id())) fileDeploymentIssueFor(application.id()); else storeIssueId(application.id(), null); } /** * When the confidence for the system version is BROKEN, file an issue listing the * applications that have been failing the upgrade to the system version for * longer than the set grace period, or update this list if the issue already exists. */ private Tenant ownerOf(ApplicationId applicationId) { return controller().tenants().tenant(new TenantId(applicationId.tenant().value())) .orElseThrow(() -> new IllegalStateException("No tenant found for application " + applicationId)); } private User userFor(Tenant tenant) { return User.from(tenant.getId().id().replaceFirst("by-", "")); } private PropertyId propertyIdFor(Tenant tenant) { return tenant.getPropertyId() .orElseThrow(() -> new NoSuchElementException("No PropertyId is listed for non-user tenant " + tenant)); } /** File an issue for applicationId, if it doesn't already have an open issue associated with it. */ private void fileDeploymentIssueFor(ApplicationId applicationId) { try { Tenant tenant = ownerOf(applicationId); Optional<IssueId> ourIssueId = controller().applications().require(applicationId).deploymentJobs().issueId(); IssueId issueId = tenant.tenantType() == TenantType.USER ? deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, userFor(tenant)) : deploymentIssues.fileUnlessOpen(ourIssueId, applicationId, propertyIdFor(tenant)); storeIssueId(applicationId, issueId); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to file an issue for " + applicationId, e); } } /** Escalate issues for which there has been no activity for a certain amount of time. */ private void escalateInactiveDeploymentIssues(Collection<Application> applications) { applications.forEach(application -> application.deploymentJobs().issueId().ifPresent(issueId -> { try { deploymentIssues.escalateIfInactive(issueId, ownerOf(application.id()).getPropertyId(), maxInactivity); } catch (RuntimeException e) { log.log(Level.WARNING, "Exception caught when attempting to escalate issue with id " + issueId, e); } })); } private void storeIssueId(ApplicationId id, IssueId issueId) { try (Lock lock = controller().applications().lock(id)) { controller().applications().get(id, lock).ifPresent( application -> controller().applications().store(application.with(issueId)) ); } } }
Accidental whitespace
public void run() { try { log.log(LogLevel.INFO, "Updating Athenz certificate through ZTS"); PrivateKey privateKey = keyProvider.getPrivateKey(zoneConfig.secretVersion() ); X509Certificate certificate = certificateClient.updateCertificate(privateKey, EXPIRY_TIME); String dummyPassword = "athenz"; KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null); keyStore.setKeyEntry("athenz", privateKey, dummyPassword.toCharArray(), new Certificate[]{certificate}); sslContextFactory.reload(sslContextFactory -> { sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(dummyPassword); }); log.log(LogLevel.INFO, "Athenz certificate reload successfully completed"); } catch (Throwable e) { log.log(LogLevel.ERROR, "Failed to update certificate from ZTS: " + e.getMessage(), e); } }
PrivateKey privateKey = keyProvider.getPrivateKey(zoneConfig.secretVersion() );
public void run() { try { log.log(LogLevel.INFO, "Updating Athenz certificate through ZTS"); PrivateKey privateKey = keyProvider.getPrivateKey(zoneConfig.secretVersion()); X509Certificate certificate = certificateClient.updateCertificate(privateKey, EXPIRY_TIME); String dummyPassword = "athenz"; KeyStore keyStore = KeyStore.getInstance("JKS"); keyStore.load(null); keyStore.setKeyEntry("athenz", privateKey, dummyPassword.toCharArray(), new Certificate[]{certificate}); sslContextFactory.reload(sslContextFactory -> { sslContextFactory.setKeyStore(keyStore); sslContextFactory.setKeyStorePassword(dummyPassword); }); log.log(LogLevel.INFO, "Athenz certificate reload successfully completed"); } catch (Throwable e) { log.log(LogLevel.ERROR, "Failed to update certificate from ZTS: " + e.getMessage(), e); } }
class AthenzCertificateUpdater implements Runnable { private static final TemporalAmount EXPIRY_TIME = Duration.ofDays(30); private static final Logger log = Logger.getLogger(AthenzCertificateUpdater.class.getName()); private final CertificateClient certificateClient; private final SslContextFactory sslContextFactory; private final KeyProvider keyProvider; private final AthenzProviderServiceConfig config; private final AthenzProviderServiceConfig.Zones zoneConfig; private AthenzCertificateUpdater(CertificateClient certificateClient, SslContextFactory sslContextFactory, KeyProvider keyProvider, AthenzProviderServiceConfig config, AthenzProviderServiceConfig.Zones zoneConfig) { this.certificateClient = certificateClient; this.sslContextFactory = sslContextFactory; this.keyProvider = keyProvider; this.config = config; this.zoneConfig = zoneConfig; } @Override }
class AthenzCertificateUpdater implements Runnable { private static final TemporalAmount EXPIRY_TIME = Duration.ofDays(30); private static final Logger log = Logger.getLogger(AthenzCertificateUpdater.class.getName()); private final CertificateClient certificateClient; private final SslContextFactory sslContextFactory; private final KeyProvider keyProvider; private final AthenzProviderServiceConfig config; private final AthenzProviderServiceConfig.Zones zoneConfig; private AthenzCertificateUpdater(CertificateClient certificateClient, SslContextFactory sslContextFactory, KeyProvider keyProvider, AthenzProviderServiceConfig config, AthenzProviderServiceConfig.Zones zoneConfig) { this.certificateClient = certificateClient; this.sslContextFactory = sslContextFactory; this.keyProvider = keyProvider; this.config = config; this.zoneConfig = zoneConfig; } @Override }
Incorrect description.
private void declareFileDistributionMethods() { supervisor.addMethod(new Method("waitFor", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getFile", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getActiveFileReferencesStatus", "", "SD", this, "getActiveFileReferencesStatus") .methodDesc("download status for file references") .returnDesc(0, "file references", "array of file references") .returnDesc(1, "download status", "percentage downloaded of each file reference in above array")); supervisor.addMethod(new Method("filedistribution.setFileReferencesToDownload", "S", "i", this, "setFileReferencesToDownload") .methodDesc("set which file references to download") .paramDesc(0, "file references", "file reference to download") .returnDesc(0, "ret", "0 if success, 1 otherwise")); }
.methodDesc("wait for file reference")
private void declareFileDistributionMethods() { supervisor.addMethod(new Method("waitFor", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getFile", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getActiveFileReferencesStatus", "", "SD", this, "getActiveFileReferencesStatus") .methodDesc("download status for file references") .returnDesc(0, "file references", "array of file references") .returnDesc(1, "download status", "percentage downloaded of each file reference in above array")); supervisor.addMethod(new Method("filedistribution.setFileReferencesToDownload", "S", "i", this, "setFileReferencesToDownload") .methodDesc("set which file references to download") .paramDesc(0, "file references", "file reference to download") .returnDesc(0, "ret", "0 if success, 1 otherwise")); }
class ConfigProxyRpcServer implements Runnable, TargetWatcher, RpcServer { private final static Logger log = Logger.getLogger(ConfigProxyRpcServer.class.getName()); private static final int TRACELEVEL = 6; private final Spec spec; private final Supervisor supervisor = new Supervisor(new Transport()); private final ProxyServer proxyServer; ConfigProxyRpcServer(ProxyServer proxyServer, Spec spec) { this.proxyServer = proxyServer; this.spec = spec; declareConfigMethods(); declareFileDistributionMethods(); } public void run() { try { Acceptor acceptor = supervisor.listen(spec); log.log(LogLevel.DEBUG, "Ready for requests on " + spec); supervisor.transport().join(); acceptor.shutdown().join(); } catch (ListenFailedException e) { proxyServer.stop(); throw new RuntimeException("Could not listen on " + spec, e); } } void shutdown() { supervisor.transport().shutdown(); } Spec getSpec() { return spec; } private void declareConfigMethods() { supervisor.addMethod(JRTMethods.createConfigV3GetConfigMethod(this, "getConfigV3")); supervisor.addMethod(new Method("ping", "", "i", this, "ping") .methodDesc("ping") .returnDesc(0, "ret code", "return code, 0 is OK")); supervisor.addMethod(new Method("printStatistics", "", "s", this, "printStatistics") .methodDesc("printStatistics") .returnDesc(0, "statistics", "Statistics for server")); supervisor.addMethod(new Method("listCachedConfig", "", "S", this, "listCachedConfig") .methodDesc("list cached configs)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listCachedConfigFull", "", "S", this, "listCachedConfigFull") .methodDesc("list cached configs with cache content)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listSourceConnections", "", "S", this, "listSourceConnections") .methodDesc("list config source connections)") .returnDesc(0, "data", "string array of source connections")); supervisor.addMethod(new Method("invalidateCache", "", "S", this, "invalidateCache") .methodDesc("list config source connections)") .returnDesc(0, "data", "0 if success, 1 otherwise")); supervisor.addMethod(new Method("updateSources", "s", "s", this, "updateSources") .methodDesc("update list of config sources") .returnDesc(0, "ret", "list of updated config sources")); supervisor.addMethod(new Method("setMode", "s", "S", this, "setMode") .methodDesc("Set config proxy mode { default | memorycache }") .returnDesc(0, "ret", "0 if success, 1 otherwise as first element, description as second element")); supervisor.addMethod(new Method("getMode", "", "s", this, "getMode") .methodDesc("What serving mode the config proxy is in (default, memorycache)") .returnDesc(0, "ret", "mode as a string")); supervisor.addMethod(new Method("dumpCache", "s", "s", this, "dumpCache") .methodDesc("Dump cache to disk") .paramDesc(0, "path", "path to write cache contents to") .returnDesc(0, "ret", "Empty string or error message")); } /** * Handles RPC method "config.v3.getConfig" requests. * * @param req a Request */ @SuppressWarnings({"UnusedDeclaration"}) public final void getConfigV3(Request req) { log.log(LogLevel.SPAM, () -> "getConfigV3"); JRTServerConfigRequest request = JRTServerConfigRequestV3.createFromRequest(req); if (isProtocolVersionSupported(request)) { preHandle(req); getConfigImpl(request); } } /** * Returns 0 if server is alive. * * @param req a Request */ public final void ping(Request req) { req.returnValues().add(new Int32Value(0)); } /** * Returns a String with statistics data for the server. * * @param req a Request */ public final void printStatistics(Request req) { StringBuilder sb = new StringBuilder(); sb.append("\nDelayed responses queue size: "); sb.append(proxyServer.delayedResponses.size()); sb.append("\nContents: "); for (DelayedResponse delayed : proxyServer.delayedResponses.responses()) { sb.append(delayed.getRequest().toString()).append("\n"); } req.returnValues().add(new StringValue(sb.toString())); } public final void listCachedConfig(Request req) { listCachedConfig(req, false); } public final void listCachedConfigFull(Request req) { listCachedConfig(req, true); } public final void listSourceConnections(Request req) { String[] ret = new String[2]; ret[0] = "Current source: " + proxyServer.getActiveSourceConnection(); ret[1] = "All sources:\n" + printSourceConnections(); req.returnValues().add(new StringArray(ret)); } @SuppressWarnings({"UnusedDeclaration"}) public final void updateSources(Request req) { String sources = req.parameters().get(0).asString(); String ret; System.out.println(proxyServer.getMode()); if (proxyServer.getMode().requiresConfigSource()) { proxyServer.updateSourceConnections(Arrays.asList(sources.split(","))); ret = "Updated config sources to: " + sources; } else { ret = "Cannot update sources when in '" + proxyServer.getMode().name() + "' mode"; } req.returnValues().add(new StringValue(ret)); } public final void invalidateCache(Request req) { proxyServer.getMemoryCache().clear(); String[] s = new String[2]; s[0] = "0"; s[1] = "success"; req.returnValues().add(new StringArray(s)); } public final void setMode(Request req) { String suppliedMode = req.parameters().get(0).asString(); log.log(LogLevel.DEBUG, () -> "Supplied mode=" + suppliedMode); String[] s = new String[2]; if (Mode.validModeName(suppliedMode.toLowerCase())) { proxyServer.setMode(suppliedMode); s[0] = "0"; s[1] = "success"; } else { s[0] = "1"; s[1] = "Could not set mode to '" + suppliedMode + "'. Legal modes are '" + Mode.modes() + "'"; } req.returnValues().add(new StringArray(s)); } public final void getMode(Request req) { req.returnValues().add(new StringValue(proxyServer.getMode().name())); } @SuppressWarnings({"UnusedDeclaration"}) public final void dumpCache(Request req) { final MemoryCache memoryCache = proxyServer.getMemoryCache(); req.returnValues().add(new StringValue(memoryCache.dumpCacheToDisk(req.parameters().get(0).asString(), memoryCache))); } @SuppressWarnings({"UnusedDeclaration"}) public final void getFile(Request req) { FileReference fileReference = new FileReference(req.parameters().get(0).asString()); String pathToFile = proxyServer.fileDownloader() .getFile(fileReference) .orElseGet(() -> new File("")) .getAbsolutePath(); log.log(LogLevel.INFO, "File reference '" + fileReference.value() + "' available at " + pathToFile); req.returnValues().add(new StringValue(pathToFile)); } @SuppressWarnings({"UnusedDeclaration"}) public final void getActiveFileReferencesStatus(Request req) { Map<FileReference, Double> downloadStatus = proxyServer.fileDownloader().downloadStatus(); String[] fileRefArray = new String[downloadStatus.keySet().size()]; fileRefArray = downloadStatus.keySet().stream() .map(FileReference::value) .collect(Collectors.toList()) .toArray(fileRefArray); double[] downloadStatusArray = new double[downloadStatus.values().size()]; int i = 0; for (Double d : downloadStatus.values()) { downloadStatusArray[i++] = d; } req.returnValues().add(new StringArray(fileRefArray)); req.returnValues().add(new DoubleArray(downloadStatusArray)); } @SuppressWarnings({"UnusedDeclaration"}) public final void setFileReferencesToDownload(Request req) { String[] fileReferenceStrings = req.parameters().get(0).asStringArray(); List<FileReference> fileReferences = Stream.of(fileReferenceStrings) .map(FileReference::new) .collect(Collectors.toList()); proxyServer.fileDownloader().queueForDownload(fileReferences); req.returnValues().add(new Int32Value(0)); } private boolean isProtocolVersionSupported(JRTServerConfigRequest request) { Set<Long> supportedProtocolVersions = JRTConfigRequestFactory.supportedProtocolVersions(); if (supportedProtocolVersions.contains(request.getProtocolVersion())) { return true; } else { String message = "Illegal protocol version " + request.getProtocolVersion() + " in request " + request.getShortDescription() + ", only protocol versions " + supportedProtocolVersions + " are supported"; log.log(LogLevel.ERROR, message); request.addErrorResponse(ErrorCode.ILLEGAL_PROTOCOL_VERSION, message); } return false; } private void preHandle(Request req) { proxyServer.getStatistics().incRpcRequests(); req.detach(); req.target().addWatcher(this); } /** * Handles all versions of "getConfig" requests. * * @param request a Request */ private void getConfigImpl(JRTServerConfigRequest request) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy getConfig()"); log.log(LogLevel.DEBUG, () ->"getConfig: " + request.getShortDescription() + ",configmd5=" + request.getRequestConfigMd5()); if (!request.validateParameters()) { log.log(LogLevel.WARNING, "Parameters for request " + request + " did not validate: " + request.errorCode() + " : " + request.errorMessage()); returnErrorResponse(request, request.errorCode(), "Parameters for request " + request.getShortDescription() + " did not validate: " + request.errorMessage()); return; } try { RawConfig config = proxyServer.resolveConfig(request); if (config == null) { log.log(LogLevel.SPAM, () -> "No config received yet for " + request.getShortDescription() + ", not sending response"); } else if (ProxyServer.configOrGenerationHasChanged(config, request)) { returnOkResponse(request, config); } else { log.log(LogLevel.SPAM, "No new config for " + request.getShortDescription() + ", not sending response"); } } catch (Exception e) { e.printStackTrace(); returnErrorResponse(request, com.yahoo.vespa.config.ErrorCode.INTERNAL_ERROR, e.getMessage()); } } private String printSourceConnections() { StringBuilder sb = new StringBuilder(); for (String s : proxyServer.getSourceConnections()) { sb.append(s).append("\n"); } return sb.toString(); } final void listCachedConfig(Request req, boolean full) { String[] ret; MemoryCache cache = proxyServer.getMemoryCache(); ret = new String[cache.size()]; int i = 0; for (RawConfig config : cache.values()) { StringBuilder sb = new StringBuilder(); sb.append(config.getNamespace()); sb.append("."); sb.append(config.getName()); sb.append(","); sb.append(config.getConfigId()); sb.append(","); sb.append(config.getGeneration()); sb.append(","); sb.append(config.getConfigMd5()); if (full) { sb.append(","); sb.append(config.getPayload()); } ret[i] = sb.toString(); i++; } Arrays.sort(ret); req.returnValues().add(new StringArray(ret)); } /** * Removes invalid targets (closed client connections) from delayedResponsesQueue. * * @param target a Target that has become invalid (i.e, client has closed connection) */ @Override public void notifyTargetInvalid(Target target) { log.log(LogLevel.DEBUG, () -> "Target invalid " + target); for (Iterator<DelayedResponse> it = proxyServer.delayedResponses.responses().iterator(); it.hasNext(); ) { DelayedResponse delayed = it.next(); JRTServerConfigRequest request = delayed.getRequest(); if (request.getRequest().target().equals(target)) { log.log(LogLevel.DEBUG, () -> "Removing " + request.getShortDescription()); it.remove(); } } } public void returnOkResponse(JRTServerConfigRequest request, RawConfig config) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnOkResponse()"); request.addOkResponse(config.getPayload(), config.getGeneration(), config.getConfigMd5()); log.log(LogLevel.DEBUG, () -> "Return response: " + request.getShortDescription() + ",configMd5=" + config.getConfigMd5() + ",generation=" + config.getGeneration()); log.log(LogLevel.SPAM, () -> "Config payload in response for " + request.getShortDescription() + ":" + config.getPayload()); try { request.getRequest().returnRequest(); } catch (IllegalStateException e) { log.log(LogLevel.DEBUG, () -> "Something bad happened when sending response for '" + request.getShortDescription() + "':" + e.getMessage()); } } public void returnErrorResponse(JRTServerConfigRequest request, int errorCode, String message) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnErrorResponse()"); request.addErrorResponse(errorCode, message); request.getRequest().returnRequest(); } }
class ConfigProxyRpcServer implements Runnable, TargetWatcher, RpcServer { private final static Logger log = Logger.getLogger(ConfigProxyRpcServer.class.getName()); private static final int TRACELEVEL = 6; private final Spec spec; private final Supervisor supervisor = new Supervisor(new Transport()); private final ProxyServer proxyServer; ConfigProxyRpcServer(ProxyServer proxyServer, Spec spec) { this.proxyServer = proxyServer; this.spec = spec; declareConfigMethods(); declareFileDistributionMethods(); } public void run() { try { Acceptor acceptor = supervisor.listen(spec); log.log(LogLevel.DEBUG, "Ready for requests on " + spec); supervisor.transport().join(); acceptor.shutdown().join(); } catch (ListenFailedException e) { proxyServer.stop(); throw new RuntimeException("Could not listen on " + spec, e); } } void shutdown() { supervisor.transport().shutdown(); } Spec getSpec() { return spec; } private void declareConfigMethods() { supervisor.addMethod(JRTMethods.createConfigV3GetConfigMethod(this, "getConfigV3")); supervisor.addMethod(new Method("ping", "", "i", this, "ping") .methodDesc("ping") .returnDesc(0, "ret code", "return code, 0 is OK")); supervisor.addMethod(new Method("printStatistics", "", "s", this, "printStatistics") .methodDesc("printStatistics") .returnDesc(0, "statistics", "Statistics for server")); supervisor.addMethod(new Method("listCachedConfig", "", "S", this, "listCachedConfig") .methodDesc("list cached configs)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listCachedConfigFull", "", "S", this, "listCachedConfigFull") .methodDesc("list cached configs with cache content)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listSourceConnections", "", "S", this, "listSourceConnections") .methodDesc("list config source connections)") .returnDesc(0, "data", "string array of source connections")); supervisor.addMethod(new Method("invalidateCache", "", "S", this, "invalidateCache") .methodDesc("list config source connections)") .returnDesc(0, "data", "0 if success, 1 otherwise")); supervisor.addMethod(new Method("updateSources", "s", "s", this, "updateSources") .methodDesc("update list of config sources") .returnDesc(0, "ret", "list of updated config sources")); supervisor.addMethod(new Method("setMode", "s", "S", this, "setMode") .methodDesc("Set config proxy mode { default | memorycache }") .returnDesc(0, "ret", "0 if success, 1 otherwise as first element, description as second element")); supervisor.addMethod(new Method("getMode", "", "s", this, "getMode") .methodDesc("What serving mode the config proxy is in (default, memorycache)") .returnDesc(0, "ret", "mode as a string")); supervisor.addMethod(new Method("dumpCache", "s", "s", this, "dumpCache") .methodDesc("Dump cache to disk") .paramDesc(0, "path", "path to write cache contents to") .returnDesc(0, "ret", "Empty string or error message")); } /** * Handles RPC method "config.v3.getConfig" requests. * * @param req a Request */ @SuppressWarnings({"UnusedDeclaration"}) public final void getConfigV3(Request req) { log.log(LogLevel.SPAM, () -> "getConfigV3"); JRTServerConfigRequest request = JRTServerConfigRequestV3.createFromRequest(req); if (isProtocolVersionSupported(request)) { preHandle(req); getConfigImpl(request); } } /** * Returns 0 if server is alive. * * @param req a Request */ public final void ping(Request req) { req.returnValues().add(new Int32Value(0)); } /** * Returns a String with statistics data for the server. * * @param req a Request */ public final void printStatistics(Request req) { StringBuilder sb = new StringBuilder(); sb.append("\nDelayed responses queue size: "); sb.append(proxyServer.delayedResponses.size()); sb.append("\nContents: "); for (DelayedResponse delayed : proxyServer.delayedResponses.responses()) { sb.append(delayed.getRequest().toString()).append("\n"); } req.returnValues().add(new StringValue(sb.toString())); } public final void listCachedConfig(Request req) { listCachedConfig(req, false); } public final void listCachedConfigFull(Request req) { listCachedConfig(req, true); } public final void listSourceConnections(Request req) { String[] ret = new String[2]; ret[0] = "Current source: " + proxyServer.getActiveSourceConnection(); ret[1] = "All sources:\n" + printSourceConnections(); req.returnValues().add(new StringArray(ret)); } @SuppressWarnings({"UnusedDeclaration"}) public final void updateSources(Request req) { String sources = req.parameters().get(0).asString(); String ret; System.out.println(proxyServer.getMode()); if (proxyServer.getMode().requiresConfigSource()) { proxyServer.updateSourceConnections(Arrays.asList(sources.split(","))); ret = "Updated config sources to: " + sources; } else { ret = "Cannot update sources when in '" + proxyServer.getMode().name() + "' mode"; } req.returnValues().add(new StringValue(ret)); } public final void invalidateCache(Request req) { proxyServer.getMemoryCache().clear(); String[] s = new String[2]; s[0] = "0"; s[1] = "success"; req.returnValues().add(new StringArray(s)); } public final void setMode(Request req) { String suppliedMode = req.parameters().get(0).asString(); log.log(LogLevel.DEBUG, () -> "Supplied mode=" + suppliedMode); String[] s = new String[2]; if (Mode.validModeName(suppliedMode.toLowerCase())) { proxyServer.setMode(suppliedMode); s[0] = "0"; s[1] = "success"; } else { s[0] = "1"; s[1] = "Could not set mode to '" + suppliedMode + "'. Legal modes are '" + Mode.modes() + "'"; } req.returnValues().add(new StringArray(s)); } public final void getMode(Request req) { req.returnValues().add(new StringValue(proxyServer.getMode().name())); } @SuppressWarnings({"UnusedDeclaration"}) public final void dumpCache(Request req) { final MemoryCache memoryCache = proxyServer.getMemoryCache(); req.returnValues().add(new StringValue(memoryCache.dumpCacheToDisk(req.parameters().get(0).asString(), memoryCache))); } @SuppressWarnings({"UnusedDeclaration"}) public final void getFile(Request req) { FileReference fileReference = new FileReference(req.parameters().get(0).asString()); String pathToFile = proxyServer.fileDownloader() .getFile(fileReference) .orElseGet(() -> new File("")) .getAbsolutePath(); log.log(LogLevel.INFO, "File reference '" + fileReference.value() + "' available at " + pathToFile); req.returnValues().add(new StringValue(pathToFile)); } @SuppressWarnings({"UnusedDeclaration"}) public final void getActiveFileReferencesStatus(Request req) { Map<FileReference, Double> downloadStatus = proxyServer.fileDownloader().downloadStatus(); String[] fileRefArray = new String[downloadStatus.keySet().size()]; fileRefArray = downloadStatus.keySet().stream() .map(FileReference::value) .collect(Collectors.toList()) .toArray(fileRefArray); double[] downloadStatusArray = new double[downloadStatus.values().size()]; int i = 0; for (Double d : downloadStatus.values()) { downloadStatusArray[i++] = d; } req.returnValues().add(new StringArray(fileRefArray)); req.returnValues().add(new DoubleArray(downloadStatusArray)); } @SuppressWarnings({"UnusedDeclaration"}) public final void setFileReferencesToDownload(Request req) { String[] fileReferenceStrings = req.parameters().get(0).asStringArray(); List<FileReference> fileReferences = Stream.of(fileReferenceStrings) .map(FileReference::new) .collect(Collectors.toList()); proxyServer.fileDownloader().queueForDownload(fileReferences); req.returnValues().add(new Int32Value(0)); } private boolean isProtocolVersionSupported(JRTServerConfigRequest request) { Set<Long> supportedProtocolVersions = JRTConfigRequestFactory.supportedProtocolVersions(); if (supportedProtocolVersions.contains(request.getProtocolVersion())) { return true; } else { String message = "Illegal protocol version " + request.getProtocolVersion() + " in request " + request.getShortDescription() + ", only protocol versions " + supportedProtocolVersions + " are supported"; log.log(LogLevel.ERROR, message); request.addErrorResponse(ErrorCode.ILLEGAL_PROTOCOL_VERSION, message); } return false; } private void preHandle(Request req) { proxyServer.getStatistics().incRpcRequests(); req.detach(); req.target().addWatcher(this); } /** * Handles all versions of "getConfig" requests. * * @param request a Request */ private void getConfigImpl(JRTServerConfigRequest request) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy getConfig()"); log.log(LogLevel.DEBUG, () ->"getConfig: " + request.getShortDescription() + ",configmd5=" + request.getRequestConfigMd5()); if (!request.validateParameters()) { log.log(LogLevel.WARNING, "Parameters for request " + request + " did not validate: " + request.errorCode() + " : " + request.errorMessage()); returnErrorResponse(request, request.errorCode(), "Parameters for request " + request.getShortDescription() + " did not validate: " + request.errorMessage()); return; } try { RawConfig config = proxyServer.resolveConfig(request); if (config == null) { log.log(LogLevel.SPAM, () -> "No config received yet for " + request.getShortDescription() + ", not sending response"); } else if (ProxyServer.configOrGenerationHasChanged(config, request)) { returnOkResponse(request, config); } else { log.log(LogLevel.SPAM, "No new config for " + request.getShortDescription() + ", not sending response"); } } catch (Exception e) { e.printStackTrace(); returnErrorResponse(request, com.yahoo.vespa.config.ErrorCode.INTERNAL_ERROR, e.getMessage()); } } private String printSourceConnections() { StringBuilder sb = new StringBuilder(); for (String s : proxyServer.getSourceConnections()) { sb.append(s).append("\n"); } return sb.toString(); } final void listCachedConfig(Request req, boolean full) { String[] ret; MemoryCache cache = proxyServer.getMemoryCache(); ret = new String[cache.size()]; int i = 0; for (RawConfig config : cache.values()) { StringBuilder sb = new StringBuilder(); sb.append(config.getNamespace()); sb.append("."); sb.append(config.getName()); sb.append(","); sb.append(config.getConfigId()); sb.append(","); sb.append(config.getGeneration()); sb.append(","); sb.append(config.getConfigMd5()); if (full) { sb.append(","); sb.append(config.getPayload()); } ret[i] = sb.toString(); i++; } Arrays.sort(ret); req.returnValues().add(new StringArray(ret)); } /** * Removes invalid targets (closed client connections) from delayedResponsesQueue. * * @param target a Target that has become invalid (i.e, client has closed connection) */ @Override public void notifyTargetInvalid(Target target) { log.log(LogLevel.DEBUG, () -> "Target invalid " + target); for (Iterator<DelayedResponse> it = proxyServer.delayedResponses.responses().iterator(); it.hasNext(); ) { DelayedResponse delayed = it.next(); JRTServerConfigRequest request = delayed.getRequest(); if (request.getRequest().target().equals(target)) { log.log(LogLevel.DEBUG, () -> "Removing " + request.getShortDescription()); it.remove(); } } } public void returnOkResponse(JRTServerConfigRequest request, RawConfig config) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnOkResponse()"); request.addOkResponse(config.getPayload(), config.getGeneration(), config.getConfigMd5()); log.log(LogLevel.DEBUG, () -> "Return response: " + request.getShortDescription() + ",configMd5=" + config.getConfigMd5() + ",generation=" + config.getGeneration()); log.log(LogLevel.SPAM, () -> "Config payload in response for " + request.getShortDescription() + ":" + config.getPayload()); try { request.getRequest().returnRequest(); } catch (IllegalStateException e) { log.log(LogLevel.DEBUG, () -> "Something bad happened when sending response for '" + request.getShortDescription() + "':" + e.getMessage()); } } public void returnErrorResponse(JRTServerConfigRequest request, int errorCode, String message) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnErrorResponse()"); request.addErrorResponse(errorCode, message); request.getRequest().returnRequest(); } }
I would do a timed wait on an object so that you can signal it and get it going right away when the file arrives.
public Optional<File> getFile(FileReference fileReference) { Objects.requireNonNull(fileReference, "file reference cannot be null"); File directory = new File(filesDirectory, fileReference.value()); log.log(LogLevel.DEBUG, "Checking if there is a file in '" + directory.getAbsolutePath() + "' "); Instant end = Instant.now().plus(timeout); do { File[] files = directory.listFiles(); if (directory.exists() && directory.isDirectory() && files != null && files.length > 0) { if (files.length != 1) { throw new RuntimeException("More than one file in '" + fileReference.value() + "', expected only one, unable to proceed"); } File file = files[0]; if (!file.exists()) { throw new RuntimeException("File with reference '" + fileReference.value() + "' does not exist"); } else if (!file.canRead()) { throw new RuntimeException("File with reference '" + fileReference.value() + "'exists, but unable to read it"); } else { downloadStatus.put(fileReference, 100.0); return Optional.of(file); } } else { queueForDownload(fileReference); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } while (Instant.now().isBefore(end)); return Optional.empty(); }
Thread.sleep(100);
public Optional<File> getFile(FileReference fileReference) { Objects.requireNonNull(fileReference, "file reference cannot be null"); File directory = new File(filesDirectory, fileReference.value()); log.log(LogLevel.DEBUG, "Checking if there is a file in '" + directory.getAbsolutePath() + "' "); Instant end = Instant.now().plus(timeout); do { File[] files = directory.listFiles(); if (directory.exists() && directory.isDirectory() && files != null && files.length > 0) { if (files.length != 1) { throw new RuntimeException("More than one file in '" + fileReference.value() + "', expected only one, unable to proceed"); } File file = files[0]; if (!file.exists()) { throw new RuntimeException("File with reference '" + fileReference.value() + "' does not exist"); } else if (!file.canRead()) { throw new RuntimeException("File with reference '" + fileReference.value() + "'exists, but unable to read it"); } else { downloadStatus.put(fileReference, 100.0); return Optional.of(file); } } else { queueForDownload(fileReference); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } while (Instant.now().isBefore(end)); return Optional.empty(); }
class FileDownloader { private final static Logger log = Logger.getLogger(FileDownloader.class.getName()); private final String filesDirectory; private final ConfigSourceSet configSourceSet; private final Duration timeout; private final Map<FileReference, Double> downloadStatus = new HashMap<>(); private final Set<FileReference> queuedForDownload = new LinkedHashSet<>(); public FileDownloader(ConfigSourceSet configSourceSet) { this(configSourceSet, Defaults.getDefaults().underVespaHome("var/db/vespa/filedistribution"), Duration.ofMinutes(15)); } FileDownloader(ConfigSourceSet configSourceSet, String filesDirectory, Duration timeout) { this.configSourceSet = configSourceSet; this.filesDirectory = filesDirectory; this.timeout = timeout; } public Map<FileReference, Double> downloadStatus() { return downloadStatus; } public void queueForDownload(List<FileReference> fileReferences) { fileReferences.forEach(this::queueForDownload); } private void queueForDownload(FileReference fileReference) { log.log(LogLevel.INFO, "Queued '" + fileReference.value() + "' for download "); queuedForDownload.add(fileReference); downloadStatus.put(fileReference, 0.0); } ImmutableSet<FileReference> queuedForDownload() { return ImmutableSet.copyOf(queuedForDownload); } }
class FileDownloader { private final static Logger log = Logger.getLogger(FileDownloader.class.getName()); private final String filesDirectory; private final ConfigSourceSet configSourceSet; private final Duration timeout; private final Map<FileReference, Double> downloadStatus = new HashMap<>(); private final Set<FileReference> queuedForDownload = new LinkedHashSet<>(); public FileDownloader(ConfigSourceSet configSourceSet) { this(configSourceSet, Defaults.getDefaults().underVespaHome("var/db/vespa/filedistribution"), Duration.ofMinutes(15)); } FileDownloader(ConfigSourceSet configSourceSet, String filesDirectory, Duration timeout) { this.configSourceSet = configSourceSet; this.filesDirectory = filesDirectory; this.timeout = timeout; } public Map<FileReference, Double> downloadStatus() { return downloadStatus; } public void queueForDownload(List<FileReference> fileReferences) { fileReferences.forEach(this::queueForDownload); } private void queueForDownload(FileReference fileReference) { log.log(LogLevel.INFO, "Queued '" + fileReference.value() + "' for download "); queuedForDownload.add(fileReference); downloadStatus.put(fileReference, 0.0); } ImmutableSet<FileReference> queuedForDownload() { return ImmutableSet.copyOf(queuedForDownload); } }
Agreed
public Optional<File> getFile(FileReference fileReference) { Objects.requireNonNull(fileReference, "file reference cannot be null"); File directory = new File(filesDirectory, fileReference.value()); log.log(LogLevel.DEBUG, "Checking if there is a file in '" + directory.getAbsolutePath() + "' "); Instant end = Instant.now().plus(timeout); do { File[] files = directory.listFiles(); if (directory.exists() && directory.isDirectory() && files != null && files.length > 0) { if (files.length != 1) { throw new RuntimeException("More than one file in '" + fileReference.value() + "', expected only one, unable to proceed"); } File file = files[0]; if (!file.exists()) { throw new RuntimeException("File with reference '" + fileReference.value() + "' does not exist"); } else if (!file.canRead()) { throw new RuntimeException("File with reference '" + fileReference.value() + "'exists, but unable to read it"); } else { downloadStatus.put(fileReference, 100.0); return Optional.of(file); } } else { queueForDownload(fileReference); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } while (Instant.now().isBefore(end)); return Optional.empty(); }
Thread.sleep(100);
public Optional<File> getFile(FileReference fileReference) { Objects.requireNonNull(fileReference, "file reference cannot be null"); File directory = new File(filesDirectory, fileReference.value()); log.log(LogLevel.DEBUG, "Checking if there is a file in '" + directory.getAbsolutePath() + "' "); Instant end = Instant.now().plus(timeout); do { File[] files = directory.listFiles(); if (directory.exists() && directory.isDirectory() && files != null && files.length > 0) { if (files.length != 1) { throw new RuntimeException("More than one file in '" + fileReference.value() + "', expected only one, unable to proceed"); } File file = files[0]; if (!file.exists()) { throw new RuntimeException("File with reference '" + fileReference.value() + "' does not exist"); } else if (!file.canRead()) { throw new RuntimeException("File with reference '" + fileReference.value() + "'exists, but unable to read it"); } else { downloadStatus.put(fileReference, 100.0); return Optional.of(file); } } else { queueForDownload(fileReference); } try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } } while (Instant.now().isBefore(end)); return Optional.empty(); }
class FileDownloader { private final static Logger log = Logger.getLogger(FileDownloader.class.getName()); private final String filesDirectory; private final ConfigSourceSet configSourceSet; private final Duration timeout; private final Map<FileReference, Double> downloadStatus = new HashMap<>(); private final Set<FileReference> queuedForDownload = new LinkedHashSet<>(); public FileDownloader(ConfigSourceSet configSourceSet) { this(configSourceSet, Defaults.getDefaults().underVespaHome("var/db/vespa/filedistribution"), Duration.ofMinutes(15)); } FileDownloader(ConfigSourceSet configSourceSet, String filesDirectory, Duration timeout) { this.configSourceSet = configSourceSet; this.filesDirectory = filesDirectory; this.timeout = timeout; } public Map<FileReference, Double> downloadStatus() { return downloadStatus; } public void queueForDownload(List<FileReference> fileReferences) { fileReferences.forEach(this::queueForDownload); } private void queueForDownload(FileReference fileReference) { log.log(LogLevel.INFO, "Queued '" + fileReference.value() + "' for download "); queuedForDownload.add(fileReference); downloadStatus.put(fileReference, 0.0); } ImmutableSet<FileReference> queuedForDownload() { return ImmutableSet.copyOf(queuedForDownload); } }
class FileDownloader { private final static Logger log = Logger.getLogger(FileDownloader.class.getName()); private final String filesDirectory; private final ConfigSourceSet configSourceSet; private final Duration timeout; private final Map<FileReference, Double> downloadStatus = new HashMap<>(); private final Set<FileReference> queuedForDownload = new LinkedHashSet<>(); public FileDownloader(ConfigSourceSet configSourceSet) { this(configSourceSet, Defaults.getDefaults().underVespaHome("var/db/vespa/filedistribution"), Duration.ofMinutes(15)); } FileDownloader(ConfigSourceSet configSourceSet, String filesDirectory, Duration timeout) { this.configSourceSet = configSourceSet; this.filesDirectory = filesDirectory; this.timeout = timeout; } public Map<FileReference, Double> downloadStatus() { return downloadStatus; } public void queueForDownload(List<FileReference> fileReferences) { fileReferences.forEach(this::queueForDownload); } private void queueForDownload(FileReference fileReference) { log.log(LogLevel.INFO, "Queued '" + fileReference.value() + "' for download "); queuedForDownload.add(fileReference); downloadStatus.put(fileReference, 0.0); } ImmutableSet<FileReference> queuedForDownload() { return ImmutableSet.copyOf(queuedForDownload); } }
Will fix in next PR
private void declareFileDistributionMethods() { supervisor.addMethod(new Method("waitFor", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getFile", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getActiveFileReferencesStatus", "", "SD", this, "getActiveFileReferencesStatus") .methodDesc("download status for file references") .returnDesc(0, "file references", "array of file references") .returnDesc(1, "download status", "percentage downloaded of each file reference in above array")); supervisor.addMethod(new Method("filedistribution.setFileReferencesToDownload", "S", "i", this, "setFileReferencesToDownload") .methodDesc("set which file references to download") .paramDesc(0, "file references", "file reference to download") .returnDesc(0, "ret", "0 if success, 1 otherwise")); }
.methodDesc("wait for file reference")
private void declareFileDistributionMethods() { supervisor.addMethod(new Method("waitFor", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getFile", "s", "s", this, "getFile") .methodDesc("wait for file reference") .paramDesc(0, "file reference", "file reference") .returnDesc(0, "path", "path to file")); supervisor.addMethod(new Method("filedistribution.getActiveFileReferencesStatus", "", "SD", this, "getActiveFileReferencesStatus") .methodDesc("download status for file references") .returnDesc(0, "file references", "array of file references") .returnDesc(1, "download status", "percentage downloaded of each file reference in above array")); supervisor.addMethod(new Method("filedistribution.setFileReferencesToDownload", "S", "i", this, "setFileReferencesToDownload") .methodDesc("set which file references to download") .paramDesc(0, "file references", "file reference to download") .returnDesc(0, "ret", "0 if success, 1 otherwise")); }
class ConfigProxyRpcServer implements Runnable, TargetWatcher, RpcServer { private final static Logger log = Logger.getLogger(ConfigProxyRpcServer.class.getName()); private static final int TRACELEVEL = 6; private final Spec spec; private final Supervisor supervisor = new Supervisor(new Transport()); private final ProxyServer proxyServer; ConfigProxyRpcServer(ProxyServer proxyServer, Spec spec) { this.proxyServer = proxyServer; this.spec = spec; declareConfigMethods(); declareFileDistributionMethods(); } public void run() { try { Acceptor acceptor = supervisor.listen(spec); log.log(LogLevel.DEBUG, "Ready for requests on " + spec); supervisor.transport().join(); acceptor.shutdown().join(); } catch (ListenFailedException e) { proxyServer.stop(); throw new RuntimeException("Could not listen on " + spec, e); } } void shutdown() { supervisor.transport().shutdown(); } Spec getSpec() { return spec; } private void declareConfigMethods() { supervisor.addMethod(JRTMethods.createConfigV3GetConfigMethod(this, "getConfigV3")); supervisor.addMethod(new Method("ping", "", "i", this, "ping") .methodDesc("ping") .returnDesc(0, "ret code", "return code, 0 is OK")); supervisor.addMethod(new Method("printStatistics", "", "s", this, "printStatistics") .methodDesc("printStatistics") .returnDesc(0, "statistics", "Statistics for server")); supervisor.addMethod(new Method("listCachedConfig", "", "S", this, "listCachedConfig") .methodDesc("list cached configs)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listCachedConfigFull", "", "S", this, "listCachedConfigFull") .methodDesc("list cached configs with cache content)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listSourceConnections", "", "S", this, "listSourceConnections") .methodDesc("list config source connections)") .returnDesc(0, "data", "string array of source connections")); supervisor.addMethod(new Method("invalidateCache", "", "S", this, "invalidateCache") .methodDesc("list config source connections)") .returnDesc(0, "data", "0 if success, 1 otherwise")); supervisor.addMethod(new Method("updateSources", "s", "s", this, "updateSources") .methodDesc("update list of config sources") .returnDesc(0, "ret", "list of updated config sources")); supervisor.addMethod(new Method("setMode", "s", "S", this, "setMode") .methodDesc("Set config proxy mode { default | memorycache }") .returnDesc(0, "ret", "0 if success, 1 otherwise as first element, description as second element")); supervisor.addMethod(new Method("getMode", "", "s", this, "getMode") .methodDesc("What serving mode the config proxy is in (default, memorycache)") .returnDesc(0, "ret", "mode as a string")); supervisor.addMethod(new Method("dumpCache", "s", "s", this, "dumpCache") .methodDesc("Dump cache to disk") .paramDesc(0, "path", "path to write cache contents to") .returnDesc(0, "ret", "Empty string or error message")); } /** * Handles RPC method "config.v3.getConfig" requests. * * @param req a Request */ @SuppressWarnings({"UnusedDeclaration"}) public final void getConfigV3(Request req) { log.log(LogLevel.SPAM, () -> "getConfigV3"); JRTServerConfigRequest request = JRTServerConfigRequestV3.createFromRequest(req); if (isProtocolVersionSupported(request)) { preHandle(req); getConfigImpl(request); } } /** * Returns 0 if server is alive. * * @param req a Request */ public final void ping(Request req) { req.returnValues().add(new Int32Value(0)); } /** * Returns a String with statistics data for the server. * * @param req a Request */ public final void printStatistics(Request req) { StringBuilder sb = new StringBuilder(); sb.append("\nDelayed responses queue size: "); sb.append(proxyServer.delayedResponses.size()); sb.append("\nContents: "); for (DelayedResponse delayed : proxyServer.delayedResponses.responses()) { sb.append(delayed.getRequest().toString()).append("\n"); } req.returnValues().add(new StringValue(sb.toString())); } public final void listCachedConfig(Request req) { listCachedConfig(req, false); } public final void listCachedConfigFull(Request req) { listCachedConfig(req, true); } public final void listSourceConnections(Request req) { String[] ret = new String[2]; ret[0] = "Current source: " + proxyServer.getActiveSourceConnection(); ret[1] = "All sources:\n" + printSourceConnections(); req.returnValues().add(new StringArray(ret)); } @SuppressWarnings({"UnusedDeclaration"}) public final void updateSources(Request req) { String sources = req.parameters().get(0).asString(); String ret; System.out.println(proxyServer.getMode()); if (proxyServer.getMode().requiresConfigSource()) { proxyServer.updateSourceConnections(Arrays.asList(sources.split(","))); ret = "Updated config sources to: " + sources; } else { ret = "Cannot update sources when in '" + proxyServer.getMode().name() + "' mode"; } req.returnValues().add(new StringValue(ret)); } public final void invalidateCache(Request req) { proxyServer.getMemoryCache().clear(); String[] s = new String[2]; s[0] = "0"; s[1] = "success"; req.returnValues().add(new StringArray(s)); } public final void setMode(Request req) { String suppliedMode = req.parameters().get(0).asString(); log.log(LogLevel.DEBUG, () -> "Supplied mode=" + suppliedMode); String[] s = new String[2]; if (Mode.validModeName(suppliedMode.toLowerCase())) { proxyServer.setMode(suppliedMode); s[0] = "0"; s[1] = "success"; } else { s[0] = "1"; s[1] = "Could not set mode to '" + suppliedMode + "'. Legal modes are '" + Mode.modes() + "'"; } req.returnValues().add(new StringArray(s)); } public final void getMode(Request req) { req.returnValues().add(new StringValue(proxyServer.getMode().name())); } @SuppressWarnings({"UnusedDeclaration"}) public final void dumpCache(Request req) { final MemoryCache memoryCache = proxyServer.getMemoryCache(); req.returnValues().add(new StringValue(memoryCache.dumpCacheToDisk(req.parameters().get(0).asString(), memoryCache))); } @SuppressWarnings({"UnusedDeclaration"}) public final void getFile(Request req) { FileReference fileReference = new FileReference(req.parameters().get(0).asString()); String pathToFile = proxyServer.fileDownloader() .getFile(fileReference) .orElseGet(() -> new File("")) .getAbsolutePath(); log.log(LogLevel.INFO, "File reference '" + fileReference.value() + "' available at " + pathToFile); req.returnValues().add(new StringValue(pathToFile)); } @SuppressWarnings({"UnusedDeclaration"}) public final void getActiveFileReferencesStatus(Request req) { Map<FileReference, Double> downloadStatus = proxyServer.fileDownloader().downloadStatus(); String[] fileRefArray = new String[downloadStatus.keySet().size()]; fileRefArray = downloadStatus.keySet().stream() .map(FileReference::value) .collect(Collectors.toList()) .toArray(fileRefArray); double[] downloadStatusArray = new double[downloadStatus.values().size()]; int i = 0; for (Double d : downloadStatus.values()) { downloadStatusArray[i++] = d; } req.returnValues().add(new StringArray(fileRefArray)); req.returnValues().add(new DoubleArray(downloadStatusArray)); } @SuppressWarnings({"UnusedDeclaration"}) public final void setFileReferencesToDownload(Request req) { String[] fileReferenceStrings = req.parameters().get(0).asStringArray(); List<FileReference> fileReferences = Stream.of(fileReferenceStrings) .map(FileReference::new) .collect(Collectors.toList()); proxyServer.fileDownloader().queueForDownload(fileReferences); req.returnValues().add(new Int32Value(0)); } private boolean isProtocolVersionSupported(JRTServerConfigRequest request) { Set<Long> supportedProtocolVersions = JRTConfigRequestFactory.supportedProtocolVersions(); if (supportedProtocolVersions.contains(request.getProtocolVersion())) { return true; } else { String message = "Illegal protocol version " + request.getProtocolVersion() + " in request " + request.getShortDescription() + ", only protocol versions " + supportedProtocolVersions + " are supported"; log.log(LogLevel.ERROR, message); request.addErrorResponse(ErrorCode.ILLEGAL_PROTOCOL_VERSION, message); } return false; } private void preHandle(Request req) { proxyServer.getStatistics().incRpcRequests(); req.detach(); req.target().addWatcher(this); } /** * Handles all versions of "getConfig" requests. * * @param request a Request */ private void getConfigImpl(JRTServerConfigRequest request) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy getConfig()"); log.log(LogLevel.DEBUG, () ->"getConfig: " + request.getShortDescription() + ",configmd5=" + request.getRequestConfigMd5()); if (!request.validateParameters()) { log.log(LogLevel.WARNING, "Parameters for request " + request + " did not validate: " + request.errorCode() + " : " + request.errorMessage()); returnErrorResponse(request, request.errorCode(), "Parameters for request " + request.getShortDescription() + " did not validate: " + request.errorMessage()); return; } try { RawConfig config = proxyServer.resolveConfig(request); if (config == null) { log.log(LogLevel.SPAM, () -> "No config received yet for " + request.getShortDescription() + ", not sending response"); } else if (ProxyServer.configOrGenerationHasChanged(config, request)) { returnOkResponse(request, config); } else { log.log(LogLevel.SPAM, "No new config for " + request.getShortDescription() + ", not sending response"); } } catch (Exception e) { e.printStackTrace(); returnErrorResponse(request, com.yahoo.vespa.config.ErrorCode.INTERNAL_ERROR, e.getMessage()); } } private String printSourceConnections() { StringBuilder sb = new StringBuilder(); for (String s : proxyServer.getSourceConnections()) { sb.append(s).append("\n"); } return sb.toString(); } final void listCachedConfig(Request req, boolean full) { String[] ret; MemoryCache cache = proxyServer.getMemoryCache(); ret = new String[cache.size()]; int i = 0; for (RawConfig config : cache.values()) { StringBuilder sb = new StringBuilder(); sb.append(config.getNamespace()); sb.append("."); sb.append(config.getName()); sb.append(","); sb.append(config.getConfigId()); sb.append(","); sb.append(config.getGeneration()); sb.append(","); sb.append(config.getConfigMd5()); if (full) { sb.append(","); sb.append(config.getPayload()); } ret[i] = sb.toString(); i++; } Arrays.sort(ret); req.returnValues().add(new StringArray(ret)); } /** * Removes invalid targets (closed client connections) from delayedResponsesQueue. * * @param target a Target that has become invalid (i.e, client has closed connection) */ @Override public void notifyTargetInvalid(Target target) { log.log(LogLevel.DEBUG, () -> "Target invalid " + target); for (Iterator<DelayedResponse> it = proxyServer.delayedResponses.responses().iterator(); it.hasNext(); ) { DelayedResponse delayed = it.next(); JRTServerConfigRequest request = delayed.getRequest(); if (request.getRequest().target().equals(target)) { log.log(LogLevel.DEBUG, () -> "Removing " + request.getShortDescription()); it.remove(); } } } public void returnOkResponse(JRTServerConfigRequest request, RawConfig config) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnOkResponse()"); request.addOkResponse(config.getPayload(), config.getGeneration(), config.getConfigMd5()); log.log(LogLevel.DEBUG, () -> "Return response: " + request.getShortDescription() + ",configMd5=" + config.getConfigMd5() + ",generation=" + config.getGeneration()); log.log(LogLevel.SPAM, () -> "Config payload in response for " + request.getShortDescription() + ":" + config.getPayload()); try { request.getRequest().returnRequest(); } catch (IllegalStateException e) { log.log(LogLevel.DEBUG, () -> "Something bad happened when sending response for '" + request.getShortDescription() + "':" + e.getMessage()); } } public void returnErrorResponse(JRTServerConfigRequest request, int errorCode, String message) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnErrorResponse()"); request.addErrorResponse(errorCode, message); request.getRequest().returnRequest(); } }
class ConfigProxyRpcServer implements Runnable, TargetWatcher, RpcServer { private final static Logger log = Logger.getLogger(ConfigProxyRpcServer.class.getName()); private static final int TRACELEVEL = 6; private final Spec spec; private final Supervisor supervisor = new Supervisor(new Transport()); private final ProxyServer proxyServer; ConfigProxyRpcServer(ProxyServer proxyServer, Spec spec) { this.proxyServer = proxyServer; this.spec = spec; declareConfigMethods(); declareFileDistributionMethods(); } public void run() { try { Acceptor acceptor = supervisor.listen(spec); log.log(LogLevel.DEBUG, "Ready for requests on " + spec); supervisor.transport().join(); acceptor.shutdown().join(); } catch (ListenFailedException e) { proxyServer.stop(); throw new RuntimeException("Could not listen on " + spec, e); } } void shutdown() { supervisor.transport().shutdown(); } Spec getSpec() { return spec; } private void declareConfigMethods() { supervisor.addMethod(JRTMethods.createConfigV3GetConfigMethod(this, "getConfigV3")); supervisor.addMethod(new Method("ping", "", "i", this, "ping") .methodDesc("ping") .returnDesc(0, "ret code", "return code, 0 is OK")); supervisor.addMethod(new Method("printStatistics", "", "s", this, "printStatistics") .methodDesc("printStatistics") .returnDesc(0, "statistics", "Statistics for server")); supervisor.addMethod(new Method("listCachedConfig", "", "S", this, "listCachedConfig") .methodDesc("list cached configs)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listCachedConfigFull", "", "S", this, "listCachedConfigFull") .methodDesc("list cached configs with cache content)") .returnDesc(0, "data", "string array of configs")); supervisor.addMethod(new Method("listSourceConnections", "", "S", this, "listSourceConnections") .methodDesc("list config source connections)") .returnDesc(0, "data", "string array of source connections")); supervisor.addMethod(new Method("invalidateCache", "", "S", this, "invalidateCache") .methodDesc("list config source connections)") .returnDesc(0, "data", "0 if success, 1 otherwise")); supervisor.addMethod(new Method("updateSources", "s", "s", this, "updateSources") .methodDesc("update list of config sources") .returnDesc(0, "ret", "list of updated config sources")); supervisor.addMethod(new Method("setMode", "s", "S", this, "setMode") .methodDesc("Set config proxy mode { default | memorycache }") .returnDesc(0, "ret", "0 if success, 1 otherwise as first element, description as second element")); supervisor.addMethod(new Method("getMode", "", "s", this, "getMode") .methodDesc("What serving mode the config proxy is in (default, memorycache)") .returnDesc(0, "ret", "mode as a string")); supervisor.addMethod(new Method("dumpCache", "s", "s", this, "dumpCache") .methodDesc("Dump cache to disk") .paramDesc(0, "path", "path to write cache contents to") .returnDesc(0, "ret", "Empty string or error message")); } /** * Handles RPC method "config.v3.getConfig" requests. * * @param req a Request */ @SuppressWarnings({"UnusedDeclaration"}) public final void getConfigV3(Request req) { log.log(LogLevel.SPAM, () -> "getConfigV3"); JRTServerConfigRequest request = JRTServerConfigRequestV3.createFromRequest(req); if (isProtocolVersionSupported(request)) { preHandle(req); getConfigImpl(request); } } /** * Returns 0 if server is alive. * * @param req a Request */ public final void ping(Request req) { req.returnValues().add(new Int32Value(0)); } /** * Returns a String with statistics data for the server. * * @param req a Request */ public final void printStatistics(Request req) { StringBuilder sb = new StringBuilder(); sb.append("\nDelayed responses queue size: "); sb.append(proxyServer.delayedResponses.size()); sb.append("\nContents: "); for (DelayedResponse delayed : proxyServer.delayedResponses.responses()) { sb.append(delayed.getRequest().toString()).append("\n"); } req.returnValues().add(new StringValue(sb.toString())); } public final void listCachedConfig(Request req) { listCachedConfig(req, false); } public final void listCachedConfigFull(Request req) { listCachedConfig(req, true); } public final void listSourceConnections(Request req) { String[] ret = new String[2]; ret[0] = "Current source: " + proxyServer.getActiveSourceConnection(); ret[1] = "All sources:\n" + printSourceConnections(); req.returnValues().add(new StringArray(ret)); } @SuppressWarnings({"UnusedDeclaration"}) public final void updateSources(Request req) { String sources = req.parameters().get(0).asString(); String ret; System.out.println(proxyServer.getMode()); if (proxyServer.getMode().requiresConfigSource()) { proxyServer.updateSourceConnections(Arrays.asList(sources.split(","))); ret = "Updated config sources to: " + sources; } else { ret = "Cannot update sources when in '" + proxyServer.getMode().name() + "' mode"; } req.returnValues().add(new StringValue(ret)); } public final void invalidateCache(Request req) { proxyServer.getMemoryCache().clear(); String[] s = new String[2]; s[0] = "0"; s[1] = "success"; req.returnValues().add(new StringArray(s)); } public final void setMode(Request req) { String suppliedMode = req.parameters().get(0).asString(); log.log(LogLevel.DEBUG, () -> "Supplied mode=" + suppliedMode); String[] s = new String[2]; if (Mode.validModeName(suppliedMode.toLowerCase())) { proxyServer.setMode(suppliedMode); s[0] = "0"; s[1] = "success"; } else { s[0] = "1"; s[1] = "Could not set mode to '" + suppliedMode + "'. Legal modes are '" + Mode.modes() + "'"; } req.returnValues().add(new StringArray(s)); } public final void getMode(Request req) { req.returnValues().add(new StringValue(proxyServer.getMode().name())); } @SuppressWarnings({"UnusedDeclaration"}) public final void dumpCache(Request req) { final MemoryCache memoryCache = proxyServer.getMemoryCache(); req.returnValues().add(new StringValue(memoryCache.dumpCacheToDisk(req.parameters().get(0).asString(), memoryCache))); } @SuppressWarnings({"UnusedDeclaration"}) public final void getFile(Request req) { FileReference fileReference = new FileReference(req.parameters().get(0).asString()); String pathToFile = proxyServer.fileDownloader() .getFile(fileReference) .orElseGet(() -> new File("")) .getAbsolutePath(); log.log(LogLevel.INFO, "File reference '" + fileReference.value() + "' available at " + pathToFile); req.returnValues().add(new StringValue(pathToFile)); } @SuppressWarnings({"UnusedDeclaration"}) public final void getActiveFileReferencesStatus(Request req) { Map<FileReference, Double> downloadStatus = proxyServer.fileDownloader().downloadStatus(); String[] fileRefArray = new String[downloadStatus.keySet().size()]; fileRefArray = downloadStatus.keySet().stream() .map(FileReference::value) .collect(Collectors.toList()) .toArray(fileRefArray); double[] downloadStatusArray = new double[downloadStatus.values().size()]; int i = 0; for (Double d : downloadStatus.values()) { downloadStatusArray[i++] = d; } req.returnValues().add(new StringArray(fileRefArray)); req.returnValues().add(new DoubleArray(downloadStatusArray)); } @SuppressWarnings({"UnusedDeclaration"}) public final void setFileReferencesToDownload(Request req) { String[] fileReferenceStrings = req.parameters().get(0).asStringArray(); List<FileReference> fileReferences = Stream.of(fileReferenceStrings) .map(FileReference::new) .collect(Collectors.toList()); proxyServer.fileDownloader().queueForDownload(fileReferences); req.returnValues().add(new Int32Value(0)); } private boolean isProtocolVersionSupported(JRTServerConfigRequest request) { Set<Long> supportedProtocolVersions = JRTConfigRequestFactory.supportedProtocolVersions(); if (supportedProtocolVersions.contains(request.getProtocolVersion())) { return true; } else { String message = "Illegal protocol version " + request.getProtocolVersion() + " in request " + request.getShortDescription() + ", only protocol versions " + supportedProtocolVersions + " are supported"; log.log(LogLevel.ERROR, message); request.addErrorResponse(ErrorCode.ILLEGAL_PROTOCOL_VERSION, message); } return false; } private void preHandle(Request req) { proxyServer.getStatistics().incRpcRequests(); req.detach(); req.target().addWatcher(this); } /** * Handles all versions of "getConfig" requests. * * @param request a Request */ private void getConfigImpl(JRTServerConfigRequest request) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy getConfig()"); log.log(LogLevel.DEBUG, () ->"getConfig: " + request.getShortDescription() + ",configmd5=" + request.getRequestConfigMd5()); if (!request.validateParameters()) { log.log(LogLevel.WARNING, "Parameters for request " + request + " did not validate: " + request.errorCode() + " : " + request.errorMessage()); returnErrorResponse(request, request.errorCode(), "Parameters for request " + request.getShortDescription() + " did not validate: " + request.errorMessage()); return; } try { RawConfig config = proxyServer.resolveConfig(request); if (config == null) { log.log(LogLevel.SPAM, () -> "No config received yet for " + request.getShortDescription() + ", not sending response"); } else if (ProxyServer.configOrGenerationHasChanged(config, request)) { returnOkResponse(request, config); } else { log.log(LogLevel.SPAM, "No new config for " + request.getShortDescription() + ", not sending response"); } } catch (Exception e) { e.printStackTrace(); returnErrorResponse(request, com.yahoo.vespa.config.ErrorCode.INTERNAL_ERROR, e.getMessage()); } } private String printSourceConnections() { StringBuilder sb = new StringBuilder(); for (String s : proxyServer.getSourceConnections()) { sb.append(s).append("\n"); } return sb.toString(); } final void listCachedConfig(Request req, boolean full) { String[] ret; MemoryCache cache = proxyServer.getMemoryCache(); ret = new String[cache.size()]; int i = 0; for (RawConfig config : cache.values()) { StringBuilder sb = new StringBuilder(); sb.append(config.getNamespace()); sb.append("."); sb.append(config.getName()); sb.append(","); sb.append(config.getConfigId()); sb.append(","); sb.append(config.getGeneration()); sb.append(","); sb.append(config.getConfigMd5()); if (full) { sb.append(","); sb.append(config.getPayload()); } ret[i] = sb.toString(); i++; } Arrays.sort(ret); req.returnValues().add(new StringArray(ret)); } /** * Removes invalid targets (closed client connections) from delayedResponsesQueue. * * @param target a Target that has become invalid (i.e, client has closed connection) */ @Override public void notifyTargetInvalid(Target target) { log.log(LogLevel.DEBUG, () -> "Target invalid " + target); for (Iterator<DelayedResponse> it = proxyServer.delayedResponses.responses().iterator(); it.hasNext(); ) { DelayedResponse delayed = it.next(); JRTServerConfigRequest request = delayed.getRequest(); if (request.getRequest().target().equals(target)) { log.log(LogLevel.DEBUG, () -> "Removing " + request.getShortDescription()); it.remove(); } } } public void returnOkResponse(JRTServerConfigRequest request, RawConfig config) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnOkResponse()"); request.addOkResponse(config.getPayload(), config.getGeneration(), config.getConfigMd5()); log.log(LogLevel.DEBUG, () -> "Return response: " + request.getShortDescription() + ",configMd5=" + config.getConfigMd5() + ",generation=" + config.getGeneration()); log.log(LogLevel.SPAM, () -> "Config payload in response for " + request.getShortDescription() + ":" + config.getPayload()); try { request.getRequest().returnRequest(); } catch (IllegalStateException e) { log.log(LogLevel.DEBUG, () -> "Something bad happened when sending response for '" + request.getShortDescription() + "':" + e.getMessage()); } } public void returnErrorResponse(JRTServerConfigRequest request, int errorCode, String message) { request.getRequestTrace().trace(TRACELEVEL, "Config proxy returnErrorResponse()"); request.addErrorResponse(errorCode, message); request.getRequest().returnRequest(); } }
Nice 👍 This unit test got a lot better after removing `ScheduledExecutorServiceMock`.
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix"); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config), sslContextFactory, keyProvider, config); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory();
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix", ZONE); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config, getZoneConfig(config, ZONE)), sslContextFactory, keyProvider, config, getZoneConfig(config, ZONE)); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix) { return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .domain(domain) .serviceName(service) .port(PORT) .keyPathPrefix("dummy-path") .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (JsonProcessingException | NoSuchAlgorithmException | UnsupportedEncodingException | SignatureException | InvalidKeyException e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() throws IOException, NoSuchAlgorithmException { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config) { this.keyPair = keyPair; this.config = config; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + config.domain() + "." + config.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix, Zone zone) { AthenzProviderServiceConfig.Zones.Builder zoneConfig = new AthenzProviderServiceConfig.Zones.Builder() .serviceName(service) .secretVersion(0) .domain(domain) .secretName("s3cr3t"); return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .zones(ImmutableMap.of(zone.environment().value() + "." + zone.region().value(), zoneConfig)) .port(PORT) .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } public static AthenzProviderServiceConfig.Zones getZoneConfig(AthenzProviderServiceConfig config, Zone zone) { return config.zones(zone.environment().value() + "." + zone.region().value()); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (Exception e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() { try { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private final AthenzProviderServiceConfig.Zones zoneConfig; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config, AthenzProviderServiceConfig.Zones zoneConfig) { this.keyPair = keyPair; this.config = config; this.zoneConfig = zoneConfig; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + zoneConfig.domain() + "." + zoneConfig.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
Consider mocking the `SslContextFactory` instance instead of creating one from `AthenzInstanceProviderService.createSslContextFactory()`.
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix"); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config), sslContextFactory, keyProvider, config); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory();
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix", ZONE); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config, getZoneConfig(config, ZONE)), sslContextFactory, keyProvider, config, getZoneConfig(config, ZONE)); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix) { return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .domain(domain) .serviceName(service) .port(PORT) .keyPathPrefix("dummy-path") .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (JsonProcessingException | NoSuchAlgorithmException | UnsupportedEncodingException | SignatureException | InvalidKeyException e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() throws IOException, NoSuchAlgorithmException { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config) { this.keyPair = keyPair; this.config = config; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + config.domain() + "." + config.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix, Zone zone) { AthenzProviderServiceConfig.Zones.Builder zoneConfig = new AthenzProviderServiceConfig.Zones.Builder() .serviceName(service) .secretVersion(0) .domain(domain) .secretName("s3cr3t"); return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .zones(ImmutableMap.of(zone.environment().value() + "." + zone.region().value(), zoneConfig)) .port(PORT) .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } public static AthenzProviderServiceConfig.Zones getZoneConfig(AthenzProviderServiceConfig config, Zone zone) { return config.zones(zone.environment().value() + "." + zone.region().value()); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (Exception e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() { try { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private final AthenzProviderServiceConfig.Zones zoneConfig; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config, AthenzProviderServiceConfig.Zones zoneConfig) { this.keyPair = keyPair; this.config = config; this.zoneConfig = zoneConfig; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + zoneConfig.domain() + "." + zoneConfig.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
This would be (at least for now) exact copy of the method in `AthenzInstanceProviderService`? I don't think it would be easier to create mockito mock to use this, and returning actual `SslContextFactory` would probably still need to set the same fields we do in real method...
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix"); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config), sslContextFactory, keyProvider, config); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory();
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix", ZONE); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config, getZoneConfig(config, ZONE)), sslContextFactory, keyProvider, config, getZoneConfig(config, ZONE)); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix) { return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .domain(domain) .serviceName(service) .port(PORT) .keyPathPrefix("dummy-path") .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (JsonProcessingException | NoSuchAlgorithmException | UnsupportedEncodingException | SignatureException | InvalidKeyException e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() throws IOException, NoSuchAlgorithmException { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config) { this.keyPair = keyPair; this.config = config; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + config.domain() + "." + config.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix, Zone zone) { AthenzProviderServiceConfig.Zones.Builder zoneConfig = new AthenzProviderServiceConfig.Zones.Builder() .serviceName(service) .secretVersion(0) .domain(domain) .secretName("s3cr3t"); return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .zones(ImmutableMap.of(zone.environment().value() + "." + zone.region().value(), zoneConfig)) .port(PORT) .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } public static AthenzProviderServiceConfig.Zones getZoneConfig(AthenzProviderServiceConfig config, Zone zone) { return config.zones(zone.environment().value() + "." + zone.region().value()); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (Exception e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() { try { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private final AthenzProviderServiceConfig.Zones zoneConfig; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config, AthenzProviderServiceConfig.Zones zoneConfig) { this.keyPair = keyPair; this.config = config; this.zoneConfig = zoneConfig; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + zoneConfig.domain() + "." + zoneConfig.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
Okay, I agree to leave it if it's not easy to mock.
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix"); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config), sslContextFactory, keyProvider, config); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory();
public void provider_service_hosts_endpoint_secured_with_tls() throws Exception { String domain = "domain"; String service = "service"; AutoGeneratedKeyProvider keyProvider = new AutoGeneratedKeyProvider(); PrivateKey privateKey = keyProvider.getPrivateKey(0); AthenzProviderServiceConfig config = getAthenzProviderConfig(domain, service, "vespa.dns.suffix", ZONE); SslContextFactory sslContextFactory = AthenzInstanceProviderService.createSslContextFactory(); AthenzCertificateUpdater certificateUpdater = new AthenzCertificateUpdater( new SelfSignedCertificateClient(keyProvider.getKeyPair(), config, getZoneConfig(config, ZONE)), sslContextFactory, keyProvider, config, getZoneConfig(config, ZONE)); ScheduledExecutorService executor = mock(ScheduledExecutorService.class); when(executor.awaitTermination(anyLong(), any())).thenReturn(true); InstanceValidator instanceValidator = mock(InstanceValidator.class); when(instanceValidator.isValidInstance(any())).thenReturn(true); IdentityDocumentGenerator identityDocumentGenerator = mock(IdentityDocumentGenerator.class); AthenzInstanceProviderService athenzInstanceProviderService = new AthenzInstanceProviderService( config, executor, ZONE, sslContextFactory, instanceValidator, identityDocumentGenerator, certificateUpdater); try (CloseableHttpClient client = createHttpClient(domain, service)) { assertFalse(getStatus(client)); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); certificateUpdater.run(); assertTrue(getStatus(client)); assertInstanceConfirmationSucceeds(client, privateKey); } finally { athenzInstanceProviderService.deconstruct(); } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix) { return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .domain(domain) .serviceName(service) .port(PORT) .keyPathPrefix("dummy-path") .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (JsonProcessingException | NoSuchAlgorithmException | UnsupportedEncodingException | SignatureException | InvalidKeyException e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() throws IOException, NoSuchAlgorithmException { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config) { this.keyPair = keyPair; this.config = config; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + config.domain() + "." + config.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
class AthenzInstanceProviderServiceTest { private static final Logger log = Logger.getLogger(AthenzInstanceProviderServiceTest.class.getName()); private static final int PORT = 12345; private static final Zone ZONE = new Zone(SystemName.cd, Environment.dev, RegionName.from("us-north-1")); @Test public static AthenzProviderServiceConfig getAthenzProviderConfig(String domain, String service, String dnsSuffix, Zone zone) { AthenzProviderServiceConfig.Zones.Builder zoneConfig = new AthenzProviderServiceConfig.Zones.Builder() .serviceName(service) .secretVersion(0) .domain(domain) .secretName("s3cr3t"); return new AthenzProviderServiceConfig( new AthenzProviderServiceConfig.Builder() .zones(ImmutableMap.of(zone.environment().value() + "." + zone.region().value(), zoneConfig)) .port(PORT) .certDnsSuffix(dnsSuffix) .ztsUrl("localhost/zts") .athenzPrincipalHeaderName("Athenz-Principal-Auth") .apiPath("")); } public static AthenzProviderServiceConfig.Zones getZoneConfig(AthenzProviderServiceConfig config, Zone zone) { return config.zones(zone.environment().value() + "." + zone.region().value()); } private static boolean getStatus(HttpClient client) { try { HttpResponse response = client.execute(new HttpGet("https: return response.getStatusLine().getStatusCode() == HttpStatus.SC_OK; } catch (Exception e) { log.log(LogLevel.INFO, "Status.html failed: " + e); return false; } } private static void assertInstanceConfirmationSucceeds(HttpClient client, PrivateKey privateKey) throws IOException { HttpPost httpPost = new HttpPost("https: httpPost.setEntity(createInstanceConfirmation(privateKey)); HttpResponse response = client.execute(httpPost); assertThat(response.getStatusLine().getStatusCode(), equalTo(200)); } private static CloseableHttpClient createHttpClient(String domain, String service) throws NoSuchAlgorithmException, KeyManagementException, KeyStoreException { SSLContext sslContext = new SSLContextBuilder() .loadTrustMaterial(null, (certificateChain, ignoredAuthType) -> certificateChain[0].getSubjectX500Principal().getName().equals("CN=" + domain + "." + service)) .build(); return HttpClients.custom() .setSslcontext(sslContext) .setSSLHostnameVerifier(new NoopHostnameVerifier()) .build(); } private static HttpEntity createInstanceConfirmation(PrivateKey privateKey) { IdentityDocument identityDocument = new IdentityDocument( new ProviderUniqueId("tenant", "application", "environment", "region", "instance", "cluster-id", 0), "hostname", "instance-hostname", Instant.now()); try { ObjectMapper mapper = Utils.getMapper(); String encodedIdentityDocument = Base64.getEncoder().encodeToString(mapper.writeValueAsString(identityDocument).getBytes()); Signature sigGenerator = Signature.getInstance("SHA512withRSA"); sigGenerator.initSign(privateKey); sigGenerator.update(encodedIdentityDocument.getBytes()); InstanceConfirmation instanceConfirmation = new InstanceConfirmation( "provider", "domain", "service", new SignedIdentityDocument(encodedIdentityDocument, Base64.getEncoder().encodeToString(sigGenerator.sign()), 0, identityDocument.providerUniqueId.asString(), "dnssuffix", "service", "localhost/zts", 1)); return new StringEntity(mapper.writeValueAsString(instanceConfirmation)); } catch (Exception e) { throw new RuntimeException(e); } } public static class AutoGeneratedKeyProvider implements KeyProvider { private final KeyPair keyPair; public AutoGeneratedKeyProvider() { try { KeyPairGenerator rsa = KeyPairGenerator.getInstance("RSA"); rsa.initialize(2048); keyPair = rsa.genKeyPair(); } catch (NoSuchAlgorithmException e) { throw new RuntimeException(e); } } @Override public PrivateKey getPrivateKey(int version) { return keyPair.getPrivate(); } @Override public PublicKey getPublicKey(int version) { return keyPair.getPublic(); } public KeyPair getKeyPair() { return keyPair; } } private static class SelfSignedCertificateClient implements CertificateClient { private final KeyPair keyPair; private final AthenzProviderServiceConfig config; private final AthenzProviderServiceConfig.Zones zoneConfig; private SelfSignedCertificateClient(KeyPair keyPair, AthenzProviderServiceConfig config, AthenzProviderServiceConfig.Zones zoneConfig) { this.keyPair = keyPair; this.config = config; this.zoneConfig = zoneConfig; } @Override public X509Certificate updateCertificate(PrivateKey privateKey, TemporalAmount expiryTime) { try { ContentSigner contentSigner = new JcaContentSignerBuilder("SHA512WithRSA").build(keyPair.getPrivate()); X500Name dnName = new X500Name("CN=" + zoneConfig.domain() + "." + zoneConfig.serviceName()); Calendar calendar = Calendar.getInstance(); calendar.add(Calendar.HOUR, 1); Date endDate = calendar.getTime(); JcaX509v3CertificateBuilder certBuilder = new JcaX509v3CertificateBuilder( dnName, BigInteger.ONE, new Date(), endDate, dnName, keyPair.getPublic()); certBuilder.addExtension(new ASN1ObjectIdentifier("2.5.29.19"), true, new BasicConstraints(true)); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(certBuilder.build(contentSigner)); } catch (CertificateException | CertIOException | OperatorCreationException e) { throw new RuntimeException(e); } } } }
Logging on error might be a bit too strict for updates?
public void run() { AthenzCredentials currentCredentials = credentials.get(); try { AthenzCredentials newCredentials = isExpired(currentCredentials) ? athenzCredentialsService.registerInstance() : athenzCredentialsService.updateCredentials(currentCredentials); credentials.set(newCredentials); scheduler.schedule(new UpdateCredentialsTask(), UPDATE_PERIOD); } catch (Throwable t) { log.log(LogLevel.ERROR, "Failed to update credentials: " + t.getMessage(), t); lastThrowable.set(t); Duration timeToExpiration = Duration.between(clock.instant(), getExpirationTime(currentCredentials)); Duration updatePeriod = timeToExpiration.compareTo(UPDATE_PERIOD) > 0 ? UPDATE_PERIOD : REDUCED_UPDATE_PERIOD; scheduler.schedule(new UpdateCredentialsTask(), updatePeriod); } }
log.log(LogLevel.ERROR, "Failed to update credentials: " + t.getMessage(), t);
public void run() { try { credentials.set(athenzCredentialsService.registerInstance()); credentialsRetrievedSignal.countDown(); scheduler.schedule(new UpdateCredentialsTask(), UPDATE_PERIOD); } catch (Throwable t) { log.log(LogLevel.ERROR, "Failed to register instance: " + t.getMessage(), t); lastThrowable.set(t); Duration nextBackoffDelay = backoffDelay.multipliedBy(BACKOFF_DELAY_MULTIPLIER); if (nextBackoffDelay.compareTo(MAX_REGISTER_BACKOFF_DELAY) > 0) { nextBackoffDelay = MAX_REGISTER_BACKOFF_DELAY; } scheduler.schedule(new RegisterInstanceTask(nextBackoffDelay), backoffDelay); } }
class RegisterInstanceTask implements RunnableWithTag { private final Duration backoffDelay; RegisterInstanceTask() { this(INITIAL_BACKOFF_DELAY); } RegisterInstanceTask(Duration backoffDelay) { this.backoffDelay = backoffDelay; } @Override @Override public String tag() { return REGISTER_INSTANCE_TAG; } }
class RegisterInstanceTask implements RunnableWithTag { private final Duration backoffDelay; RegisterInstanceTask() { this(INITIAL_BACKOFF_DELAY); } RegisterInstanceTask(Duration backoffDelay) { this.backoffDelay = backoffDelay; } @Override @Override public String tag() { return REGISTER_INSTANCE_TAG; } }
This no longer works, after parallell steps. It is also superseded by the validateSteps which is called after this method in the constructor.
private static List<Step> completeSteps(List<Step> steps) { if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) && steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) { steps.add(new DeclaredZone(Environment.staging)); } if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) && steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) { steps.add(new DeclaredZone(Environment.test)); } DeclaredZone testStep = remove(Environment.test, steps); if (testStep != null) steps.add(0, testStep); DeclaredZone stagingStep = remove(Environment.staging, steps); if (stagingStep != null) steps.add(1, stagingStep); return steps; }
steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) {
private static List<Step> completeSteps(List<Step> steps) { if (steps.stream().anyMatch(step -> step.deploysTo(Environment.prod)) && steps.stream().noneMatch(step -> step.deploysTo(Environment.staging))) { steps.add(new DeclaredZone(Environment.staging)); } if (steps.stream().anyMatch(step -> step.deploysTo(Environment.staging)) && steps.stream().noneMatch(step -> step.deploysTo(Environment.test))) { steps.add(new DeclaredZone(Environment.test)); } DeclaredZone testStep = remove(Environment.test, steps); if (testStep != null) steps.add(0, testStep); DeclaredZone stagingStep = remove(Environment.staging, steps); if (stagingStep != null) steps.add(1, stagingStep); return steps; }
class DeploymentSpec { /** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */ public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(), UpgradePolicy.defaultPolicy, Collections.emptyList(), Collections.emptyList(), "<deployment version='1.0'/>"); private final Optional<String> globalServiceId; private final UpgradePolicy upgradePolicy; private final List<ChangeBlocker> changeBlockers; private final List<Step> steps; private final String xmlForm; public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, List<ChangeBlocker> changeBlockers, List<Step> steps) { this(globalServiceId, upgradePolicy, changeBlockers, steps, null); } public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm) { validateTotalDelay(steps); this.globalServiceId = globalServiceId; this.upgradePolicy = upgradePolicy; this.changeBlockers = changeBlockers; this.steps = ImmutableList.copyOf(completeSteps(new ArrayList<>(steps))); this.xmlForm = xmlForm; validateZones(this.steps); } /** Throw an IllegalArgumentException if the total delay exceeds 24 hours */ private void validateTotalDelay(List<Step> steps) { long totalDelaySeconds = steps.stream().filter(step -> step instanceof Delay) .mapToLong(delay -> ((Delay)delay).duration().getSeconds()) .sum(); if (totalDelaySeconds > Duration.ofHours(24).getSeconds()) throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) + " but max 24 hours is allowed"); } /** Throw an IllegalArgumentException if any production zone is declared multiple times */ private void validateZones(List<Step> steps) { Set<DeclaredZone> zones = new HashSet<>(); for (Step step : steps) for (DeclaredZone zone : step.zones()) ensureUnique(zone, zones); } private void ensureUnique(DeclaredZone zone, Set<DeclaredZone> zones) { if ( ! zones.add(zone)) throw new IllegalArgumentException(zone + " is listed twice in deployment.xml"); } /** Adds missing required steps and reorders steps to a permissible order */ /** * Removes the first occurrence of a deployment step to the given environment and returns it. * * @return the removed step, or null if it is not present */ private static DeclaredZone remove(Environment environment, List<Step> steps) { for (int i = 0; i < steps.size(); i++) { if (steps.get(i).deploysTo(environment)) return (DeclaredZone)steps.remove(i); } return null; } /** Returns the ID of the service to expose through global routing, if present */ public Optional<String> globalServiceId() { return globalServiceId; } /** Returns the upgrade policy of this, which is defaultPolicy if none is specified */ public UpgradePolicy upgradePolicy() { return upgradePolicy; } /** Returns whether upgrade can occur at the given instant */ public boolean canUpgradeAt(Instant instant) { return changeBlockers.stream().filter(block -> block.blocksVersions()) .noneMatch(block -> block.window().includes(instant)); } /** Returns whether an application revision change can occur at the given instant */ public boolean canChangeRevisionAt(Instant instant) { return changeBlockers.stream().filter(block -> block.blocksRevisions()) .noneMatch(block -> block.window().includes(instant)); } /** Returns time windows where upgrades are disallowed */ public List<ChangeBlocker> changeBlocker() { return changeBlockers; } /** Returns the deployment steps of this in the order they will be performed */ public List<Step> steps() { return steps; } /** Returns all the DeclaredZone deployment steps in the order they are declared */ public List<DeclaredZone> zones() { return steps.stream() .flatMap(step -> step.zones().stream()) .collect(Collectors.toList()); } /** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */ public String xmlForm() { return xmlForm; } /** Returns whether this deployment spec specifies the given zone, either implicitly or explicitly */ public boolean includes(Environment environment, Optional<RegionName> region) { for (Step step : steps) if (step.deploysTo(environment, region)) return true; return false; } /** * Creates a deployment spec from XML. * * @throws IllegalArgumentException if the XML is invalid */ public static DeploymentSpec fromXml(Reader reader) { return new DeploymentSpecXmlReader().read(reader); } /** * Creates a deployment spec from XML. * * @throws IllegalArgumentException if the XML is invalid */ public static DeploymentSpec fromXml(String xmlForm) { return fromXml(xmlForm, true); } /** * Creates a deployment spec from XML. * * @throws IllegalArgumentException if the XML is invalid */ public static DeploymentSpec fromXml(String xmlForm, boolean validate) { return new DeploymentSpecXmlReader(validate).read(xmlForm); } public static String toMessageString(Throwable t) { StringBuilder b = new StringBuilder(); String lastMessage = null; String message; for (; t != null; t = t.getCause()) { message = t.getMessage(); if (message == null) continue; if (message.equals(lastMessage)) continue; if (b.length() > 0) { b.append(": "); } b.append(message); lastMessage = message; } return b.toString(); } /** This may be invoked by a continuous build */ public static void main(String[] args) { if (args.length != 2 && args.length != 3) { System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" + "Returns 0 if the specified zone matches the deployment spec, 1 otherwise"); System.exit(1); } try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) { DeploymentSpec spec = DeploymentSpec.fromXml(reader); Environment environment = Environment.from(args[1]); Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty(); if (spec.includes(environment, region)) System.exit(0); else System.exit(1); } catch (Exception e) { System.err.println("Exception checking deployment spec: " + toMessageString(e)); System.exit(1); } } /** A deployment step */ public abstract static class Step { /** Returns whether this step deploys to the given region */ public final boolean deploysTo(Environment environment) { return deploysTo(environment, Optional.empty()); } /** Returns whether this step deploys to the given environment, and (if specified) region */ public abstract boolean deploysTo(Environment environment, Optional<RegionName> region); /** Returns the zones deployed to in this step */ public List<DeclaredZone> zones() { return Collections.emptyList(); } } /** A deployment step which is to wait for some time before progressing to the next step */ public static class Delay extends Step { private final Duration duration; public Delay(Duration duration) { this.duration = duration; } public Duration duration() { return duration; } @Override public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; } } /** A deployment step which is to run deployment in a particular zone */ public static class DeclaredZone extends Step { private final Environment environment; private Optional<RegionName> region; private final boolean active; public DeclaredZone(Environment environment) { this(environment, Optional.empty(), false); } public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) { if (environment != Environment.prod && region.isPresent()) throw new IllegalArgumentException("Non-prod environments cannot specify a region"); if (environment == Environment.prod && ! region.isPresent()) throw new IllegalArgumentException("Prod environments must be specified with a region"); this.environment = environment; this.region = region; this.active = active; } public Environment environment() { return environment; } /** The region name, or empty if not declared */ public Optional<RegionName> region() { return region; } /** Returns whether this zone should receive production traffic */ public boolean active() { return active; } @Override public List<DeclaredZone> zones() { return Collections.singletonList(this); } @Override public boolean deploysTo(Environment environment, Optional<RegionName> region) { if (environment != this.environment) return false; if (region.isPresent() && ! region.equals(this.region)) return false; return true; } @Override public int hashCode() { return Objects.hash(environment, region); } @Override public boolean equals(Object o) { if (o == this) return true; if ( ! (o instanceof DeclaredZone)) return false; DeclaredZone other = (DeclaredZone)o; if (this.environment != other.environment) return false; if ( ! this.region.equals(other.region())) return false; return true; } @Override public String toString() { return environment + ( region.isPresent() ? "." + region.get() : ""); } } /** A deployment step which is to run deployment to multiple zones in parallel */ public static class ParallelZones extends Step { private final List<DeclaredZone> zones; public ParallelZones(List<DeclaredZone> zones) { this.zones = ImmutableList.copyOf(zones); } @Override public List<DeclaredZone> zones() { return this.zones; } @Override public boolean deploysTo(Environment environment, Optional<RegionName> region) { return zones.stream().anyMatch(zone -> zone.deploysTo(environment, region)); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ParallelZones)) return false; ParallelZones that = (ParallelZones) o; return Objects.equals(zones, that.zones); } @Override public int hashCode() { return Objects.hash(zones); } } /** Controls when this application will be upgraded to new Vespa versions */ public enum UpgradePolicy { /** Canary: Applications with this policy will upgrade before any other */ canary, /** Default: Will upgrade after all canary applications upgraded successfully. The default. */ defaultPolicy, /** Will upgrade after most default applications upgraded successfully */ conservative } /** A blocking of changes in a given time window */ public static class ChangeBlocker { private final boolean revision; private final boolean version; private final TimeWindow window; public ChangeBlocker(boolean revision, boolean version, TimeWindow window) { this.revision = revision; this.version = version; this.window = window; } public boolean blocksRevisions() { return revision; } public boolean blocksVersions() { return version; } public TimeWindow window() { return window; } } }
class DeploymentSpec { /** The empty deployment spec, specifying no zones or rotation, and defaults for all settings */ public static final DeploymentSpec empty = new DeploymentSpec(Optional.empty(), UpgradePolicy.defaultPolicy, Collections.emptyList(), Collections.emptyList(), "<deployment version='1.0'/>"); private final Optional<String> globalServiceId; private final UpgradePolicy upgradePolicy; private final List<ChangeBlocker> changeBlockers; private final List<Step> steps; private final String xmlForm; public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, List<ChangeBlocker> changeBlockers, List<Step> steps) { this(globalServiceId, upgradePolicy, changeBlockers, steps, null); } public DeploymentSpec(Optional<String> globalServiceId, UpgradePolicy upgradePolicy, List<ChangeBlocker> changeBlockers, List<Step> steps, String xmlForm) { validateTotalDelay(steps); this.globalServiceId = globalServiceId; this.upgradePolicy = upgradePolicy; this.changeBlockers = changeBlockers; this.steps = ImmutableList.copyOf(completeSteps(new ArrayList<>(steps))); this.xmlForm = xmlForm; validateZones(this.steps); } /** Throw an IllegalArgumentException if the total delay exceeds 24 hours */ private void validateTotalDelay(List<Step> steps) { long totalDelaySeconds = steps.stream().filter(step -> step instanceof Delay) .mapToLong(delay -> ((Delay)delay).duration().getSeconds()) .sum(); if (totalDelaySeconds > Duration.ofHours(24).getSeconds()) throw new IllegalArgumentException("The total delay specified is " + Duration.ofSeconds(totalDelaySeconds) + " but max 24 hours is allowed"); } /** Throw an IllegalArgumentException if any production zone is declared multiple times */ private void validateZones(List<Step> steps) { Set<DeclaredZone> zones = new HashSet<>(); for (Step step : steps) for (DeclaredZone zone : step.zones()) ensureUnique(zone, zones); } private void ensureUnique(DeclaredZone zone, Set<DeclaredZone> zones) { if ( ! zones.add(zone)) throw new IllegalArgumentException(zone + " is listed twice in deployment.xml"); } /** Adds missing required steps and reorders steps to a permissible order */ /** * Removes the first occurrence of a deployment step to the given environment and returns it. * * @return the removed step, or null if it is not present */ private static DeclaredZone remove(Environment environment, List<Step> steps) { for (int i = 0; i < steps.size(); i++) { if (steps.get(i).deploysTo(environment)) return (DeclaredZone)steps.remove(i); } return null; } /** Returns the ID of the service to expose through global routing, if present */ public Optional<String> globalServiceId() { return globalServiceId; } /** Returns the upgrade policy of this, which is defaultPolicy if none is specified */ public UpgradePolicy upgradePolicy() { return upgradePolicy; } /** Returns whether upgrade can occur at the given instant */ public boolean canUpgradeAt(Instant instant) { return changeBlockers.stream().filter(block -> block.blocksVersions()) .noneMatch(block -> block.window().includes(instant)); } /** Returns whether an application revision change can occur at the given instant */ public boolean canChangeRevisionAt(Instant instant) { return changeBlockers.stream().filter(block -> block.blocksRevisions()) .noneMatch(block -> block.window().includes(instant)); } /** Returns time windows where upgrades are disallowed */ public List<ChangeBlocker> changeBlocker() { return changeBlockers; } /** Returns the deployment steps of this in the order they will be performed */ public List<Step> steps() { return steps; } /** Returns all the DeclaredZone deployment steps in the order they are declared */ public List<DeclaredZone> zones() { return steps.stream() .flatMap(step -> step.zones().stream()) .collect(Collectors.toList()); } /** Returns the XML form of this spec, or null if it was not created by fromXml, nor is empty */ public String xmlForm() { return xmlForm; } /** Returns whether this deployment spec specifies the given zone, either implicitly or explicitly */ public boolean includes(Environment environment, Optional<RegionName> region) { for (Step step : steps) if (step.deploysTo(environment, region)) return true; return false; } /** * Creates a deployment spec from XML. * * @throws IllegalArgumentException if the XML is invalid */ public static DeploymentSpec fromXml(Reader reader) { return new DeploymentSpecXmlReader().read(reader); } /** * Creates a deployment spec from XML. * * @throws IllegalArgumentException if the XML is invalid */ public static DeploymentSpec fromXml(String xmlForm) { return fromXml(xmlForm, true); } /** * Creates a deployment spec from XML. * * @throws IllegalArgumentException if the XML is invalid */ public static DeploymentSpec fromXml(String xmlForm, boolean validate) { return new DeploymentSpecXmlReader(validate).read(xmlForm); } public static String toMessageString(Throwable t) { StringBuilder b = new StringBuilder(); String lastMessage = null; String message; for (; t != null; t = t.getCause()) { message = t.getMessage(); if (message == null) continue; if (message.equals(lastMessage)) continue; if (b.length() > 0) { b.append(": "); } b.append(message); lastMessage = message; } return b.toString(); } /** This may be invoked by a continuous build */ public static void main(String[] args) { if (args.length != 2 && args.length != 3) { System.err.println("Usage: DeploymentSpec [file] [environment] [region]?" + "Returns 0 if the specified zone matches the deployment spec, 1 otherwise"); System.exit(1); } try (BufferedReader reader = new BufferedReader(new FileReader(args[0]))) { DeploymentSpec spec = DeploymentSpec.fromXml(reader); Environment environment = Environment.from(args[1]); Optional<RegionName> region = args.length == 3 ? Optional.of(RegionName.from(args[2])) : Optional.empty(); if (spec.includes(environment, region)) System.exit(0); else System.exit(1); } catch (Exception e) { System.err.println("Exception checking deployment spec: " + toMessageString(e)); System.exit(1); } } /** A deployment step */ public abstract static class Step { /** Returns whether this step deploys to the given region */ public final boolean deploysTo(Environment environment) { return deploysTo(environment, Optional.empty()); } /** Returns whether this step deploys to the given environment, and (if specified) region */ public abstract boolean deploysTo(Environment environment, Optional<RegionName> region); /** Returns the zones deployed to in this step */ public List<DeclaredZone> zones() { return Collections.emptyList(); } } /** A deployment step which is to wait for some time before progressing to the next step */ public static class Delay extends Step { private final Duration duration; public Delay(Duration duration) { this.duration = duration; } public Duration duration() { return duration; } @Override public boolean deploysTo(Environment environment, Optional<RegionName> region) { return false; } } /** A deployment step which is to run deployment in a particular zone */ public static class DeclaredZone extends Step { private final Environment environment; private Optional<RegionName> region; private final boolean active; public DeclaredZone(Environment environment) { this(environment, Optional.empty(), false); } public DeclaredZone(Environment environment, Optional<RegionName> region, boolean active) { if (environment != Environment.prod && region.isPresent()) throw new IllegalArgumentException("Non-prod environments cannot specify a region"); if (environment == Environment.prod && ! region.isPresent()) throw new IllegalArgumentException("Prod environments must be specified with a region"); this.environment = environment; this.region = region; this.active = active; } public Environment environment() { return environment; } /** The region name, or empty if not declared */ public Optional<RegionName> region() { return region; } /** Returns whether this zone should receive production traffic */ public boolean active() { return active; } @Override public List<DeclaredZone> zones() { return Collections.singletonList(this); } @Override public boolean deploysTo(Environment environment, Optional<RegionName> region) { if (environment != this.environment) return false; if (region.isPresent() && ! region.equals(this.region)) return false; return true; } @Override public int hashCode() { return Objects.hash(environment, region); } @Override public boolean equals(Object o) { if (o == this) return true; if ( ! (o instanceof DeclaredZone)) return false; DeclaredZone other = (DeclaredZone)o; if (this.environment != other.environment) return false; if ( ! this.region.equals(other.region())) return false; return true; } @Override public String toString() { return environment + ( region.isPresent() ? "." + region.get() : ""); } } /** A deployment step which is to run deployment to multiple zones in parallel */ public static class ParallelZones extends Step { private final List<DeclaredZone> zones; public ParallelZones(List<DeclaredZone> zones) { this.zones = ImmutableList.copyOf(zones); } @Override public List<DeclaredZone> zones() { return this.zones; } @Override public boolean deploysTo(Environment environment, Optional<RegionName> region) { return zones.stream().anyMatch(zone -> zone.deploysTo(environment, region)); } @Override public boolean equals(Object o) { if (this == o) return true; if (!(o instanceof ParallelZones)) return false; ParallelZones that = (ParallelZones) o; return Objects.equals(zones, that.zones); } @Override public int hashCode() { return Objects.hash(zones); } } /** Controls when this application will be upgraded to new Vespa versions */ public enum UpgradePolicy { /** Canary: Applications with this policy will upgrade before any other */ canary, /** Default: Will upgrade after all canary applications upgraded successfully. The default. */ defaultPolicy, /** Will upgrade after most default applications upgraded successfully */ conservative } /** A blocking of changes in a given time window */ public static class ChangeBlocker { private final boolean revision; private final boolean version; private final TimeWindow window; public ChangeBlocker(boolean revision, boolean version, TimeWindow window) { this.revision = revision; this.version = version; this.window = window; } public boolean blocksRevisions() { return revision; } public boolean blocksVersions() { return version; } public TimeWindow window() { return window; } } }
Changed these two to accept collections and return lists, to clarify intent, and to avoid needless complexity.
public List<Deployment> sortBy(List<DeploymentSpec.DeclaredZone> zones, Collection<Deployment> deployments) { List<Zone> productionZones = zones.stream() .filter(z -> z.region().isPresent()) .map(z -> new Zone(z.environment(), z.region().get())) .collect(toList()); return deployments.stream() .sorted(comparingInt(deployment -> productionZones.indexOf(deployment.zone()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); }
}
public List<Deployment> sortBy(List<DeploymentSpec.DeclaredZone> zones, Collection<Deployment> deployments) { List<Zone> productionZones = zones.stream() .filter(z -> z.region().isPresent()) .map(z -> new Zone(z.environment(), z.region().get())) .collect(toList()); return deployments.stream() .sorted(comparingInt(deployment -> productionZones.indexOf(deployment.zone()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); }
class DeploymentOrder { private static final Logger log = Logger.getLogger(DeploymentOrder.class.getName()); private final Controller controller; private final Clock clock; public DeploymentOrder(Controller controller) { Objects.requireNonNull(controller, "controller cannot be null"); this.controller = controller; this.clock = controller.clock(); } /** Returns a list of jobs to trigger after the given job */ public List<JobType> nextAfter(JobType job, LockedApplication application) { if ( ! application.deploying().isPresent()) { return Collections.emptyList(); } if (job == JobType.component) { return Collections.singletonList(JobType.systemTest); } List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); Optional<DeploymentSpec.Step> currentStep = fromJob(job, application); if ( ! currentStep.isPresent()) { return Collections.emptyList(); } int currentIndex = deploymentSteps.indexOf(currentStep.get()); if (currentIndex == deploymentSteps.size() - 1) { return Collections.emptyList(); } if ( ! completedSuccessfully(currentStep.get(), application.deploying().get(), application)) { return Collections.emptyList(); } Duration delay = delayAfter(currentStep.get(), application); if (shouldPostponeDeployment(delay, job, application)) { log.info(String.format("Delaying next job after %s of %s by %s", job, application, delay)); return Collections.emptyList(); } DeploymentSpec.Step nextStep = deploymentSteps.get(currentIndex + 1); return nextStep.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether the given job causes an application change */ public boolean givesApplicationChange(JobType job) { return job == JobType.component; } /** Returns whether the given job is last in a deployment */ public boolean isLast(JobType job, Application application) { List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); if (deploymentSteps.isEmpty()) { return false; } DeploymentSpec.Step lastStep = deploymentSteps.get(deploymentSteps.size() - 1); Optional<DeploymentSpec.Step> step = fromJob(job, application); return step.map(s -> s.equals(lastStep)).orElse(false); } /** Returns jobs for given deployment spec, in the order they are declared */ public List<JobType> jobsFrom(DeploymentSpec deploymentSpec) { return deploymentSpec.steps().stream() .flatMap(step -> jobsFrom(step).stream()) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns job status sorted according to deployment spec */ public List<JobStatus> sortBy(DeploymentSpec deploymentSpec, Collection<JobStatus> jobStatus) { List<DeploymentJobs.JobType> sortedJobs = jobsFrom(deploymentSpec); return jobStatus.stream() .sorted(comparingInt(job -> sortedJobs.indexOf(job.type()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns deployments sorted according to declared zones */ /** Returns jobs for the given step */ private List<JobType> jobsFrom(DeploymentSpec.Step step) { return step.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether all jobs have completed successfully for given step */ private boolean completedSuccessfully(DeploymentSpec.Step step, Change change, Application application) { return jobsFrom(step).stream() .allMatch(job -> application.deploymentJobs().isSuccessful(change, job)); } /** Resolve deployment step from job */ private Optional<DeploymentSpec.Step> fromJob(JobType job, Application application) { for (DeploymentSpec.Step step : application.deploymentSpec().steps()) { if (step.deploysTo(job.environment(), job.isProduction() ? job.region(controller.system()) : Optional.empty())) { return Optional.of(step); } } return Optional.empty(); } /** Resolve job from deployment step */ private JobType toJob(DeploymentSpec.DeclaredZone zone) { return JobType.from(controller.system(), zone.environment(), zone.region().orElse(null)) .orElseThrow(() -> new IllegalArgumentException("Invalid zone " + zone)); } /** Returns whether deployment should be postponed according to delay */ private boolean shouldPostponeDeployment(Duration delay, JobType job, Application application) { Optional<Instant> lastSuccess = Optional.ofNullable(application.deploymentJobs().jobStatus().get(job)) .flatMap(JobStatus::lastSuccess) .map(JobStatus.JobRun::at); return lastSuccess.isPresent() && lastSuccess.get().plus(delay).isAfter(clock.instant()); } /** Find all steps that deploy to one or more zones */ private static List<DeploymentSpec.Step> deploymentSteps(Application application) { return application.deploymentSpec().steps().stream() .filter(step -> ! step.zones().isEmpty()) .collect(toList()); } /** Determines the delay that should pass after the given step */ private static Duration delayAfter(DeploymentSpec.Step step, Application application) { int stepIndex = application.deploymentSpec().steps().indexOf(step); if (stepIndex == -1 || stepIndex == application.deploymentSpec().steps().size() - 1) { return Duration.ZERO; } Duration totalDelay = Duration.ZERO; List<DeploymentSpec.Step> remainingSteps = application.deploymentSpec().steps() .subList(stepIndex + 1, application.deploymentSpec().steps().size()); for (DeploymentSpec.Step s : remainingSteps) { if (!(s instanceof DeploymentSpec.Delay)) { break; } totalDelay = totalDelay.plus(((DeploymentSpec.Delay) s).duration()); } return totalDelay; } }
class DeploymentOrder { private static final Logger log = Logger.getLogger(DeploymentOrder.class.getName()); private final Controller controller; private final Clock clock; public DeploymentOrder(Controller controller) { Objects.requireNonNull(controller, "controller cannot be null"); this.controller = controller; this.clock = controller.clock(); } /** Returns a list of jobs to trigger after the given job */ public List<JobType> nextAfter(JobType job, LockedApplication application) { if ( ! application.deploying().isPresent()) { return Collections.emptyList(); } if (job == JobType.component) { return Collections.singletonList(JobType.systemTest); } List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); Optional<DeploymentSpec.Step> currentStep = fromJob(job, application); if ( ! currentStep.isPresent()) { return Collections.emptyList(); } int currentIndex = deploymentSteps.indexOf(currentStep.get()); if (currentIndex == deploymentSteps.size() - 1) { return Collections.emptyList(); } if ( ! completedSuccessfully(currentStep.get(), application.deploying().get(), application)) { return Collections.emptyList(); } Duration delay = delayAfter(currentStep.get(), application); if (shouldPostponeDeployment(delay, job, application)) { log.info(String.format("Delaying next job after %s of %s by %s", job, application, delay)); return Collections.emptyList(); } DeploymentSpec.Step nextStep = deploymentSteps.get(currentIndex + 1); return nextStep.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether the given job causes an application change */ public boolean givesApplicationChange(JobType job) { return job == JobType.component; } /** Returns whether the given job is last in a deployment */ public boolean isLast(JobType job, Application application) { List<DeploymentSpec.Step> deploymentSteps = deploymentSteps(application); if (deploymentSteps.isEmpty()) { return false; } DeploymentSpec.Step lastStep = deploymentSteps.get(deploymentSteps.size() - 1); Optional<DeploymentSpec.Step> step = fromJob(job, application); return step.map(s -> s.equals(lastStep)).orElse(false); } /** Returns jobs for given deployment spec, in the order they are declared */ public List<JobType> jobsFrom(DeploymentSpec deploymentSpec) { return deploymentSpec.steps().stream() .flatMap(step -> jobsFrom(step).stream()) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns job status sorted according to deployment spec */ public List<JobStatus> sortBy(DeploymentSpec deploymentSpec, Collection<JobStatus> jobStatus) { List<DeploymentJobs.JobType> sortedJobs = jobsFrom(deploymentSpec); return jobStatus.stream() .sorted(comparingInt(job -> sortedJobs.indexOf(job.type()))) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns deployments sorted according to declared zones */ /** Returns jobs for the given step */ private List<JobType> jobsFrom(DeploymentSpec.Step step) { return step.zones().stream() .map(this::toJob) .collect(collectingAndThen(toList(), Collections::unmodifiableList)); } /** Returns whether all jobs have completed successfully for given step */ private boolean completedSuccessfully(DeploymentSpec.Step step, Change change, Application application) { return jobsFrom(step).stream() .allMatch(job -> application.deploymentJobs().isSuccessful(change, job)); } /** Resolve deployment step from job */ private Optional<DeploymentSpec.Step> fromJob(JobType job, Application application) { for (DeploymentSpec.Step step : application.deploymentSpec().steps()) { if (step.deploysTo(job.environment(), job.isProduction() ? job.region(controller.system()) : Optional.empty())) { return Optional.of(step); } } return Optional.empty(); } /** Resolve job from deployment step */ private JobType toJob(DeploymentSpec.DeclaredZone zone) { return JobType.from(controller.system(), zone.environment(), zone.region().orElse(null)) .orElseThrow(() -> new IllegalArgumentException("Invalid zone " + zone)); } /** Returns whether deployment should be postponed according to delay */ private boolean shouldPostponeDeployment(Duration delay, JobType job, Application application) { Optional<Instant> lastSuccess = Optional.ofNullable(application.deploymentJobs().jobStatus().get(job)) .flatMap(JobStatus::lastSuccess) .map(JobStatus.JobRun::at); return lastSuccess.isPresent() && lastSuccess.get().plus(delay).isAfter(clock.instant()); } /** Find all steps that deploy to one or more zones */ private static List<DeploymentSpec.Step> deploymentSteps(Application application) { return application.deploymentSpec().steps().stream() .filter(step -> ! step.zones().isEmpty()) .collect(toList()); } /** Determines the delay that should pass after the given step */ private static Duration delayAfter(DeploymentSpec.Step step, Application application) { int stepIndex = application.deploymentSpec().steps().indexOf(step); if (stepIndex == -1 || stepIndex == application.deploymentSpec().steps().size() - 1) { return Duration.ZERO; } Duration totalDelay = Duration.ZERO; List<DeploymentSpec.Step> remainingSteps = application.deploymentSpec().steps() .subList(stepIndex + 1, application.deploymentSpec().steps().size()); for (DeploymentSpec.Step s : remainingSteps) { if (!(s instanceof DeploymentSpec.Delay)) { break; } totalDelay = totalDelay.plus(((DeploymentSpec.Delay) s).duration()); } return totalDelay; } }
This.
public void notifyJobCompletion(JobType jobType, Application application, Optional<DeploymentJobs.JobError> jobError) { clock().advance(Duration.ofMillis(1)); applications().notifyJobCompletion(jobReport(application, jobType, jobError)); }
clock().advance(Duration.ofMillis(1));
public void notifyJobCompletion(JobType jobType, Application application, Optional<DeploymentJobs.JobError> jobError) { clock().advance(Duration.ofMillis(1)); applications().notifyJobCompletion(jobReport(application, jobType, jobError)); }
class DeploymentTester { private static final Duration maintenanceInterval = Duration.ofDays(1); private final ControllerTester tester; private final Upgrader upgrader; private final FailureRedeployer failureRedeployer; public DeploymentTester() { this(new ControllerTester()); } public DeploymentTester(ControllerTester tester) { this.tester = tester; tester.curator().writeUpgradesPerMinute(100); this.upgrader = new Upgrader(tester.controller(), maintenanceInterval, new JobControl(tester.curator()), tester.curator()); this.failureRedeployer = new FailureRedeployer(tester.controller(), maintenanceInterval, new JobControl(tester.curator())); } public Upgrader upgrader() { return upgrader; } public FailureRedeployer failureRedeployer() { return failureRedeployer; } public Controller controller() { return tester.controller(); } public ApplicationController applications() { return tester.controller().applications(); } public BuildSystem buildSystem() { return tester.controller().applications().deploymentTrigger().buildSystem(); } public DeploymentTrigger deploymentTrigger() { return tester.controller().applications().deploymentTrigger(); } public ManualClock clock() { return tester.clock(); } public ControllerTester controllerTester() { return tester; } public ConfigServerClientMock configServer() { return tester.configServer(); } public Application application(String name) { return application(ApplicationId.from("tenant1", name, "default")); } public Application application(ApplicationId application) { return controller().applications().require(application); } public Optional<Change.VersionChange> versionChange(ApplicationId application) { return application(application).deploying() .filter(c -> c instanceof Change.VersionChange) .map(Change.VersionChange.class::cast); } public void updateVersionStatus() { controller().updateVersionStatus(VersionStatus.compute(controller(), tester.controller().systemVersion())); } public void updateVersionStatus(Version currentVersion) { configServer().setDefaultVersion(currentVersion); controller().updateVersionStatus(VersionStatus.compute(controller(), currentVersion)); } public void upgradeSystem(Version version) { controllerTester().configServer().setDefaultVersion(version); updateVersionStatus(version); upgrader().maintain(); } public Application createApplication(String applicationName, String tenantName, long projectId, Long propertyId) { TenantId tenant = tester.createTenant(tenantName, UUID.randomUUID().toString(), propertyId); return tester.createApplication(tenant, applicationName, "default", projectId); } public void restartController() { tester.createNewController(); } /** Simulate the full lifecycle of an application deployment as declared in given application package */ public Application createAndDeploy(String applicationName, int projectId, ApplicationPackage applicationPackage) { tester.createTenant("tenant1", "domain1", 1L); Application application = tester.createApplication(new TenantId("tenant1"), applicationName, "default", projectId); deployCompletely(application, applicationPackage); return applications().require(application.id()); } /** Simulate the full lifecycle of an application deployment to prod.us-west-1 with the given upgrade policy */ public Application createAndDeploy(String applicationName, int projectId, String upgradePolicy) { return createAndDeploy(applicationName, projectId, applicationPackage(upgradePolicy)); } /** Complete an ongoing deployment */ public void deployCompletely(String applicationName) { deployCompletely(applications().require(ApplicationId.from("tenant1", applicationName, "default")), applicationPackage("default")); } /** Deploy application completely using the given application package */ public void deployCompletely(Application application, ApplicationPackage applicationPackage) { notifyJobCompletion(JobType.component, application, true); assertTrue(applications().require(application.id()).deploying().isPresent()); completeDeployment(application, applicationPackage, Optional.empty(), true); } public static DeploymentJobs.JobReport jobReport(Application application, JobType jobType, boolean success) { return jobReport(application, jobType, Optional.ofNullable(success ? null : unknown)); } public static DeploymentJobs.JobReport jobReport(Application application, JobType jobType, Optional<DeploymentJobs.JobError> jobError) { return new DeploymentJobs.JobReport( application.id(), jobType, application.deploymentJobs().projectId().get(), 42, jobError ); } /** Deploy application using the given application package, but expecting to stop after test phases */ public void deployTestOnly(Application application, ApplicationPackage applicationPackage) { notifyJobCompletion(JobType.component, application, true); assertTrue(applications().require(application.id()).deploying().isPresent()); completeDeployment(application, applicationPackage, Optional.empty(), false); } private void completeDeployment(Application application, ApplicationPackage applicationPackage, Optional<JobType> failOnJob, boolean includingProductionZones) { DeploymentOrder order = new DeploymentOrder(controller()); List<JobType> jobs = order.jobsFrom(applicationPackage.deploymentSpec()); if ( ! includingProductionZones) jobs = jobs.stream().filter(job -> ! job.isProduction()).collect(Collectors.toList()); for (JobType job : jobs) { boolean failJob = failOnJob.map(j -> j.equals(job)).orElse(false); deployAndNotify(application, applicationPackage, ! failJob, false, job); if (failJob) { break; } } if (failOnJob.isPresent()) { assertTrue(applications().require(application.id()).deploying().isPresent()); assertTrue(applications().require(application.id()).deploymentJobs().hasFailures()); } else if (includingProductionZones) { assertFalse(applications().require(application.id()).deploying().isPresent()); } else { assertTrue(applications().require(application.id()).deploying().isPresent()); } } public void notifyJobCompletion(JobType jobType, Application application, boolean success) { notifyJobCompletion(jobType, application, Optional.ofNullable(success ? null : unknown)); } public void completeUpgrade(Application application, Version version, String upgradePolicy) { assertTrue(applications().require(application.id()).deploying().isPresent()); assertEquals(new Change.VersionChange(version), applications().require(application.id()).deploying().get()); completeDeployment(application, applicationPackage(upgradePolicy), Optional.empty(), true); } public void completeUpgradeWithError(Application application, Version version, String upgradePolicy, JobType failOnJob) { completeUpgradeWithError(application, version, applicationPackage(upgradePolicy), Optional.of(failOnJob)); } public void completeUpgradeWithError(Application application, Version version, ApplicationPackage applicationPackage, JobType failOnJob) { completeUpgradeWithError(application, version, applicationPackage, Optional.of(failOnJob)); } private void completeUpgradeWithError(Application application, Version version, ApplicationPackage applicationPackage, Optional<JobType> failOnJob) { assertTrue(applications().require(application.id()).deploying().isPresent()); assertEquals(new Change.VersionChange(version), applications().require(application.id()).deploying().get()); completeDeployment(application, applicationPackage, failOnJob, true); } public void deploy(JobType job, Application application, ApplicationPackage applicationPackage) { deploy(job, application, applicationPackage, false); } public void deploy(JobType job, Application application, ApplicationPackage applicationPackage, boolean deployCurrentVersion) { job.zone(controller().system()).ifPresent(zone -> tester.deploy(application, zone, applicationPackage, deployCurrentVersion)); } public void deployAndNotify(Application application, ApplicationPackage applicationPackage, boolean success, JobType... jobs) { deployAndNotify(application, applicationPackage, success, true, jobs); } public void deployAndNotify(Application application, ApplicationPackage applicationPackage, boolean success, boolean expectOnlyTheseJobs, JobType... jobs) { consumeJobs(application, expectOnlyTheseJobs, jobs); for (JobType job : jobs) { if (success) { deploy(job, application, applicationPackage); } notifyJobCompletion(job, application, success); } } /** Assert that the sceduled jobs of this application are exactly those given, and take them */ private void consumeJobs(Application application, boolean expectOnlyTheseJobs, JobType... jobs) { for (JobType job : jobs) { BuildService.BuildJob buildJob = findJob(application, job); assertEquals((long) application.deploymentJobs().projectId().get(), buildJob.projectId()); assertEquals(job.jobName(), buildJob.jobName()); } if (expectOnlyTheseJobs) assertEquals(jobs.length, countJobsOf(application)); buildSystem().removeJobs(application.id()); } private BuildService.BuildJob findJob(Application application, JobType jobType) { for (BuildService.BuildJob job : buildSystem().jobs()) if (job.projectId() == application.deploymentJobs().projectId().get() && job.jobName().equals(jobType.jobName())) return job; throw new NoSuchElementException(jobType + " is not scheduled for " + application); } private int countJobsOf(Application application) { return (int)buildSystem().jobs().stream() .filter(job -> job.projectId() == application.deploymentJobs().projectId().get()) .count(); } public static ApplicationPackage applicationPackage(String upgradePolicy) { return new ApplicationPackageBuilder() .upgradePolicy(upgradePolicy) .environment(Environment.prod) .region("us-west-1") .build(); } }
class DeploymentTester { private static final Duration maintenanceInterval = Duration.ofDays(1); private final ControllerTester tester; private final Upgrader upgrader; private final FailureRedeployer failureRedeployer; public DeploymentTester() { this(new ControllerTester()); } public DeploymentTester(ControllerTester tester) { this.tester = tester; tester.curator().writeUpgradesPerMinute(100); this.upgrader = new Upgrader(tester.controller(), maintenanceInterval, new JobControl(tester.curator()), tester.curator()); this.failureRedeployer = new FailureRedeployer(tester.controller(), maintenanceInterval, new JobControl(tester.curator())); } public Upgrader upgrader() { return upgrader; } public FailureRedeployer failureRedeployer() { return failureRedeployer; } public Controller controller() { return tester.controller(); } public ApplicationController applications() { return tester.controller().applications(); } public BuildSystem buildSystem() { return tester.controller().applications().deploymentTrigger().buildSystem(); } public DeploymentTrigger deploymentTrigger() { return tester.controller().applications().deploymentTrigger(); } public ManualClock clock() { return tester.clock(); } public ControllerTester controllerTester() { return tester; } public ConfigServerClientMock configServer() { return tester.configServer(); } public Application application(String name) { return application(ApplicationId.from("tenant1", name, "default")); } public Application application(ApplicationId application) { return controller().applications().require(application); } public Optional<Change.VersionChange> versionChange(ApplicationId application) { return application(application).deploying() .filter(c -> c instanceof Change.VersionChange) .map(Change.VersionChange.class::cast); } public void updateVersionStatus() { controller().updateVersionStatus(VersionStatus.compute(controller(), tester.controller().systemVersion())); } public void updateVersionStatus(Version currentVersion) { configServer().setDefaultVersion(currentVersion); controller().updateVersionStatus(VersionStatus.compute(controller(), currentVersion)); } public void upgradeSystem(Version version) { controllerTester().configServer().setDefaultVersion(version); updateVersionStatus(version); upgrader().maintain(); } public Application createApplication(String applicationName, String tenantName, long projectId, Long propertyId) { TenantId tenant = tester.createTenant(tenantName, UUID.randomUUID().toString(), propertyId); return tester.createApplication(tenant, applicationName, "default", projectId); } public void restartController() { tester.createNewController(); } /** Simulate the full lifecycle of an application deployment as declared in given application package */ public Application createAndDeploy(String applicationName, int projectId, ApplicationPackage applicationPackage) { tester.createTenant("tenant1", "domain1", 1L); Application application = tester.createApplication(new TenantId("tenant1"), applicationName, "default", projectId); deployCompletely(application, applicationPackage); return applications().require(application.id()); } /** Simulate the full lifecycle of an application deployment to prod.us-west-1 with the given upgrade policy */ public Application createAndDeploy(String applicationName, int projectId, String upgradePolicy) { return createAndDeploy(applicationName, projectId, applicationPackage(upgradePolicy)); } /** Complete an ongoing deployment */ public void deployCompletely(String applicationName) { deployCompletely(applications().require(ApplicationId.from("tenant1", applicationName, "default")), applicationPackage("default")); } /** Deploy application completely using the given application package */ public void deployCompletely(Application application, ApplicationPackage applicationPackage) { notifyJobCompletion(JobType.component, application, true); assertTrue(applications().require(application.id()).deploying().isPresent()); completeDeployment(application, applicationPackage, Optional.empty(), true); } public static DeploymentJobs.JobReport jobReport(Application application, JobType jobType, boolean success) { return jobReport(application, jobType, Optional.ofNullable(success ? null : unknown)); } public static DeploymentJobs.JobReport jobReport(Application application, JobType jobType, Optional<DeploymentJobs.JobError> jobError) { return new DeploymentJobs.JobReport( application.id(), jobType, application.deploymentJobs().projectId().get(), 42, jobError ); } /** Deploy application using the given application package, but expecting to stop after test phases */ public void deployTestOnly(Application application, ApplicationPackage applicationPackage) { notifyJobCompletion(JobType.component, application, true); assertTrue(applications().require(application.id()).deploying().isPresent()); completeDeployment(application, applicationPackage, Optional.empty(), false); } private void completeDeployment(Application application, ApplicationPackage applicationPackage, Optional<JobType> failOnJob, boolean includingProductionZones) { DeploymentOrder order = new DeploymentOrder(controller()); List<JobType> jobs = order.jobsFrom(applicationPackage.deploymentSpec()); if ( ! includingProductionZones) jobs = jobs.stream().filter(job -> ! job.isProduction()).collect(Collectors.toList()); for (JobType job : jobs) { boolean failJob = failOnJob.map(j -> j.equals(job)).orElse(false); deployAndNotify(application, applicationPackage, ! failJob, false, job); if (failJob) { break; } } if (failOnJob.isPresent()) { assertTrue(applications().require(application.id()).deploying().isPresent()); assertTrue(applications().require(application.id()).deploymentJobs().hasFailures()); } else if (includingProductionZones) { assertFalse(applications().require(application.id()).deploying().isPresent()); } else { assertTrue(applications().require(application.id()).deploying().isPresent()); } } public void notifyJobCompletion(JobType jobType, Application application, boolean success) { notifyJobCompletion(jobType, application, Optional.ofNullable(success ? null : unknown)); } public void completeUpgrade(Application application, Version version, String upgradePolicy) { assertTrue(applications().require(application.id()).deploying().isPresent()); assertEquals(new Change.VersionChange(version), applications().require(application.id()).deploying().get()); completeDeployment(application, applicationPackage(upgradePolicy), Optional.empty(), true); } public void completeUpgradeWithError(Application application, Version version, String upgradePolicy, JobType failOnJob) { completeUpgradeWithError(application, version, applicationPackage(upgradePolicy), Optional.of(failOnJob)); } public void completeUpgradeWithError(Application application, Version version, ApplicationPackage applicationPackage, JobType failOnJob) { completeUpgradeWithError(application, version, applicationPackage, Optional.of(failOnJob)); } private void completeUpgradeWithError(Application application, Version version, ApplicationPackage applicationPackage, Optional<JobType> failOnJob) { assertTrue(applications().require(application.id()).deploying().isPresent()); assertEquals(new Change.VersionChange(version), applications().require(application.id()).deploying().get()); completeDeployment(application, applicationPackage, failOnJob, true); } public void deploy(JobType job, Application application, ApplicationPackage applicationPackage) { deploy(job, application, applicationPackage, false); } public void deploy(JobType job, Application application, ApplicationPackage applicationPackage, boolean deployCurrentVersion) { job.zone(controller().system()).ifPresent(zone -> tester.deploy(application, zone, applicationPackage, deployCurrentVersion)); } public void deployAndNotify(Application application, ApplicationPackage applicationPackage, boolean success, JobType... jobs) { deployAndNotify(application, applicationPackage, success, true, jobs); } public void deployAndNotify(Application application, ApplicationPackage applicationPackage, boolean success, boolean expectOnlyTheseJobs, JobType... jobs) { consumeJobs(application, expectOnlyTheseJobs, jobs); for (JobType job : jobs) { if (success) { deploy(job, application, applicationPackage); } notifyJobCompletion(job, application, success); } } /** Assert that the sceduled jobs of this application are exactly those given, and take them */ private void consumeJobs(Application application, boolean expectOnlyTheseJobs, JobType... jobs) { for (JobType job : jobs) { BuildService.BuildJob buildJob = findJob(application, job); assertEquals((long) application.deploymentJobs().projectId().get(), buildJob.projectId()); assertEquals(job.jobName(), buildJob.jobName()); } if (expectOnlyTheseJobs) assertEquals(jobs.length, countJobsOf(application)); buildSystem().removeJobs(application.id()); } private BuildService.BuildJob findJob(Application application, JobType jobType) { for (BuildService.BuildJob job : buildSystem().jobs()) if (job.projectId() == application.deploymentJobs().projectId().get() && job.jobName().equals(jobType.jobName())) return job; throw new NoSuchElementException(jobType + " is not scheduled for " + application); } private int countJobsOf(Application application) { return (int)buildSystem().jobs().stream() .filter(job -> job.projectId() == application.deploymentJobs().projectId().get()) .count(); } public static ApplicationPackage applicationPackage(String upgradePolicy) { return new ApplicationPackageBuilder() .upgradePolicy(upgradePolicy) .environment(Environment.prod) .region("us-west-1") .build(); } }
This is something to consider. I had to add the below to make the test (and logic) right. Perhaps we should rather use a Target with Optional .version() and .revision() methods, instead of Change with subclasses? I think that's both cleaner, it allows modelling simultaneous changes — like we apparently support now — and the current Change is used mostly as a Target, anway.
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
Not sure what you mean by "No" here, did you disallow this? It need to be allowed. Change carries a single change, but it only *decides* the version, it does not decide the revision. Regarding Change: I want to get rid of it too. We should definitely have an optional target version, but it may be better to just infer the revision from the observed job status on demand as that will match what is actually happening.
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
No, and it's just diff noise obscuring the actual change. Lets not have a style discussion though. :-)
private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); }
&& status.lastCompleted().get().lastCompletedWas(change);
private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
I mean that in the current implementation, the ongoing upgrade is overridden, since the application will get a new deploying(), which is an ApplicationChange, from the new component job run. Thus, the first pass through the pipeline upgrades the revision, and a second pass is needed for the version to reach production. I can't say exactly why the test didn't fail before, but the isRunning() was not well behaved for the time-less testing tools (DeploymentTester et al), and I suspect that's why it wasn't caught.
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
On its own: Yes, but the caller has an additional guard.
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
You mean that the caller cancels the VersionChange and rolls out the ApplicationChange instead. I'll remove the question.
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
No, an application change will not overwrite an ongoing version change: // Handle successful starting and ending if (report.success()) { if (order.givesApplicationChange(report.jobType())) { if (acceptNewRevisionNow(application)) { // Set this as the change we are doing, unless we are already pushing a platform change if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } } ... } Anyway, this confusion just illustrates that we should change this model as suggested above.
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
Argh, another condition, hidden away somewhere! I missed that one.
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
So what happens, then, when there is a failing upgrade? The new application revision is carried, in stealth, until it catches the failing version upgrade?
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
No, the caller only sets the change if there is not a version change present: https://github.com/vespa-engine/vespa/blob/master/controller-server/src/main/java/com/yahoo/vespa/hosted/controller/deployment/DeploymentTrigger.java#L87
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
Make `BouncyCastleProvider` a static/instance field. It might be considerable expensive to create.
X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, String remoteHostname) { assertCertificateCommonName(certReq.getSubject(), remoteHostname); assertCertificateExtensions(certReq); Date notBefore = Date.from(clock.instant()); Date notAfter = Date.from(clock.instant().plus(CERTIIFICATE_DURATION)); try { PublicKey publicKey = new JcaPKCS10CertificationRequest(certReq).getPublicKey(); X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder( issuer, BigInteger.valueOf(clock.millis()), notBefore, notAfter, certReq.getSubject(), publicKey) .addExtension(Extension.basicConstraints, false, new BasicConstraints(false)); ContentSigner caSigner = new JcaContentSignerBuilder(SIGNER_ALGORITHM).build(caPrivateKey); return new JcaX509CertificateConverter() .setProvider(new BouncyCastleProvider()) .getCertificate(caBuilder.build(caSigner)); } catch (Exception ex) { log.log(LogLevel.ERROR, "Failed to generate X509 Certificate", ex); throw new RuntimeException("Failed to generate X509 Certificate"); } }
.setProvider(new BouncyCastleProvider())
X509Certificate generateX509Certificate(PKCS10CertificationRequest certReq, String remoteHostname) { verifyCertificateCommonName(certReq.getSubject(), remoteHostname); verifyCertificateExtensions(certReq); Date notBefore = Date.from(clock.instant()); Date notAfter = Date.from(clock.instant().plus(CERTIFICATE_EXPIRATION)); try { PublicKey publicKey = new JcaPKCS10CertificationRequest(certReq).getPublicKey(); X509v3CertificateBuilder caBuilder = new JcaX509v3CertificateBuilder( issuer, BigInteger.valueOf(clock.millis()), notBefore, notAfter, certReq.getSubject(), publicKey) .addExtension(Extension.basicConstraints, true, new BasicConstraints(false)); ContentSigner caSigner = new JcaContentSignerBuilder(SIGNER_ALGORITHM).build(caPrivateKey); return certificateConverter .setProvider(provider) .getCertificate(caBuilder.build(caSigner)); } catch (Exception ex) { log.log(LogLevel.ERROR, "Failed to generate X509 Certificate", ex); throw new RuntimeException("Failed to generate X509 Certificate"); } }
class CertificateSigner { private static final Logger log = Logger.getLogger(CertificateSigner.class.getName()); static final String SIGNER_ALGORITHM = "SHA256withRSA"; private static final Duration CERTIIFICATE_DURATION = Duration.ofDays(30); private static final List<ASN1ObjectIdentifier> ILLEGAL_EXTENSIONS = Arrays.asList( Extension.basicConstraints, Extension.subjectAlternativeName); private final PrivateKey caPrivateKey; private final X500Name issuer; private final Clock clock; public CertificateSigner(KeyProvider keyProvider, AthenzProviderServiceConfig.Zones zoneConfig, String configServerHostname) { this(keyProvider.getPrivateKey(zoneConfig.secretVersion()), configServerHostname, Clock.systemUTC()); } CertificateSigner(PrivateKey caPrivateKey, String configServerHostname, Clock clock) { this.caPrivateKey = caPrivateKey; this.issuer = new X500Name("CN=" + configServerHostname); this.clock = clock; } static void assertCertificateCommonName(X500Name subject, String commonName) { List<AttributeTypeAndValue> attributesAndValues = Arrays.stream(subject.getRDNs()) .flatMap(rdn -> rdn.isMultiValued() ? Stream.of(rdn.getTypesAndValues()) : Stream.of(rdn.getFirst())) .filter(attr -> attr.getType() == BCStyle.CN) .collect(Collectors.toList()); if (attributesAndValues.size() != 1) { throw new IllegalArgumentException("Only 1 common name should be set"); } String actualCommonName = DERUTF8String.getInstance(attributesAndValues.get(0).getValue()).getString(); if (! actualCommonName.equals(commonName)) { throw new IllegalArgumentException("Expected common name to be " + commonName + ", but was " + actualCommonName); } } static void assertCertificateExtensions(PKCS10CertificationRequest request) { List<String> illegalExt = Arrays .stream(request.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) .map(attribute -> Extensions.getInstance(attribute.getAttrValues().getObjectAt(0))) .flatMap(ext -> Collections.list((Enumeration<ASN1ObjectIdentifier>) ext.oids()).stream()) .filter(ILLEGAL_EXTENSIONS::contains) .map(ASN1ObjectIdentifier::getId) .collect(Collectors.toList()); if (! illegalExt.isEmpty()) { throw new IllegalArgumentException("CSR contains illegal extensions: " + String.join(", ", illegalExt)); } } }
class CertificateSigner { private static final Logger log = Logger.getLogger(CertificateSigner.class.getName()); static final String SIGNER_ALGORITHM = "SHA256withRSA"; static final Duration CERTIFICATE_EXPIRATION = Duration.ofDays(30); private static final List<ASN1ObjectIdentifier> ILLEGAL_EXTENSIONS = ImmutableList.of( Extension.basicConstraints, Extension.subjectAlternativeName); private final JcaX509CertificateConverter certificateConverter = new JcaX509CertificateConverter(); private final Provider provider = new BouncyCastleProvider(); private final PrivateKey caPrivateKey; private final X500Name issuer; private final Clock clock; public CertificateSigner(KeyProvider keyProvider, AthenzProviderServiceConfig.Zones zoneConfig, String configServerHostname) { this(keyProvider.getPrivateKey(zoneConfig.secretVersion()), configServerHostname, Clock.systemUTC()); } CertificateSigner(PrivateKey caPrivateKey, String configServerHostname, Clock clock) { this.caPrivateKey = caPrivateKey; this.issuer = new X500Name("CN=" + configServerHostname); this.clock = clock; } /** * Signs the CSR if: * <ul> * <li>Common Name matches {@code remoteHostname}</li> * <li>CSR does not contain any any of the extensions in {@code ILLEGAL_EXTENSIONS}</li> * </ul> */ static void verifyCertificateCommonName(X500Name subject, String commonName) { List<AttributeTypeAndValue> attributesAndValues = Arrays.stream(subject.getRDNs()) .flatMap(rdn -> rdn.isMultiValued() ? Stream.of(rdn.getTypesAndValues()) : Stream.of(rdn.getFirst())) .filter(attr -> attr.getType() == BCStyle.CN) .collect(Collectors.toList()); if (attributesAndValues.size() != 1) { throw new IllegalArgumentException("Only 1 common name should be set"); } String actualCommonName = DERUTF8String.getInstance(attributesAndValues.get(0).getValue()).getString(); if (! actualCommonName.equals(commonName)) { throw new IllegalArgumentException("Expected common name to be " + commonName + ", but was " + actualCommonName); } } @SuppressWarnings("unchecked") static void verifyCertificateExtensions(PKCS10CertificationRequest request) { List<String> illegalExt = Arrays .stream(request.getAttributes(PKCSObjectIdentifiers.pkcs_9_at_extensionRequest)) .map(attribute -> Extensions.getInstance(attribute.getAttrValues().getObjectAt(0))) .flatMap(ext -> Collections.list((Enumeration<ASN1ObjectIdentifier>) ext.oids()).stream()) .filter(ILLEGAL_EXTENSIONS::contains) .map(ASN1ObjectIdentifier::getId) .collect(Collectors.toList()); if (! illegalExt.isEmpty()) { throw new IllegalArgumentException("CSR contains illegal extensions: " + String.join(", ", illegalExt)); } } }
This can't be removed, then.
public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } }
else {
public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
I thought this test was redundant, since we were only supposed to accept one kind of change at a time. We most certainly should change Change!
public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } }
else {
public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
Also, reinserting the condition I removed (which you posted above), made the test succeed without the extra pass.
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
public void testUpgrading() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application conservative0 = tester.createAndDeploy("conservative0", 6, "conservative"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(canary0, version, "canary", DeploymentJobs.JobType.stagingTest); assertEquals("Other Canary was cancelled", 2, tester.buildSystem().jobs().size()); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Version broken, but Canaries should keep trying", 2, tester.buildSystem().jobs().size()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); tester.clock().advance(Duration.ofHours(1)); tester.deployAndNotify(canary0, DeploymentTester.applicationPackage("canary"), false, DeploymentJobs.JobType.stagingTest); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, canary1, false); version = Version.fromString("5.3"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 3, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.updateVersionStatus(version); assertEquals("Not enough evidence to mark this as neither broken nor high", VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrade with error should retry", 1, tester.buildSystem().jobs().size()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, default0, false); tester.deployCompletely("default0"); tester.upgrader().maintain(); tester.deployCompletely("default0"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Normals done: Should upgrade conservatives", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(conservative0, version, "conservative"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("Applications are on 5.3 - nothing to do", 0, tester.buildSystem().jobs().size()); Version version54 = Version.fromString("5.4"); Application default3 = tester.createAndDeploy("default3", 5, "default"); Application default4 = tester.createAndDeploy("default4", 5, "default"); tester.updateVersionStatus(version54); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version54, "canary"); tester.completeUpgrade(canary1, version54, "canary"); tester.updateVersionStatus(version54); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version54, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default0, version54, "default"); Version version55 = Version.fromString("5.5"); tester.updateVersionStatus(version55); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version55, "canary"); tester.completeUpgrade(canary1, version55, "canary"); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled", 5, tester.buildSystem().jobs().size()); assertEquals(version55, ((Change.VersionChange)tester.application(default0.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default1.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default2.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version()); assertEquals(version54, ((Change.VersionChange)tester.application(default4.id()).deploying().get()).version()); tester.completeUpgrade(default1, version54, "default"); tester.completeUpgrade(default2, version54, "default"); tester.completeUpgradeWithError(default3, version54, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default4, version54, "default", DeploymentJobs.JobType.productionUsWest1); tester.upgrader().maintain(); tester.completeUpgradeWithError(default0, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default1, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default2, version55, "default", DeploymentJobs.JobType.stagingTest); tester.completeUpgradeWithError(default3, version55, "default", DeploymentJobs.JobType.productionUsWest1); tester.updateVersionStatus(version55); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.productionUsWest1, default3, false); tester.upgrader().maintain(); assertEquals("Upgrade of defaults are scheduled on 5.4 instead, since 5.5 broken: " + "This is default3 since it failed upgrade on both 5.4 and 5.5", 1, tester.buildSystem().jobs().size()); assertEquals("5.4", ((Change.VersionChange)tester.application(default3.id()).deploying().get()).version().toString()); }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
class UpgraderTest { @Test @Test public void testUpgradingToVersionWhichBreaksSomeNonCanaries() { DeploymentTester tester = new DeploymentTester(); tester.upgrader().maintain(); assertEquals("No system version: Nothing to do", 0, tester.buildSystem().jobs().size()); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("No applications: Nothing to do", 0, tester.buildSystem().jobs().size()); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); Application default5 = tester.createAndDeploy("default5", 8, "default"); Application default6 = tester.createAndDeploy("default6", 9, "default"); Application default7 = tester.createAndDeploy("default7", 10, "default"); Application default8 = tester.createAndDeploy("default8", 11, "default"); Application default9 = tester.createAndDeploy("default9", 12, "default"); tester.upgrader().maintain(); assertEquals("All already on the right version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertEquals("New system version: Should upgrade Canaries", 2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); assertEquals(version, tester.configServer().lastPrepareVersion().get()); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals("One canary pending; nothing else", 1, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Canaries done: Should upgrade defaults", 10, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default4, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); assertEquals("Upgrades are cancelled", 0, tester.buildSystem().jobs().size()); } @Test public void testDeploymentAlreadyInProgressForUpgrade() { DeploymentTester tester = new DeploymentTester(); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .environment(Environment.prod) .region("us-east-3") .build(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application app = tester.createApplication("app1", "tenant1", 1, 11L); tester.notifyJobCompletion(DeploymentJobs.JobType.component, app, true); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); tester.upgrader().maintain(); assertEquals("Application is on expected version: Nothing to do", 0, tester.buildSystem().jobs().size()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, false, DeploymentJobs.JobType.stagingTest); tester.buildSystem().takeJobsToRun(); tester.clock().advance(Duration.ofMinutes(10)); tester.notifyJobCompletion(DeploymentJobs.JobType.stagingTest, app, false); assertTrue("Retries exhausted", tester.buildSystem().jobs().isEmpty()); assertTrue("Failure is recorded", tester.application(app.id()).deploymentJobs().hasFailures()); assertTrue("Application has pending change", tester.application(app.id()).deploying().isPresent()); version = Version.fromString("5.2"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); assertTrue("Application still has failures", tester.application(app.id()).deploymentJobs().hasFailures()); assertEquals(1, tester.buildSystem().jobs().size()); tester.buildSystem().takeJobsToRun(); tester.upgrader().maintain(); assertTrue("No more jobs triggered at this time", tester.buildSystem().jobs().isEmpty()); } @Test public void testUpgradeCancelledWithDeploymentInProgress() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertFalse("No change present", tester.applications().require(default4.id()).deploying().isPresent()); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default4, true); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testConfidenceIgnoresFailingApplicationChanges() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); tester.completeUpgrade(default4, version, "default"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.high, tester.controller().versionStatus().systemVersion().get().confidence()); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default2, true); tester.notifyJobCompletion(DeploymentJobs.JobType.component, default3, true); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); } @Test public void testBlockVersionChange() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T18:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .blockChange(false, true, "tue", "18-19", "UTC") .region("us-west-1") .build(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); tester.upgrader().maintain(); assertFalse("Job is scheduled", tester.buildSystem().jobs().isEmpty()); tester.completeUpgrade(app, version, "canary"); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } @Test public void testBlockVersionChangeHalfwayThough() { ManualClock clock = new ManualClock(Instant.parse("2017-09-26T17:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); assertTrue("No jobs scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofHours(1)); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } /** * Tests the scenario where a release is deployed to 2 of 3 production zones, then blocked, * followed by timeout of the upgrade and a new release. * In this case, the blocked production zone should not progress with upgrading to the previous version, * and should not upgrade to the new version until the other production zones have it * (expected behavior; both requirements are debatable). */ @Test public void testBlockVersionChangeHalfwayThoughThenNewVersion() { ManualClock clock = new ManualClock(Instant.parse("2017-09-29T16:00:00.00Z")); DeploymentTester tester = new DeploymentTester(new ControllerTester(clock)); BlockedChangeDeployer blockedChangeDeployer = new BlockedChangeDeployer(tester.controller(), Duration.ofHours(1), new JobControl(tester.controllerTester().curator())); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .upgradePolicy("canary") .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(); Application app = tester.createAndDeploy("app1", 1, applicationPackage); version = Version.fromString("5.1"); tester.updateVersionStatus(version); tester.upgrader().maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); clock.advance(Duration.ofHours(1)); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); assertTrue(tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); version = Version.fromString("5.2"); tester.updateVersionStatus(version); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); assertTrue("Nothing is scheduled", tester.buildSystem().jobs().isEmpty()); tester.clock().advance(Duration.ofDays(1)); tester.clock().advance(Duration.ofHours(17)); tester.upgrader().maintain(); blockedChangeDeployer.maintain(); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.systemTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.stagingTest); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsWest1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsCentral1); tester.deployAndNotify(app, applicationPackage, true, DeploymentJobs.JobType.productionUsEast3); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); for (Deployment deployment : tester.applications().require(app.id()).deployments().values()) assertEquals(version, deployment.version()); } @Test public void testReschedulesUpgradeAfterTimeout() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); ApplicationPackage applicationPackage = new ApplicationPackageBuilder() .environment(Environment.prod) .region("us-west-1") .build(); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application default4 = tester.createAndDeploy("default4", 7, "default"); assertEquals(version, default0.deployedVersion().get()); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); tester.upgrader().maintain(); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.clock().advance(Duration.ofMinutes(1)); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for remaining apps", 5, tester.buildSystem().jobs().size()); tester.completeUpgradeWithError(default0, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default1, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default2, version, "default", DeploymentJobs.JobType.systemTest); tester.completeUpgradeWithError(default3, version, "default", DeploymentJobs.JobType.systemTest); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.broken, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); tester.clock().advance(Duration.ofHours(1)); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default0, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default1, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default2, false); tester.notifyJobCompletion(DeploymentJobs.JobType.systemTest, default3, false); Application deadLocked = tester.applications().require(default4.id()); assertTrue("Jobs in progress", deadLocked.deploymentJobs().isRunning(tester.controller().applications().deploymentTrigger().jobTimeoutLimit())); assertFalse("No change present", deadLocked.deploying().isPresent()); tester.deployCompletely(default0, applicationPackage); tester.deployCompletely(default1, applicationPackage); tester.deployCompletely(default2, applicationPackage); tester.deployCompletely(default3, applicationPackage); tester.updateVersionStatus(version); assertEquals(VespaVersion.Confidence.normal, tester.controller().versionStatus().systemVersion().get().confidence()); tester.upgrader().maintain(); assertEquals("Upgrade scheduled for previously failing apps", 4, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default2, version, "default"); tester.completeUpgrade(default3, version, "default"); assertEquals(version, tester.application(default0.id()).deployedVersion().get()); assertEquals(version, tester.application(default1.id()).deployedVersion().get()); assertEquals(version, tester.application(default2.id()).deployedVersion().get()); assertEquals(version, tester.application(default3.id()).deployedVersion().get()); } @Test public void testThrottlesUpgrades() { DeploymentTester tester = new DeploymentTester(); Version version = Version.fromString("5.0"); tester.updateVersionStatus(version); Upgrader upgrader = new Upgrader(tester.controller(), Duration.ofMinutes(10), new JobControl(tester.controllerTester().curator()), tester.controllerTester().curator()); upgrader.setUpgradesPerMinute(0.2); Application canary0 = tester.createAndDeploy("canary0", 1, "canary"); Application canary1 = tester.createAndDeploy("canary1", 2, "canary"); Application default0 = tester.createAndDeploy("default0", 3, "default"); Application default1 = tester.createAndDeploy("default1", 4, "default"); Application default2 = tester.createAndDeploy("default2", 5, "default"); Application default3 = tester.createAndDeploy("default3", 6, "default"); Application dev0 = tester.createApplication("dev0", "tenant1", 7, 1L); tester.controllerTester().deploy(dev0, new Zone(Environment.dev, RegionName.from("dev-region"))); version = Version.fromString("5.1"); tester.updateVersionStatus(version); assertEquals(version, tester.controller().versionStatus().systemVersion().get().versionNumber()); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(canary0, version, "canary"); tester.completeUpgrade(canary1, version, "canary"); tester.updateVersionStatus(version); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default0, version, "default"); tester.completeUpgrade(default2, version, "default"); upgrader.maintain(); assertEquals(2, tester.buildSystem().jobs().size()); tester.completeUpgrade(default1, version, "default"); tester.completeUpgrade(default3, version, "default"); upgrader.maintain(); assertTrue("All jobs consumed", tester.buildSystem().jobs().isEmpty()); } }
You mean like we do in the next test, `testMacroGeneration`?
public void testImportingFromStoredExpressionsWithSmallConstants() throws IOException { final String expression = "join(reduce(join(join(join(constant(\"dnn_hidden2_Const\"), tf_macro_dnn_hidden2_add, f(a,b)(a * b)), tf_macro_dnn_hidden2_add, f(a,b)(max(a,b))), constant(\"dnn_outputs_weights_read\"), f(a,b)(a * b)), sum, d2), constant(\"dnn_outputs_bias_read\"), f(a,b)(a + b))"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir); RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist/saved')", null, null, "input", application); search.assertFirstPhaseExpression(expression, "my_profile"); assertSmallConstant("dnn_hidden2_Const", TensorType.fromSpec("tensor(d0[1])"), search); Path storedApplicationDirectory = applicationDir.getParentPath().append("copy"); try { storedApplicationDirectory.toFile().mkdirs(); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); StoringApplicationPackage storedApplication = new StoringApplicationPackage(storedApplicationDirectory); RankProfileSearchFixture searchFromStored = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist/saved')", null, null, "input", storedApplication); searchFromStored.assertFirstPhaseExpression(expression, "my_profile"); assertSmallConstant("dnn_hidden2_Const", TensorType.fromSpec("tensor(d0[1])"), search); } finally { IOUtils.recursiveDeleteDir(storedApplicationDirectory.toFile()); } }
}
public void testImportingFromStoredExpressionsWithSmallConstants() throws IOException { final String expression = "join(reduce(join(join(join(constant(\"dnn_hidden2_Const\"), tf_macro_dnn_hidden2_add, f(a,b)(a * b)), tf_macro_dnn_hidden2_add, f(a,b)(max(a,b))), constant(\"dnn_outputs_weights_read\"), f(a,b)(a * b)), sum, d2), constant(\"dnn_outputs_bias_read\"), f(a,b)(a + b))"; final String macroExpression1 = "join(reduce(join(rename(input, (d0, d1), (d0, d4)), constant(\"dnn_hidden1_weights_read\"), f(a,b)(a * b)), sum, d4), constant(\"dnn_hidden1_bias_read\"), f(a,b)(a + b))"; final String macroExpression2 = "join(reduce(join(join(join(0.009999999776482582, tf_macro_dnn_hidden1_add, f(a,b)(a * b)), tf_macro_dnn_hidden1_add, f(a,b)(max(a,b))), constant(\"dnn_hidden2_weights_read\"), f(a,b)(a * b)), sum, d3), constant(\"dnn_hidden2_bias_read\"), f(a,b)(a + b))"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir); RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist/saved')", null, null, "input", application); search.assertFirstPhaseExpression(expression, "my_profile"); assertSmallConstant("dnn_hidden2_Const", TensorType.fromSpec("tensor(d0[1])"), search); search.assertMacro(macroExpression1, "tf_macro_dnn_hidden1_add", "my_profile"); search.assertMacro(macroExpression2, "tf_macro_dnn_hidden2_add", "my_profile"); Path storedApplicationDirectory = applicationDir.getParentPath().append("copy"); try { storedApplicationDirectory.toFile().mkdirs(); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); StoringApplicationPackage storedApplication = new StoringApplicationPackage(storedApplicationDirectory); RankProfileSearchFixture searchFromStored = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist/saved')", null, null, "input", storedApplication); searchFromStored.assertFirstPhaseExpression(expression, "my_profile"); assertSmallConstant("dnn_hidden2_Const", TensorType.fromSpec("tensor(d0[1])"), search); searchFromStored.assertMacro(macroExpression1, "tf_macro_dnn_hidden1_add", "my_profile"); searchFromStored.assertMacro(macroExpression2, "tf_macro_dnn_hidden2_add", "my_profile"); } finally { IOUtils.recursiveDeleteDir(storedApplicationDirectory.toFile()); } }
class RankingExpressionWithTensorFlowTestCase { private final Path applicationDir = Path.fromString("src/test/integration/tensorflow/"); private final String vespaExpression = "join(reduce(join(rename(Placeholder, (d0, d1), (d0, d2)), constant(\"layer_Variable_read\"), f(a,b)(a * b)), sum, d2), constant(\"layer_Variable_1_read\"), f(a,b)(a + b))"; @After public void removeGeneratedConstantTensorFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test public void testTensorFlowReference() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithConstantFeature() { RankProfileSearchFixture search = fixtureWith("constant(mytensor)", "tensorflow('mnist_softmax/saved')", "constant mytensor { file: ignored\ntype: tensor(d0[7],d1[784]) }", null); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithQueryFeature() { String queryProfile = "<query-profile id='default' type='root'/>"; String queryProfileType = "<query-profile-type id='root'>" + " <field name='query(mytensor)' type='tensor(d0[3],d1[784])'/>" + "</query-profile-type>"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType); RankProfileSearchFixture search = fixtureWith("query(mytensor)", "tensorflow('mnist_softmax/saved')", null, null, "Placeholder", application); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithDocumentFeature() { StoringApplicationPackage application = new StoringApplicationPackage(applicationDir); RankProfileSearchFixture search = fixtureWith("attribute(mytensor)", "tensorflow('mnist_softmax/saved')", null, "field mytensor type tensor(d0[],d1[784]) { indexing: attribute }", "Placeholder", application); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithFeatureCombination() { String queryProfile = "<query-profile id='default' type='root'/>"; String queryProfileType = "<query-profile-type id='root'>" + " <field name='query(mytensor)' type='tensor(d0[3],d1[784],d2[10])'/>" + "</query-profile-type>"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType); RankProfileSearchFixture search = fixtureWith("sum(query(mytensor) * attribute(mytensor) * constant(mytensor),d2)", "tensorflow('mnist_softmax/saved')", "constant mytensor { file: ignored\ntype: tensor(d0[7],d1[784]) }", "field mytensor type tensor(d0[],d1[784]) { indexing: attribute }", "Placeholder", application); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testNestedTensorFlowReference() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "5 + sum(tensorflow('mnist_softmax/saved'))"); search.assertFirstPhaseExpression("5 + reduce(" + vespaExpression + ", sum)", "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceSpecifyingSignature() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_default')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test public void testTensorFlowReferenceSpecifyingSignatureAndOutput() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_default', 'y')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test public void testTensorFlowReferenceMissingMacro() throws ParseException { try { RankProfileSearchFixture search = new RankProfileSearchFixture( new StoringApplicationPackage(applicationDir), new QueryProfileRegistry(), " rank-profile my_profile {\n" + " first-phase {\n" + " expression: tensorflow('mnist_softmax/saved')" + " }\n" + " }"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved'): " + "Model refers Placeholder 'Placeholder' of type tensor(d0[],d1[784]) but this macro is " + "not present in rank profile 'my_profile'", Exceptions.toMessageString(expected)); } } @Test public void testTensorFlowReferenceWithWrongMacroType() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d5[10])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved'): " + "Model refers Placeholder 'Placeholder' of type tensor(d0[],d1[784]) which must be produced " + "by a macro in the rank profile, but this macro produces type tensor(d0[2],d5[10])", Exceptions.toMessageString(expected)); } } @Test public void testTensorFlowReferenceSpecifyingNonExistingSignature() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_defaultz')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved','serving_defaultz'): " + "Model does not have the specified signature 'serving_defaultz'", Exceptions.toMessageString(expected)); } } @Test public void testTensorFlowReferenceSpecifyingNonExistingOutput() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_default', 'x')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved','serving_default','x'): " + "Model does not have the specified output 'x'", Exceptions.toMessageString(expected)); } } @Test public void testImportingFromStoredExpressions() throws IOException { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); Path storedApplicationDirectory = applicationDir.getParentPath().append("copy"); try { storedApplicationDirectory.toFile().mkdirs(); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); StoringApplicationPackage storedApplication = new StoringApplicationPackage(storedApplicationDirectory); RankProfileSearchFixture searchFromStored = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')", null, null, "Placeholder", storedApplication); searchFromStored.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", searchFromStored, Optional.empty()); assertLargeConstant("layer_Variable_read", searchFromStored, Optional.empty()); } finally { IOUtils.recursiveDeleteDir(storedApplicationDirectory.toFile()); } } @Test public void testTensorFlowReduceBatchDimension() { final String expression = "join(join(reduce(join(reduce(rename(Placeholder, (d0, d1), (d0, d2)), sum, d0), constant(\"layer_Variable_read\"), f(a,b)(a * b)), sum, d2), constant(\"layer_Variable_1_read\"), f(a,b)(a + b)), tensor(d0[1])(1.0), f(a,b)(a * b))"; RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(expression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test @Test public void testMacroGeneration() { final String expression = "join(reduce(join(join(join(constant(\"dnn_hidden2_Const\"), tf_macro_dnn_hidden2_add, f(a,b)(a * b)), tf_macro_dnn_hidden2_add, f(a,b)(max(a,b))), constant(\"dnn_outputs_weights_read\"), f(a,b)(a * b)), sum, d2), constant(\"dnn_outputs_bias_read\"), f(a,b)(a + b))"; final String macroExpression1 = "join(reduce(join(rename(input, (d0, d1), (d0, d4)), constant(\"dnn_hidden1_weights_read\"), f(a,b)(a * b)), sum, d4), constant(\"dnn_hidden1_bias_read\"), f(a,b)(a + b))"; final String macroExpression2 = "join(reduce(join(join(join(0.009999999776482582, tf_macro_dnn_hidden1_add, f(a,b)(a * b)), tf_macro_dnn_hidden1_add, f(a,b)(max(a,b))), constant(\"dnn_hidden2_weights_read\"), f(a,b)(a * b)), sum, d3), constant(\"dnn_hidden2_bias_read\"), f(a,b)(a + b))"; RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist/saved')"); search.assertFirstPhaseExpression(expression, "my_profile"); search.assertMacro(macroExpression1, "tf_macro_dnn_hidden1_add", "my_profile"); search.assertMacro(macroExpression2, "tf_macro_dnn_hidden2_add", "my_profile"); } private void assertSmallConstant(String name, TensorType type, RankProfileSearchFixture search) { Value value = search.rankProfile("my_profile").getConstants().get(name); assertNotNull(value); assertEquals(type, value.type()); } /** * Verifies that the constant with the given name exists, and - only if an expected size is given - * that the content of the constant is available and has the expected size. */ private void assertLargeConstant(String name, RankProfileSearchFixture search, Optional<Long> expectedSize) { try { Path constantApplicationPackagePath = Path.fromString("models.generated/mnist_softmax/saved/constants").append(name + ".tbf"); RankingConstant rankingConstant = search.search().getRankingConstants().get(name); assertEquals(name, rankingConstant.getName()); assertTrue(rankingConstant.getFileName().endsWith(constantApplicationPackagePath.toString())); if (expectedSize.isPresent()) { Path constantPath = applicationDir.append(constantApplicationPackagePath); assertTrue("Constant file '" + constantPath + "' has been written", constantPath.toFile().exists()); Tensor deserializedConstant = TypedBinaryFormat.decode(Optional.empty(), GrowableByteBuffer.wrap(IOUtils.readFileBytes(constantPath.toFile()))); assertEquals(expectedSize.get().longValue(), deserializedConstant.size()); } } catch (IOException e) { throw new UncheckedIOException(e); } } private RankProfileSearchFixture fixtureWith(String placeholderExpression, String firstPhaseExpression) { return fixtureWith(placeholderExpression, firstPhaseExpression, null, null, "Placeholder", new StoringApplicationPackage(applicationDir)); } private RankProfileSearchFixture fixtureWith(String placeholderExpression, String firstPhaseExpression, String constant, String field) { return fixtureWith(placeholderExpression, firstPhaseExpression, constant, field, "Placeholder", new StoringApplicationPackage(applicationDir)); } private RankProfileSearchFixture fixtureWith(String macroExpression, String firstPhaseExpression, String constant, String field, String macroName, StoringApplicationPackage application) { try { return new RankProfileSearchFixture( application, application.getQueryProfiles(), " rank-profile my_profile {\n" + " macro " + macroName + "() {\n" + " expression: " + macroExpression + " }\n" + " first-phase {\n" + " expression: " + firstPhaseExpression + " }\n" + " }", constant, field); } catch (ParseException e) { throw new IllegalArgumentException(e); } } private static class StoringApplicationPackage extends MockApplicationPackage { private final File root; StoringApplicationPackage(Path applicationPackageWritableRoot) { this(applicationPackageWritableRoot, null, null); } StoringApplicationPackage(Path applicationPackageWritableRoot, String queryProfile, String queryProfileType) { super(null, null, Collections.emptyList(), null, null, null, false, queryProfile, queryProfileType); this.root = new File(applicationPackageWritableRoot.toString()); } @Override public File getFileReference(Path path) { return Path.fromString(root.toString()).append(path).toFile(); } @Override public ApplicationFile getFile(Path file) { return new StoringApplicationPackageFile(file, Path.fromString(root.toString())); } } private static class StoringApplicationPackageFile extends ApplicationFile { /** The path to the application package root */ private final Path root; /** The File pointing to the actual file represented by this */ private final File file; StoringApplicationPackageFile(Path filePath, Path applicationPackagePath) { super(filePath); this.root = applicationPackagePath; file = applicationPackagePath.append(filePath).toFile(); } @Override public boolean isDirectory() { return file.isDirectory(); } @Override public boolean exists() { return file.exists(); } @Override public Reader createReader() throws FileNotFoundException { try { if ( ! exists()) throw new FileNotFoundException("File '" + file + "' does not exist"); return IOUtils.createReader(file, "UTF-8"); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public InputStream createInputStream() throws FileNotFoundException { try { if ( ! exists()) throw new FileNotFoundException("File '" + file + "' does not exist"); return new BufferedInputStream(new FileInputStream(file)); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public ApplicationFile createDirectory() { file.mkdirs(); return this; } @Override public ApplicationFile writeFile(Reader input) { try { IOUtils.writeFile(file, IOUtils.readAll(input), false); return this; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public ApplicationFile appendFile(String value) { try { IOUtils.writeFile(file, value, true); return this; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public List<ApplicationFile> listFiles(PathFilter filter) { if ( ! isDirectory()) return Collections.emptyList(); return Arrays.stream(file.listFiles()).filter(f -> filter.accept(Path.fromString(f.toString()))) .map(f -> new StoringApplicationPackageFile(asApplicationRelativePath(f), root)) .collect(Collectors.toList()); } @Override public ApplicationFile delete() { file.delete(); return this; } @Override public MetaData getMetaData() { throw new UnsupportedOperationException(); } @Override public int compareTo(ApplicationFile other) { return this.getPath().getName().compareTo((other).getPath().getName()); } /** Strips the application package root path prefix from the path of the given file */ private Path asApplicationRelativePath(File file) { Path path = Path.fromString(file.toString()); Iterator<String> pathIterator = path.iterator(); for (Iterator<String> rootIterator = root.iterator(); rootIterator.hasNext(); ) { String rootElement = rootIterator.next(); String pathElement = pathIterator.next(); if ( ! rootElement.equals(pathElement)) throw new RuntimeException("Assumption broken"); } Path relative = Path.fromString(""); while (pathIterator.hasNext()) relative = relative.append(pathIterator.next()); return relative; } } }
class RankingExpressionWithTensorFlowTestCase { private final Path applicationDir = Path.fromString("src/test/integration/tensorflow/"); private final String vespaExpression = "join(reduce(join(rename(Placeholder, (d0, d1), (d0, d2)), constant(\"layer_Variable_read\"), f(a,b)(a * b)), sum, d2), constant(\"layer_Variable_1_read\"), f(a,b)(a + b))"; @After public void removeGeneratedConstantTensorFiles() { IOUtils.recursiveDeleteDir(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); } @Test public void testTensorFlowReference() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithConstantFeature() { RankProfileSearchFixture search = fixtureWith("constant(mytensor)", "tensorflow('mnist_softmax/saved')", "constant mytensor { file: ignored\ntype: tensor(d0[7],d1[784]) }", null); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithQueryFeature() { String queryProfile = "<query-profile id='default' type='root'/>"; String queryProfileType = "<query-profile-type id='root'>" + " <field name='query(mytensor)' type='tensor(d0[3],d1[784])'/>" + "</query-profile-type>"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType); RankProfileSearchFixture search = fixtureWith("query(mytensor)", "tensorflow('mnist_softmax/saved')", null, null, "Placeholder", application); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithDocumentFeature() { StoringApplicationPackage application = new StoringApplicationPackage(applicationDir); RankProfileSearchFixture search = fixtureWith("attribute(mytensor)", "tensorflow('mnist_softmax/saved')", null, "field mytensor type tensor(d0[],d1[784]) { indexing: attribute }", "Placeholder", application); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceWithFeatureCombination() { String queryProfile = "<query-profile id='default' type='root'/>"; String queryProfileType = "<query-profile-type id='root'>" + " <field name='query(mytensor)' type='tensor(d0[3],d1[784],d2[10])'/>" + "</query-profile-type>"; StoringApplicationPackage application = new StoringApplicationPackage(applicationDir, queryProfile, queryProfileType); RankProfileSearchFixture search = fixtureWith("sum(query(mytensor) * attribute(mytensor) * constant(mytensor),d2)", "tensorflow('mnist_softmax/saved')", "constant mytensor { file: ignored\ntype: tensor(d0[7],d1[784]) }", "field mytensor type tensor(d0[],d1[784]) { indexing: attribute }", "Placeholder", application); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testNestedTensorFlowReference() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "5 + sum(tensorflow('mnist_softmax/saved'))"); search.assertFirstPhaseExpression("5 + reduce(" + vespaExpression + ", sum)", "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testTensorFlowReferenceSpecifyingSignature() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_default')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test public void testTensorFlowReferenceSpecifyingSignatureAndOutput() { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_default', 'y')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); } @Test public void testTensorFlowReferenceMissingMacro() throws ParseException { try { RankProfileSearchFixture search = new RankProfileSearchFixture( new StoringApplicationPackage(applicationDir), new QueryProfileRegistry(), " rank-profile my_profile {\n" + " first-phase {\n" + " expression: tensorflow('mnist_softmax/saved')" + " }\n" + " }"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved'): " + "Model refers Placeholder 'Placeholder' of type tensor(d0[],d1[784]) but this macro is " + "not present in rank profile 'my_profile'", Exceptions.toMessageString(expected)); } } @Test public void testTensorFlowReferenceWithWrongMacroType() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d5[10])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved'): " + "Model refers Placeholder 'Placeholder' of type tensor(d0[],d1[784]) which must be produced " + "by a macro in the rank profile, but this macro produces type tensor(d0[2],d5[10])", Exceptions.toMessageString(expected)); } } @Test public void testTensorFlowReferenceSpecifyingNonExistingSignature() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_defaultz')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved','serving_defaultz'): " + "Model does not have the specified signature 'serving_defaultz'", Exceptions.toMessageString(expected)); } } @Test public void testTensorFlowReferenceSpecifyingNonExistingOutput() { try { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved', 'serving_default', 'x')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); fail("Expecting exception"); } catch (IllegalArgumentException expected) { assertEquals("Rank profile 'my_profile' is invalid: Could not use tensorflow model from " + "tensorflow('mnist_softmax/saved','serving_default','x'): " + "Model does not have the specified output 'x'", Exceptions.toMessageString(expected)); } } @Test public void testImportingFromStoredExpressions() throws IOException { RankProfileSearchFixture search = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); Path storedApplicationDirectory = applicationDir.getParentPath().append("copy"); try { storedApplicationDirectory.toFile().mkdirs(); IOUtils.copyDirectory(applicationDir.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile(), storedApplicationDirectory.append(ApplicationPackage.MODELS_GENERATED_DIR).toFile()); StoringApplicationPackage storedApplication = new StoringApplicationPackage(storedApplicationDirectory); RankProfileSearchFixture searchFromStored = fixtureWith("tensor(d0[2],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')", null, null, "Placeholder", storedApplication); searchFromStored.assertFirstPhaseExpression(vespaExpression, "my_profile"); assertLargeConstant("layer_Variable_1_read", searchFromStored, Optional.empty()); assertLargeConstant("layer_Variable_read", searchFromStored, Optional.empty()); } finally { IOUtils.recursiveDeleteDir(storedApplicationDirectory.toFile()); } } @Test public void testTensorFlowReduceBatchDimension() { final String expression = "join(join(reduce(join(reduce(rename(Placeholder, (d0, d1), (d0, d2)), sum, d0), constant(\"layer_Variable_read\"), f(a,b)(a * b)), sum, d2), constant(\"layer_Variable_1_read\"), f(a,b)(a + b)), tensor(d0[1])(1.0), f(a,b)(a * b))"; RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist_softmax/saved')"); search.assertFirstPhaseExpression(expression, "my_profile"); assertLargeConstant("layer_Variable_1_read", search, Optional.of(10L)); assertLargeConstant("layer_Variable_read", search, Optional.of(7840L)); } @Test public void testMacroGeneration() { final String expression = "join(reduce(join(join(join(constant(\"dnn_hidden2_Const\"), tf_macro_dnn_hidden2_add, f(a,b)(a * b)), tf_macro_dnn_hidden2_add, f(a,b)(max(a,b))), constant(\"dnn_outputs_weights_read\"), f(a,b)(a * b)), sum, d2), constant(\"dnn_outputs_bias_read\"), f(a,b)(a + b))"; final String macroExpression1 = "join(reduce(join(rename(input, (d0, d1), (d0, d4)), constant(\"dnn_hidden1_weights_read\"), f(a,b)(a * b)), sum, d4), constant(\"dnn_hidden1_bias_read\"), f(a,b)(a + b))"; final String macroExpression2 = "join(reduce(join(join(join(0.009999999776482582, tf_macro_dnn_hidden1_add, f(a,b)(a * b)), tf_macro_dnn_hidden1_add, f(a,b)(max(a,b))), constant(\"dnn_hidden2_weights_read\"), f(a,b)(a * b)), sum, d3), constant(\"dnn_hidden2_bias_read\"), f(a,b)(a + b))"; RankProfileSearchFixture search = fixtureWith("tensor(d0[1],d1[784])(0.0)", "tensorflow('mnist/saved')"); search.assertFirstPhaseExpression(expression, "my_profile"); search.assertMacro(macroExpression1, "tf_macro_dnn_hidden1_add", "my_profile"); search.assertMacro(macroExpression2, "tf_macro_dnn_hidden2_add", "my_profile"); } @Test private void assertSmallConstant(String name, TensorType type, RankProfileSearchFixture search) { Value value = search.rankProfile("my_profile").getConstants().get(name); assertNotNull(value); assertEquals(type, value.type()); } /** * Verifies that the constant with the given name exists, and - only if an expected size is given - * that the content of the constant is available and has the expected size. */ private void assertLargeConstant(String name, RankProfileSearchFixture search, Optional<Long> expectedSize) { try { Path constantApplicationPackagePath = Path.fromString("models.generated/mnist_softmax/saved/constants").append(name + ".tbf"); RankingConstant rankingConstant = search.search().getRankingConstants().get(name); assertEquals(name, rankingConstant.getName()); assertTrue(rankingConstant.getFileName().endsWith(constantApplicationPackagePath.toString())); if (expectedSize.isPresent()) { Path constantPath = applicationDir.append(constantApplicationPackagePath); assertTrue("Constant file '" + constantPath + "' has been written", constantPath.toFile().exists()); Tensor deserializedConstant = TypedBinaryFormat.decode(Optional.empty(), GrowableByteBuffer.wrap(IOUtils.readFileBytes(constantPath.toFile()))); assertEquals(expectedSize.get().longValue(), deserializedConstant.size()); } } catch (IOException e) { throw new UncheckedIOException(e); } } private RankProfileSearchFixture fixtureWith(String placeholderExpression, String firstPhaseExpression) { return fixtureWith(placeholderExpression, firstPhaseExpression, null, null, "Placeholder", new StoringApplicationPackage(applicationDir)); } private RankProfileSearchFixture fixtureWith(String placeholderExpression, String firstPhaseExpression, String constant, String field) { return fixtureWith(placeholderExpression, firstPhaseExpression, constant, field, "Placeholder", new StoringApplicationPackage(applicationDir)); } private RankProfileSearchFixture fixtureWith(String macroExpression, String firstPhaseExpression, String constant, String field, String macroName, StoringApplicationPackage application) { try { return new RankProfileSearchFixture( application, application.getQueryProfiles(), " rank-profile my_profile {\n" + " macro " + macroName + "() {\n" + " expression: " + macroExpression + " }\n" + " first-phase {\n" + " expression: " + firstPhaseExpression + " }\n" + " }", constant, field); } catch (ParseException e) { throw new IllegalArgumentException(e); } } private static class StoringApplicationPackage extends MockApplicationPackage { private final File root; StoringApplicationPackage(Path applicationPackageWritableRoot) { this(applicationPackageWritableRoot, null, null); } StoringApplicationPackage(Path applicationPackageWritableRoot, String queryProfile, String queryProfileType) { super(null, null, Collections.emptyList(), null, null, null, false, queryProfile, queryProfileType); this.root = new File(applicationPackageWritableRoot.toString()); } @Override public File getFileReference(Path path) { return Path.fromString(root.toString()).append(path).toFile(); } @Override public ApplicationFile getFile(Path file) { return new StoringApplicationPackageFile(file, Path.fromString(root.toString())); } } private static class StoringApplicationPackageFile extends ApplicationFile { /** The path to the application package root */ private final Path root; /** The File pointing to the actual file represented by this */ private final File file; StoringApplicationPackageFile(Path filePath, Path applicationPackagePath) { super(filePath); this.root = applicationPackagePath; file = applicationPackagePath.append(filePath).toFile(); } @Override public boolean isDirectory() { return file.isDirectory(); } @Override public boolean exists() { return file.exists(); } @Override public Reader createReader() throws FileNotFoundException { try { if ( ! exists()) throw new FileNotFoundException("File '" + file + "' does not exist"); return IOUtils.createReader(file, "UTF-8"); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public InputStream createInputStream() throws FileNotFoundException { try { if ( ! exists()) throw new FileNotFoundException("File '" + file + "' does not exist"); return new BufferedInputStream(new FileInputStream(file)); } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public ApplicationFile createDirectory() { file.mkdirs(); return this; } @Override public ApplicationFile writeFile(Reader input) { try { IOUtils.writeFile(file, IOUtils.readAll(input), false); return this; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public ApplicationFile appendFile(String value) { try { IOUtils.writeFile(file, value, true); return this; } catch (IOException e) { throw new UncheckedIOException(e); } } @Override public List<ApplicationFile> listFiles(PathFilter filter) { if ( ! isDirectory()) return Collections.emptyList(); return Arrays.stream(file.listFiles()).filter(f -> filter.accept(Path.fromString(f.toString()))) .map(f -> new StoringApplicationPackageFile(asApplicationRelativePath(f), root)) .collect(Collectors.toList()); } @Override public ApplicationFile delete() { file.delete(); return this; } @Override public MetaData getMetaData() { throw new UnsupportedOperationException(); } @Override public int compareTo(ApplicationFile other) { return this.getPath().getName().compareTo((other).getPath().getName()); } /** Strips the application package root path prefix from the path of the given file */ private Path asApplicationRelativePath(File file) { Path path = Path.fromString(file.toString()); Iterator<String> pathIterator = path.iterator(); for (Iterator<String> rootIterator = root.iterator(); rootIterator.hasNext(); ) { String rootElement = rootIterator.next(); String pathElement = pathIterator.next(); if ( ! rootElement.equals(pathElement)) throw new RuntimeException("Assumption broken"); } Path relative = Path.fromString(""); while (pathIterator.hasNext()) relative = relative.append(pathIterator.next()); return relative; } } }
Yes, I found that, after @bratseth pointed it out.
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
private boolean acceptNewRevisionNow(LockedApplication application) { if ( ! application.deploying().isPresent()) return true; if ( application.deploying().get() instanceof Change.ApplicationChange) return true; if ( application.deploymentJobs().hasFailures()) return true; if ( application.isBlocked(clock.instant())) return true; return false; }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }
class DeploymentTrigger { /** The max duration a job may run before we consider it dead/hanging */ private final Duration jobTimeout; private final static Logger log = Logger.getLogger(DeploymentTrigger.class.getName()); private final Controller controller; private final Clock clock; private final BuildSystem buildSystem; private final DeploymentOrder order; public DeploymentTrigger(Controller controller, CuratorDb curator, Clock clock) { Objects.requireNonNull(controller,"controller cannot be null"); Objects.requireNonNull(curator,"curator cannot be null"); Objects.requireNonNull(clock,"clock cannot be null"); this.controller = controller; this.clock = clock; this.buildSystem = new PolledBuildSystem(controller, curator); this.order = new DeploymentOrder(controller); this.jobTimeout = controller.system().equals(SystemName.main) ? Duration.ofHours(12) : Duration.ofHours(1); } /** Returns the time in the past before which jobs are at this moment considered unresponsive */ public Instant jobTimeoutLimit() { return clock.instant().minus(jobTimeout); } /** * Called each time a job completes (successfully or not) to cause triggering of one or more follow-up jobs * (which may possibly the same job once over). * * @param report information about the job that just completed */ public void triggerFromCompletion(JobReport report) { try (Lock lock = applications().lock(report.applicationId())) { LockedApplication application = applications().require(report.applicationId(), lock); application = application.withJobCompletion(report, clock.instant(), controller); if (report.success()) { if (order.givesNewRevision(report.jobType())) { if (acceptNewRevisionNow(application)) { if ( ! ( application.deploying().isPresent() && (application.deploying().get() instanceof Change.VersionChange))) application = application.withDeploying(Optional.of(Change.ApplicationChange.unknown())); } else { applications().store(application.withOutstandingChange(true)); return; } } else if (order.isLast(report.jobType(), application) && application.deployingCompleted()) { application = application.withDeploying(Optional.empty()); } } if (report.success()) application = trigger(order.nextAfter(report.jobType(), application), application, report.jobType().jobName() + " completed"); else if (isCapacityConstrained(report.jobType()) && shouldRetryOnOutOfCapacity(application, report.jobType())) application = trigger(report.jobType(), application, true, "Retrying on out of capacity"); else if (shouldRetryNow(application)) application = trigger(report.jobType(), application, false, "Immediate retry on failure"); applications().store(application); } } /** * Find jobs that can and should run but are currently not. */ public void triggerReadyJobs() { ApplicationList applications = ApplicationList.from(applications().asList()); applications = applications.notPullRequest(); for (Application application : applications.asList()) { try (Lock lock = applications().lock(application.id())) { Optional<LockedApplication> lockedApplication = controller.applications().get(application.id(), lock); if ( ! lockedApplication.isPresent()) continue; triggerReadyJobs(lockedApplication.get()); } } } /** Find the next step to trigger if any, and triggers it */ private void triggerReadyJobs(LockedApplication application) { if ( ! application.deploying().isPresent()) return; List<JobType> jobs = order.jobsFrom(application.deploymentSpec()); if ( ! jobs.isEmpty() && jobs.get(0).equals(JobType.systemTest) && application.deploying().get() instanceof Change.VersionChange) { Version target = ((Change.VersionChange)application.deploying().get()).version(); JobStatus jobStatus = application.deploymentJobs().jobStatus().get(JobType.systemTest); if (jobStatus == null || ! jobStatus.lastTriggered().isPresent() || ! jobStatus.lastTriggered().get().version().equals(target)) { application = trigger(JobType.systemTest, application, false, "Upgrade to " + target); controller.applications().store(application); } } for (JobType jobType : jobs) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (jobStatus == null) continue; if (jobStatus.isRunning(jobTimeoutLimit())) continue; List<JobType> nextToTrigger = new ArrayList<>(); for (JobType nextJobType : order.nextAfter(jobType, application)) { JobStatus nextStatus = application.deploymentJobs().jobStatus().get(nextJobType); if (changesAvailable(application, jobStatus, nextStatus)) nextToTrigger.add(nextJobType); } application = trigger(nextToTrigger, application, "Available change in " + jobType.jobName()); controller.applications().store(application); } } /** * Returns true if the previous job has completed successfully with a revision and/or version which is * newer (different) than the one last completed successfully in next */ private boolean changesAvailable(Application application, JobStatus previous, JobStatus next) { if ( ! application.deploying().isPresent()) return false; Change change = application.deploying().get(); if ( ! previous.lastSuccess().isPresent() && ! productionJobHasSucceededFor(previous, change)) return false; if (change instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)change).version(); if ( ! (targetVersion.equals(previous.lastSuccess().get().version())) ) return false; if (isOnNewerVersionInProductionThan(targetVersion, application, next.type())) return false; } if (next == null) return true; if ( ! next.lastSuccess().isPresent()) return true; JobStatus.JobRun previousSuccess = previous.lastSuccess().get(); JobStatus.JobRun nextSuccess = next.lastSuccess().get(); if (previousSuccess.revision().isPresent() && ! previousSuccess.revision().get().equals(nextSuccess.revision().get())) return true; if ( ! previousSuccess.version().equals(nextSuccess.version())) return true; return false; } /** * Called periodically to cause triggering of jobs in the background */ public void triggerFailing(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if ( ! application.deploying().isPresent()) return; for (JobType jobType : order.jobsFrom(application.deploymentSpec())) { JobStatus jobStatus = application.deploymentJobs().jobStatus().get(jobType); if (isFailing(application.deploying().get(), jobStatus)) { if (shouldRetryNow(jobStatus)) { application = trigger(jobType, application, false, "Retrying failing job"); applications().store(application); } break; } } Optional<JobStatus> firstDeadJob = firstDeadJob(application.deploymentJobs()); if (firstDeadJob.isPresent()) { application = trigger(firstDeadJob.get().type(), application, false, "Retrying dead job"); applications().store(application); } } } /** Triggers jobs that have been delayed according to deployment spec */ public void triggerDelayed() { for (Application application : applications().asList()) { if ( ! application.deploying().isPresent() ) continue; if (application.deploymentJobs().hasFailures()) continue; if (application.deploymentJobs().isRunning(controller.applications().deploymentTrigger().jobTimeoutLimit())) continue; if (application.deploymentSpec().steps().stream().noneMatch(step -> step instanceof DeploymentSpec.Delay)) { continue; } Optional<JobStatus> lastSuccessfulJob = application.deploymentJobs().jobStatus().values() .stream() .filter(j -> j.lastSuccess().isPresent()) .sorted(Comparator.<JobStatus, Instant>comparing(j -> j.lastSuccess().get().at()).reversed()) .findFirst(); if ( ! lastSuccessfulJob.isPresent() ) continue; try (Lock lock = applications().lock(application.id())) { LockedApplication lockedApplication = applications().require(application.id(), lock); lockedApplication = trigger(order.nextAfter(lastSuccessfulJob.get().type(), lockedApplication), lockedApplication, "Resuming delayed deployment"); applications().store(lockedApplication); } } } /** * Triggers a change of this application * * @param applicationId the application to trigger * @throws IllegalArgumentException if this application already have an ongoing change */ public void triggerChange(ApplicationId applicationId, Change change) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); if (application.deploying().isPresent() && ! application.deploymentJobs().hasFailures()) throw new IllegalArgumentException("Could not start " + change + " on " + application + ": " + application.deploying().get() + " is already in progress"); application = application.withDeploying(Optional.of(change)); if (change instanceof Change.ApplicationChange) application = application.withOutstandingChange(false); application = trigger(JobType.systemTest, application, false, "Deploying " + change); applications().store(application); } } /** * Cancels any ongoing upgrade of the given application * * @param applicationId the application to trigger */ public void cancelChange(ApplicationId applicationId) { try (Lock lock = applications().lock(applicationId)) { LockedApplication application = applications().require(applicationId, lock); buildSystem.removeJobs(application.id()); application = application.withDeploying(Optional.empty()); applications().store(application); } } private ApplicationController applications() { return controller.applications(); } /** Returns whether a job is failing for the current change in the given application */ private boolean isFailing(Change change, JobStatus status) { return status != null && ! status.isSuccess() && status.lastCompleted().get().lastCompletedWas(change); } private boolean isCapacityConstrained(JobType jobType) { return jobType == JobType.stagingTest || jobType == JobType.systemTest; } /** Returns the first job that has been running for more than the given timeout */ private Optional<JobStatus> firstDeadJob(DeploymentJobs jobs) { Optional<JobStatus> oldestRunningJob = jobs.jobStatus().values().stream() .filter(job -> job.isRunning(Instant.ofEpochMilli(0))) .sorted(Comparator.comparing(status -> status.lastTriggered().get().at())) .findFirst(); return oldestRunningJob.filter(job -> job.lastTriggered().get().at().isBefore(jobTimeoutLimit())); } /** Decide whether the job should be triggered by the periodic trigger */ private boolean shouldRetryNow(JobStatus job) { if (job.isSuccess()) return false; if (job.isRunning(jobTimeoutLimit())) return false; Duration aTenthOfFailTime = Duration.ofMillis( (clock.millis() - job.firstFailing().get().at().toEpochMilli()) / 10); if (job.lastCompleted().get().at().isBefore(clock.instant().minus(aTenthOfFailTime))) return true; if (job.lastCompleted().get().at().isBefore(clock.instant().minus(Duration.ofHours(4)))) return true; return false; } /** Retry immediately only if this just started failing. Otherwise retry periodically */ private boolean shouldRetryNow(Application application) { return application.deploymentJobs().failingSince().isAfter(clock.instant().minus(Duration.ofSeconds(10))); } /** Decide whether to retry due to capacity restrictions */ private boolean shouldRetryOnOutOfCapacity(Application application, JobType jobType) { Optional<JobError> outOfCapacityError = Optional.ofNullable(application.deploymentJobs().jobStatus().get(jobType)) .flatMap(JobStatus::jobError) .filter(e -> e.equals(JobError.outOfCapacity)); if ( ! outOfCapacityError.isPresent()) return false; return application.deploymentJobs().jobStatus().get(jobType).firstFailing().get().at() .isAfter(clock.instant().minus(Duration.ofMinutes(15))); } /** Returns whether the given job type should be triggered according to deployment spec */ private boolean deploysTo(Application application, JobType jobType) { Optional<Zone> zone = jobType.zone(controller.system()); if (zone.isPresent() && jobType.isProduction()) { if ( ! application.deploymentSpec().includes(jobType.environment(), Optional.of(zone.get().region()))) { return false; } } return true; } /** * Trigger a job for an application * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param reason describes why the job is triggered * @return the application in the triggered state, which *must* be stored by the caller */ private LockedApplication trigger(JobType jobType, LockedApplication application, boolean first, String reason) { if (isRunningProductionJob(application)) return application; return triggerAllowParallel(jobType, application, first, false, reason); } private LockedApplication trigger(List<JobType> jobs, LockedApplication application, String reason) { if (isRunningProductionJob(application)) return application; for (JobType job : jobs) application = triggerAllowParallel(job, application, false, false, reason); return application; } /** * Trigger a job for an application, if allowed * * @param jobType the type of the job to trigger, or null to trigger nothing * @param application the application to trigger the job for * @param first whether to trigger the job before other jobs * @param force true to disable checks which should normally prevent this triggering from happening * @param reason describes why the job is triggered * @return the application in the triggered state, if actually triggered. This *must* be stored by the caller */ public LockedApplication triggerAllowParallel(JobType jobType, LockedApplication application, boolean first, boolean force, String reason) { if (jobType == null) return application; if ( ! application.deploymentJobs().isDeployableTo(jobType.environment(), application.deploying())) { log.warning(String.format("Want to trigger %s for %s with reason %s, but change is untested", jobType, application, reason)); return application; } if ( ! force && ! allowedTriggering(jobType, application)) return application; log.info(String.format("Triggering %s for %s, %s: %s", jobType, application, application.deploying().map(d -> "deploying " + d).orElse("restarted deployment"), reason)); buildSystem.addJob(application.id(), jobType, first); return application.withJobTriggering(-1, jobType, application.deploying(), reason, clock.instant(), controller); } /** Returns true if the given proposed job triggering should be effected */ private boolean allowedTriggering(JobType jobType, LockedApplication application) { if (jobType.isProduction() && application.deployingBlocked(clock.instant())) return false; if (application.deploymentJobs().isRunning(jobType, jobTimeoutLimit())) return false; if ( ! deploysTo(application, jobType)) return false; if ( ! application.deploymentJobs().projectId().isPresent()) return false; if (application.deploying().isPresent() && application.deploying().get() instanceof Change.VersionChange) { Version targetVersion = ((Change.VersionChange)application.deploying().get()).version(); if (isOnNewerVersionInProductionThan(targetVersion, application, jobType)) return false; } return true; } private boolean isRunningProductionJob(Application application) { return JobList.from(application) .production() .running(jobTimeoutLimit()) .anyMatch(); } /** * When upgrading it is ok to trigger the next job even if the previous failed if the previous has earlier succeeded * on the version we are currently upgrading to */ private boolean productionJobHasSucceededFor(JobStatus jobStatus, Change change) { if ( ! (change instanceof Change.VersionChange) ) return false; if ( ! isProduction(jobStatus.type())) return false; Optional<JobStatus.JobRun> lastSuccess = jobStatus.lastSuccess(); if ( ! lastSuccess.isPresent()) return false; return lastSuccess.get().version().equals(((Change.VersionChange)change).version()); } /** * Returns whether the current deployed version in the zone given by the job * is newer than the given version. This may be the case even if the production job * in question failed, if the failure happens after deployment. * In that case we should never deploy an earlier version as that may potentially * downgrade production nodes which we are not guaranteed to support. */ private boolean isOnNewerVersionInProductionThan(Version version, Application application, JobType job) { if ( ! isProduction(job)) return false; Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; Deployment existingDeployment = application.deployments().get(zone.get()); if (existingDeployment == null) return false; return existingDeployment.version().isAfter(version); } private boolean isProduction(JobType job) { Optional<Zone> zone = job.zone(controller.system()); if ( ! zone.isPresent()) return false; return zone.get().environment() == Environment.prod; } public BuildSystem buildSystem() { return buildSystem; } public DeploymentOrder deploymentOrder() { return order; } }