io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder Java Examples

The following examples show how to use io.fabric8.kubernetes.api.model.apps.StatefulSetBuilder. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a StatefulSet with PropagationPolicy=Background")
void testDeleteStatefulSet() throws InterruptedException {
  // Given
  server.expect().delete().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/mystatefulset")
    .andReturn(HttpURLConnection.HTTP_OK, new StatefulSetBuilder().build())
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.apps().statefulSets().inNamespace("ns1").withName("mystatefulset").delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.BACKGROUND.toString(), server.getLastRequest());
}
 
Example #2
Source File: StatefulSetTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testGet() {
 server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, new StatefulSetBuilder().build()).once();
 server.expect().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/repl2").andReturn(200, new StatefulSetBuilder().build()).once();

  KubernetesClient client = server.getClient();

  StatefulSet repl1 = client.apps().statefulSets().withName("repl1").get();
  assertNotNull(repl1);

  repl1 = client.apps().statefulSets().withName("repl2").get();
  assertNull(repl1);

  repl1 = client.apps().statefulSets().inNamespace("ns1").withName("repl2").get();
  assertNotNull(repl1);
}
 
Example #3
Source File: StatefulSetTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
public void testScale() {
 server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, new StatefulSetBuilder()
    .withNewMetadata()
    .withName("repl1")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(5)
    .endSpec()
    .withNewStatus()
      .withReplicas(1)
    .endStatus()
    .build()).always();

  KubernetesClient client = server.getClient();
  StatefulSet repl = client.apps().statefulSets().withName("repl1").scale(5);
  assertNotNull(repl);
  assertNotNull(repl.getSpec());
  assertEquals(5, repl.getSpec().getReplicas().intValue());
  assertEquals(1, repl.getStatus().getReplicas().intValue());
}
 
Example #4
Source File: StatefulSetOperatorTest.java    From strimzi-kafka-operator with Apache License 2.0 6 votes vote down vote up
@Override
protected StatefulSet resource() {
    return new StatefulSetBuilder()
            .withNewMetadata()
                .withNamespace(AbstractResourceOperatorTest.NAMESPACE)
                .withName(AbstractResourceOperatorTest.RESOURCE_NAME)
            .endMetadata()
            .withNewSpec()
                .withReplicas(3)
                .withNewTemplate()
                    .withNewMetadata()
                    .endMetadata()
                .endTemplate()
            .endSpec()
            .build();
}
 
Example #5
Source File: StatefulSetTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
private StatefulSetBuilder getStatefulSetBuilder() {
  return new StatefulSetBuilder()
    .withNewMetadata()
    .withName("statefulset1")
    .addToLabels("app", "nginx")
    .addToAnnotations("app", "nginx")
    .endMetadata()
    .withNewSpec()
    .withReplicas(1)
    .withNewSelector()
    .addToMatchLabels("app", "nginx")
    .endSelector()
    .withNewTemplate()
    .withNewMetadata().addToLabels("app", "nginx").endMetadata()
    .withNewSpec()
    .addNewContainer()
    .withName("nginx")
    .withImage("nginx:1.7.9")
    .addNewPort().withContainerPort(80).endPort()
    .endContainer()
    .endSpec()
    .endTemplate()
    .endSpec();
}
 
Example #6
Source File: PropagationPolicyTest.java    From kubernetes-client with Apache License 2.0 6 votes vote down vote up
@Test
@DisplayName("Should delete a StatefulSet with explicitly set PropagationPolicy")
void testDeleteStatefulSetWithExplicitPropagationPolicy() throws InterruptedException {
  // Given
  server.expect().delete().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/mystatefulset")
    .andReturn(HttpURLConnection.HTTP_OK, new StatefulSetBuilder().build())
    .once();
  KubernetesClient client = server.getClient();

  // When
  Boolean isDeleted = client.apps().statefulSets().inNamespace("ns1").withName("mystatefulset").withPropagationPolicy(DeletionPropagation.FOREGROUND).delete();

  // Then
  assertTrue(isDeleted);
  assertDeleteOptionsInLastRecordedRequest(DeletionPropagation.FOREGROUND.toString(), server.getLastRequest());
}
 
Example #7
Source File: ImageEnricherTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void checkEnrichStatefulSet() throws Exception {
    KubernetesListBuilder builder = new KubernetesListBuilder().addToItems(new StatefulSetBuilder().build());

    imageEnricher.create(PlatformMode.kubernetes, builder);
    assertCorrectlyGeneratedResources(builder.build(), "StatefulSet");
}
 
Example #8
Source File: StatefulSetRollingUpdater.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Override
protected StatefulSet createClone(StatefulSet obj, String newName, String newDeploymentHash) {
  return new StatefulSetBuilder(obj)
    .editMetadata()
    .withResourceVersion(null)
    .withName(newName)
    .endMetadata()
    .editSpec()
    .withReplicas(0)
    .editSelector().addToMatchLabels(DEPLOYMENT_KEY, newDeploymentHash).endSelector()
    .editTemplate().editMetadata().addToLabels(DEPLOYMENT_KEY, newDeploymentHash).endMetadata().endTemplate()
    .endSpec()
    .build();
}
 
Example #9
Source File: TriggersAnnotationEnricherTest.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
@Test
public void testStatefulSetEnrichment() throws IOException {

    KubernetesListBuilder builder = new KubernetesListBuilder()
            .addToItems(new StatefulSetBuilder()
                .withNewSpec()
                    .withNewTemplate()
                        .withNewSpec()
                            .withContainers(createContainers("c1", "is:latest"))
                        .endSpec()
                    .endTemplate()
                .endSpec()
                .build());


    TriggersAnnotationEnricher enricher = new TriggersAnnotationEnricher(context);
    enricher.enrich(PlatformMode.kubernetes, builder);


    StatefulSet res = (StatefulSet) builder.build().getItems().get(0);
    String triggers = res.getMetadata().getAnnotations().get("image.openshift.io/triggers");
    assertNotNull(triggers);

    List<ImageChangeTrigger> triggerList = OBJECT_MAPPER.readValue(triggers, OBJECT_MAPPER.getTypeFactory().constructCollectionType(List.class, ImageChangeTrigger.class));
    assertEquals(1, triggerList.size());

    ImageChangeTrigger trigger = triggerList.get(0);
    assertEquals("ImageStreamTag", trigger.getFrom().getKind());
    assertEquals("is:latest", trigger.getFrom().getName());
    assertTrue(trigger.getAdditionalProperties().containsKey("fieldPath"));

}
 
Example #10
Source File: ImageEnricher.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
private void ensureTemplateSpecsInStatefulSet(KubernetesListBuilder builder) {
    builder.accept(new TypedVisitor<StatefulSetBuilder>() {
        @Override
        public void visit(StatefulSetBuilder item) {
            StatefulSetFluent.SpecNested<StatefulSetBuilder> spec =
                    item.buildSpec() == null ? item.withNewSpec() : item.editSpec();
            StatefulSetSpecFluent.TemplateNested<StatefulSetFluent.SpecNested<StatefulSetBuilder>> template =
                    spec.buildTemplate() == null ? spec.withNewTemplate() : spec.editTemplate();
            template.endTemplate().endSpec();
        }
    });
}
 
Example #11
Source File: StatefulSetDiffTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
@Test
public void testSpecVolumesIgnored() {
    StatefulSet ss1 = new StatefulSetBuilder()
        .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
        .endMetadata()
        .withNewSpec().
            withNewTemplate()
                .withNewSpec()
                    .addToVolumes(0, new VolumeBuilder()
                                .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(1).build())
                            .build())
                .endSpec()
            .endTemplate()
        .endSpec()
        .build();
    StatefulSet ss2 = new StatefulSetBuilder()
        .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
        .endMetadata()
        .withNewSpec()
            .withNewTemplate()
                .withNewSpec()
                    .addToVolumes(0, new VolumeBuilder()
                            .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(2).build())
                            .build())
                .endSpec()
            .endTemplate()
        .endSpec()
        .build();
    assertThat(new StatefulSetDiff(ss1, ss2).changesSpecTemplate(), is(false));
}
 
Example #12
Source File: StatefulSetDiffTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
public StatefulSetDiff testCpuResources(ResourceRequirements requirements1, ResourceRequirements requirements2) {
    StatefulSet ss1 = new StatefulSetBuilder()
            .withNewMetadata()
                .withNamespace("test")
                .withName("foo")
            .endMetadata()
            .withNewSpec().
                withNewTemplate()
                    .withNewSpec()
                        .addNewContainer()
                            .withResources(requirements1)
                        .endContainer()
                    .endSpec()
                .endTemplate()
            .endSpec()
        .build();
    StatefulSet ss2 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
                .withNewTemplate()
                    .withNewSpec()
                        .addNewContainer()
                            .withResources(requirements2)
                        .endContainer()
                    .endSpec()
                .endTemplate()
            .endSpec()
            .build();
    return new StatefulSetDiff(ss1, ss2);
}
 
Example #13
Source File: StatefulSetTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Disabled
@Test
public void testUpdate() {
  StatefulSet repl1 = new StatefulSetBuilder()
    .withNewMetadata()
    .withName("repl1")
    .withNamespace("test")
    .endMetadata()
    .withNewSpec()
      .withReplicas(1)
      .withNewTemplate()
        .withNewMetadata().withLabels(new HashMap<String, String>()).endMetadata()
        .withNewSpec()
          .addNewContainer()
            .withImage("img1")
          .endContainer()
        .endSpec()
      .endTemplate()
    .endSpec()
    .withNewStatus().withReplicas(1).endStatus()
    .build();

 server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, repl1).once();
 server.expect().put().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, repl1).once();
 server.expect().get().withPath("/apis/apps/v1/namespaces/test/statefulsets").andReturn(200, new StatefulSetListBuilder().withItems(repl1).build()).once();
 server.expect().post().withPath("/apis/apps/v1/namespaces/test/statefulsets").andReturn(201, repl1).once();
 server.expect().withPath("/apis/apps/v1/namespaces/test/pods").andReturn(200, new KubernetesListBuilder().build()).once();
  KubernetesClient client = server.getClient();

  repl1 = client.apps().statefulSets().withName("repl1")
    .rolling()
    .withTimeout(5, TimeUnit.MINUTES)
    .updateImage("");
  assertNotNull(repl1);
}
 
Example #14
Source File: StatefulSetTest.java    From kubernetes-client with Apache License 2.0 5 votes vote down vote up
@Test
public void testScaleAndWait() {
 server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, new StatefulSetBuilder()
    .withNewMetadata()
    .withName("repl1")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(5)
    .endSpec()
    .withNewStatus()
      .withReplicas(1)
    .endStatus()
    .build()).once();

  server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, new StatefulSetBuilder()
      .withNewMetadata()
      .withName("repl1")
      .withResourceVersion("1")
      .endMetadata()
      .withNewSpec()
      .withReplicas(5)
      .endSpec()
      .withNewStatus()
      .withReplicas(5)
      .endStatus()
      .build()).always();

  KubernetesClient client = server.getClient();
  StatefulSet repl = client.apps().statefulSets().withName("repl1").scale(5, true);
  assertNotNull(repl);
  assertNotNull(repl.getSpec());
  assertEquals(5, repl.getSpec().getReplicas().intValue());
  assertEquals(5, repl.getStatus().getReplicas().intValue());
}
 
Example #15
Source File: StatefulSetHandler.java    From jkube with Eclipse Public License 2.0 5 votes vote down vote up
public StatefulSet getStatefulSet(ResourceConfig config,
                                  List<ImageConfiguration> images) {

    return new StatefulSetBuilder()
            .withMetadata(createStatefulSetMetaData(config))
            .withSpec(createStatefulSetSpec(config, images))
            .build();
}
 
Example #16
Source File: KafkaRollerTest.java    From strimzi-kafka-operator with Apache License 2.0 5 votes vote down vote up
private StatefulSet buildStatefulSet() {
    return new StatefulSetBuilder()
            .withNewMetadata()
            .withName(ssName())
            .withNamespace(ssNamespace())
            .addToLabels(Labels.STRIMZI_CLUSTER_LABEL, clusterName())
            .endMetadata()
            .withNewSpec()
            .withReplicas(5)
            .endSpec()
            .build();
}
 
Example #17
Source File: StatefulSetDiffTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Test
public void testPvcSizeChangeIgnored() {
    StatefulSet ss1 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
                .withNewTemplate()
                    .withNewSpec()
                        .addToVolumes(0, new VolumeBuilder()
                                .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(1).build())
                                .build())
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(new PersistentVolumeClaimBuilder()
                        .withNewSpec()
                            .withNewResources()
                                .withRequests(singletonMap("storage", new Quantity("100Gi")))
                            .endResources()
                        .endSpec()
                        .build())
            .endSpec()
            .build();
    StatefulSet ss2 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
                .withNewTemplate()
                    .withNewSpec()
                        .addToVolumes(0, new VolumeBuilder()
                                .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(2).build())
                                .build())
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(new PersistentVolumeClaimBuilder()
                        .withNewSpec()
                        .withNewResources()
                        .withRequests(singletonMap("storage", new Quantity("110Gi")))
                        .endResources()
                        .endSpec()
                        .build())
            .endSpec()
            .build();
    assertThat(new StatefulSetDiff(ss1, ss2).changesVolumeClaimTemplates(), is(false));
    assertThat(new StatefulSetDiff(ss1, ss2).changesVolumeSize(), is(true));
}
 
Example #18
Source File: StatefulSetRollingUpdater.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Override
protected StatefulSet setReplicas(StatefulSet obj, int replicas) {
  return new StatefulSetBuilder(obj).editSpec().withReplicas(replicas).endSpec().build();
}
 
Example #19
Source File: StatefulSetIT.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Before
public void init() {
  currentNamespace = session.getNamespace();
  ss1 = new StatefulSetBuilder()
    .withNewMetadata().withName("ss1").endMetadata()
    .withNewSpec()
    .withReplicas(2)
    .withNewSelector().withMatchLabels(Collections.singletonMap("app", "nginx")).endSelector()
    .withNewTemplate()
    .withNewMetadata()
    .addToLabels("app", "nginx")
    .endMetadata()
    .withNewSpec()
    .addNewContainer()
    .withName("nginx")
    .withImage("nginx")
    .addNewPort()
    .withContainerPort(80)
    .withName("web")
    .endPort()
    .addNewVolumeMount()
    .withName("www")
    .withMountPath("/usr/share/nginx/html")
    .endVolumeMount()
    .endContainer()
    .endSpec()
    .endTemplate()
    .addNewVolumeClaimTemplate()
    .withNewMetadata()
    .withName("www")
    .endMetadata()
    .withNewSpec()
    .addToAccessModes("ReadWriteOnce")
    .withNewResources()
    .withRequests(Collections.singletonMap("storage", new Quantity("1Gi")))
    .endResources()
    .endSpec()
    .endVolumeClaimTemplate()
    .endSpec()
    .build();

  client.apps().statefulSets().inNamespace(currentNamespace).create(ss1);
}
 
Example #20
Source File: StatefulSetTest.java    From kubernetes-client with Apache License 2.0 4 votes vote down vote up
@Test
public void testDelete() {
 server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, new StatefulSetBuilder() .withNewMetadata()
    .withName("repl1")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(0)
    .endSpec()
    .withNewStatus()
    .withReplicas(1)
    .endStatus()
    .build()).once();

 server.expect().withPath("/apis/apps/v1/namespaces/test/statefulsets/repl1").andReturn(200, new StatefulSetBuilder() .withNewMetadata()
    .withName("repl1")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(0)
    .endSpec()
    .withNewStatus()
    .withReplicas(0)
    .endStatus()
    .build()).times(5);

 server.expect().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/repl2").andReturn(200, new StatefulSetBuilder() .withNewMetadata()
    .withName("repl2")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(0)
    .endSpec()
    .withNewStatus()
    .withReplicas(1)
    .endStatus()
    .build()).once();

 server.expect().withPath("/apis/apps/v1/namespaces/ns1/statefulsets/repl2").andReturn(200, new StatefulSetBuilder() .withNewMetadata()
    .withName("repl2")
    .withResourceVersion("1")
    .endMetadata()
    .withNewSpec()
    .withReplicas(0)
    .endSpec()
    .withNewStatus()
    .withReplicas(0)
    .endStatus()
    .build()).times(5);

  KubernetesClient client = server.getClient();

  Boolean deleted = client.apps().statefulSets().withName("repl1").delete();
  assertTrue(deleted);

  deleted = client.apps().statefulSets().withName("repl2").delete();
  assertFalse(deleted);

  deleted = client.apps().statefulSets().inNamespace("ns1").withName("repl2").delete();
  assertTrue(deleted);
}
 
Example #21
Source File: StatefulSetDiffTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Test
public void testNewPvcNotIgnored() {
    StatefulSet ss1 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
                .withNewTemplate()
                    .withNewSpec()
                        .addToVolumes(0, new VolumeBuilder()
                                .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(1).build())
                                .build())
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(new PersistentVolumeClaimBuilder()
                        .withNewSpec()
                        .withNewResources()
                        .withRequests(singletonMap("storage", new Quantity("100Gi")))
                        .endResources()
                        .endSpec()
                        .build())
            .endSpec()
            .build();
    StatefulSet ss2 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
                .withNewTemplate()
                    .withNewSpec()
                        .addToVolumes(0, new VolumeBuilder()
                                .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(2).build())
                                .build())
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(new PersistentVolumeClaimBuilder()
                        .withNewSpec()
                        .withNewResources()
                        .withRequests(singletonMap("storage", new Quantity("100Gi")))
                        .endResources()
                        .endSpec()
                        .build(),
                        new PersistentVolumeClaimBuilder()
                                .withNewSpec()
                                .withNewResources()
                                .withRequests(singletonMap("storage", new Quantity("110Gi")))
                                .endResources()
                                .endSpec()
                                .build())
            .endSpec()
            .build();
    assertThat(new StatefulSetDiff(ss1, ss2).changesVolumeClaimTemplates(), is(true));
    assertThat(new StatefulSetDiff(ss1, ss2).changesVolumeSize(), is(false));
}
 
Example #22
Source File: StatefulSetDiffTest.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
@Test
public void testPvcSizeUnitChangeIgnored() {
    StatefulSet ss1 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
            .withNewTemplate()
            .withNewSpec()
            .addToVolumes(0, new VolumeBuilder()
                    .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(1).build())
                    .build())
            .endSpec()
            .endTemplate()
            .withVolumeClaimTemplates(new PersistentVolumeClaimBuilder()
                    .withNewSpec()
                    .withNewResources()
                    .withRequests(singletonMap("storage", new Quantity("3072Gi")))
                    .endResources()
                    .endSpec()
                    .build())
            .endSpec()
            .build();
    StatefulSet ss2 = new StatefulSetBuilder()
            .withNewMetadata()
            .withNamespace("test")
            .withName("foo")
            .endMetadata()
            .withNewSpec()
            .withNewTemplate()
            .withNewSpec()
            .addToVolumes(0, new VolumeBuilder()
                    .withConfigMap(new ConfigMapVolumeSourceBuilder().withDefaultMode(2).build())
                    .build())
            .endSpec()
            .endTemplate()
            .withVolumeClaimTemplates(new PersistentVolumeClaimBuilder()
                    .withNewSpec()
                    .withNewResources()
                    .withRequests(singletonMap("storage", new Quantity("3Ti")))
                    .endResources()
                    .endSpec()
                    .build())
            .endSpec()
            .build();
    assertThat(new StatefulSetDiff(ss1, ss2).changesVolumeClaimTemplates(), is(false));
    assertThat(new StatefulSetDiff(ss1, ss2).changesVolumeSize(), is(false));
}
 
Example #23
Source File: RabbitMQClusterFactory.java    From rabbitmq-operator with Apache License 2.0 4 votes vote down vote up
private StatefulSet buildStatefulSet(
        final RabbitMQCustomResource resource,
        final Container container
) {
    final String clusterName = resource.getName();
    final String namespace = resource.getMetadata().getNamespace();

    final RabbitMQStorageResources storage = resource.getSpec().getStorageResources();

    return new StatefulSetBuilder()
            .withNewMetadata()
            .withName(clusterName)
            .withNamespace(namespace)
            .withOwnerReferences(
                    new OwnerReference(
                            resource.getApiVersion(),
                            true,
                            true,
                            resource.getKind(),
                            clusterName,
                            resource.getMetadata().getUid()
                    )
            )
            .addToLabels(Labels.Kubernetes.INSTANCE, clusterName)
            .addToLabels(Labels.Kubernetes.MANAGED_BY, Labels.Values.RABBITMQ_OPERATOR)
            .addToLabels(Labels.Kubernetes.PART_OF, Labels.Values.RABBITMQ)
            .endMetadata()
            .withNewSpec()
            .withReplicas(resource.getSpec().getReplicas())
            .withServiceName(RabbitMQServices.getDiscoveryServiceName(clusterName))
            .withNewSelector().addToMatchLabels(Labels.Kubernetes.INSTANCE, clusterName).endSelector()
            .withNewTemplate()
            .withNewMetadata()
            .addToLabels(Labels.Kubernetes.INSTANCE, clusterName)
            .addToLabels(Labels.Kubernetes.MANAGED_BY, Labels.Values.RABBITMQ_OPERATOR)
            .addToLabels(Labels.Kubernetes.PART_OF, Labels.Values.RABBITMQ)
            .addToLabels(Labels.Indeed.getIndeedLabels(resource))
            .addToAnnotations("ad.datadoghq.com/" + clusterName + ".check_names", "[\"rabbitmq\"]")
            .addToAnnotations("ad.datadoghq.com/" + clusterName + ".init_configs", "[{}]")
            .addToAnnotations("ad.datadoghq.com/" + clusterName + ".instances", "[{\"rabbitmq_api_url\":\"http://%%host%%:15672/api\",\"rabbitmq_user\":\"monitoring\",\"rabbitmq_pass\":\"monitoring\"}]")
            .endMetadata()
            .withSpec(rabbitMQPods.buildPodSpec(clusterName, resource.getSpec().getInitContainerImage(), container))
            .endTemplate()
            .addNewVolumeClaimTemplate()
            .withNewMetadata()
            .withName(RABBITMQ_STORAGE_NAME)
            .withOwnerReferences(
                    new OwnerReference(
                            resource.getApiVersion(),
                            true,
                            true,
                            resource.getKind(),
                            clusterName,
                            resource.getMetadata().getUid()
                    )
            )
            .addToLabels(Labels.Kubernetes.INSTANCE, clusterName)
            .addToLabels(Labels.Kubernetes.MANAGED_BY, Labels.Values.RABBITMQ_OPERATOR)
            .addToLabels(Labels.Kubernetes.PART_OF, Labels.Values.RABBITMQ)
            .endMetadata()
            .withNewSpec()
            .withStorageClassName(storage.getStorageClassName())
            .withAccessModes("ReadWriteOnce")
            .withNewResources()
            .withRequests(Collections.singletonMap("storage", storage.getStorage()))
            .endResources()
            .endSpec()
            .endVolumeClaimTemplate()
            .endSpec()
            .build();
}
 
Example #24
Source File: AbstractModel.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
protected StatefulSet createStatefulSet(
        Map<String, String> stsAnnotations,
        Map<String, String> podAnnotations,
        List<Volume> volumes,
        List<PersistentVolumeClaim> volumeClaims,
        Affinity affinity,
        List<Container> initContainers,
        List<Container> containers,
        List<LocalObjectReference> imagePullSecrets,
        boolean isOpenShift) {

    PodSecurityContext securityContext = templateSecurityContext;

    // if a persistent volume claim is requested and the running cluster is a Kubernetes one (non-openshift) and we
    // have no user configured PodSecurityContext we set the podSecurityContext.
    // This is to give each pod write permissions under a specific group so that if a pod changes users it does not have permission issues.
    if (ModelUtils.containsPersistentStorage(storage) && !isOpenShift && securityContext == null) {
        securityContext = new PodSecurityContextBuilder()
                .withFsGroup(AbstractModel.DEFAULT_FS_GROUPID)
                .build();
    }

    StatefulSet statefulSet = new StatefulSetBuilder()
            .withNewMetadata()
                .withName(name)
                .withLabels(getLabelsWithStrimziName(name, templateStatefulSetLabels).toMap())
                .withNamespace(namespace)
                .withAnnotations(mergeLabelsOrAnnotations(stsAnnotations, templateStatefulSetAnnotations))
                .withOwnerReferences(createOwnerReference())
            .endMetadata()
            .withNewSpec()
                .withPodManagementPolicy(templatePodManagementPolicy.toValue())
                .withUpdateStrategy(new StatefulSetUpdateStrategyBuilder().withType("OnDelete").build())
                .withSelector(new LabelSelectorBuilder().withMatchLabels(getSelectorLabels().toMap()).build())
                .withServiceName(headlessServiceName)
                .withReplicas(replicas)
                .withNewTemplate()
                    .withNewMetadata()
                        .withName(name)
                        .withLabels(getLabelsWithStrimziName(name, templatePodLabels).toMap())
                        .withAnnotations(mergeLabelsOrAnnotations(podAnnotations, templatePodAnnotations))
                    .endMetadata()
                    .withNewSpec()
                        .withServiceAccountName(getServiceAccountName())
                        .withAffinity(affinity)
                        .withInitContainers(initContainers)
                        .withContainers(containers)
                        .withVolumes(volumes)
                        .withTolerations(getTolerations())
                        .withTerminationGracePeriodSeconds(Long.valueOf(templateTerminationGracePeriodSeconds))
                        .withImagePullSecrets(templateImagePullSecrets != null ? templateImagePullSecrets : imagePullSecrets)
                        .withSecurityContext(securityContext)
                        .withPriorityClassName(templatePodPriorityClassName)
                        .withSchedulerName(templatePodSchedulerName != null ? templatePodSchedulerName : "default-scheduler")
                    .endSpec()
                .endTemplate()
                .withVolumeClaimTemplates(volumeClaims)
            .endSpec()
            .build();

    return statefulSet;
}
 
Example #25
Source File: KafkaAssemblyOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * <p>Final downgrade phase
 * <ol>
 *     <li>Update the strimzi.io/kafka-version to the new version</li>
 *     <li>Remove the strimzi.io/from-kafka-version since this is the last phase</li>
 *     <li>Remove the strimzi.io/to-kafka-version since this is the last phase</li>
 *     <li>Remove inter.broker.protocol.version (so the new version's default is used)</li>
 *     <li>Update the image in the STS</li>
 *     <li>Reconcile the STS and perform a rolling update of the pods</li>
 * </ol>
 */
private Future<Void> kafkaDowngradePhase2(StatefulSet sts, ConfigMap cm, KafkaVersionChange versionChange, String downgradedImage) {
    log.info("{}: {}, phase 2", reconciliation, versionChange);
    // Remove the strimzi.io/from-version and strimzi.io/to-version since this is the last phase

    Map<String, String> annotations = Annotations.annotations(sts);

    log.info("{}: Upgrade: Removing annotations {}, {}",
            reconciliation, ANNO_STRIMZI_IO_FROM_VERSION, ANNO_STRIMZI_IO_TO_VERSION);
    annotations.remove(ANNO_STRIMZI_IO_FROM_VERSION);
    annotations.remove(ANNO_STRIMZI_IO_TO_VERSION);
    annotations.put(ANNO_STRIMZI_IO_KAFKA_VERSION, versionChange.to().version());

    // Remove inter.broker.protocol.version (so the new version's default is used)
    String config = cm.getData().getOrDefault("server.config", "");
    log.info("{}: Upgrade: Removing Kafka config {}, will default to {}",
            reconciliation, INTERBROKER_PROTOCOL_VERSION, versionChange.to().protocolVersion());

    StatefulSet newSts = new StatefulSetBuilder(sts)
            .editMetadata()
                .withAnnotations(annotations)
            .endMetadata()
            .build();

    StringBuilder newConfigBuilder = new StringBuilder();
    Arrays.stream(config.split(System.lineSeparator())).filter(line -> !line.startsWith(INTERBROKER_PROTOCOL_VERSION + "=")).forEach(line -> newConfigBuilder.append(line + System.lineSeparator()));
    String newConfig = newConfigBuilder.toString();

    ConfigMap newCm = new ConfigMapBuilder(cm).build();
    newCm.getData().put("server.config", newConfig);

    // Reconcile the STS and perform a rolling update of the pods
    String stsName = KafkaCluster.kafkaClusterName(this.name);
    String cmName = KafkaCluster.metricAndLogConfigsName(this.name);
    log.info("{}: Upgrade: Patch + rolling update of {}", reconciliation, stsName);
    return CompositeFuture.join(kafkaSetOperations.reconcile(namespace, stsName, newSts), configMapOperations.reconcile(namespace, cmName, newCm))
            .compose(ignored -> kafkaSetOperations.maybeRollingUpdate(sts, pod -> {
                log.info("{}: Upgrade: Patch + rolling update of {}: Pod {}", reconciliation, stsName, pod.getMetadata().getName());
                return "Upgrade phase 2 of 2: Patch + rolling update of " + name + ": Pod " + pod.getMetadata().getName();
            }))
            .compose(ignored -> {
                log.info("{}: {}, phase 2 of 2 completed", reconciliation, versionChange);
                return Future.succeededFuture();
            });
}
 
Example #26
Source File: KafkaAssemblyOperator.java    From strimzi-kafka-operator with Apache License 2.0 4 votes vote down vote up
/**
 * Final upgrade phase
 * Note: The log.message.format.version is left at the old version.
 * It is a manual action to remove that once the user has updated all their clients.
 */
private Future<Void> kafkaUpgradePhase2(StatefulSet sts, ConfigMap cm, KafkaVersionChange upgrade) {
    if (sts == null) {
        // It was a one-phase update
        return Future.succeededFuture();
    }
    // Cluster is now using new binaries, but old proto version
    log.info("{}: {}, phase 2", reconciliation, upgrade);
    // Remove the strimzi.io/from-version and strimzi.io/to-version since this is the last phase
    Map<String, String> annotations = Annotations.annotations(sts);
    log.info("{}: Upgrade: Removing annotations {}, {}",
            reconciliation, ANNO_STRIMZI_IO_FROM_VERSION, ANNO_STRIMZI_IO_TO_VERSION);
    annotations.remove(ANNO_STRIMZI_IO_FROM_VERSION);
    annotations.remove(ANNO_STRIMZI_IO_TO_VERSION);

    // Remove inter.broker.protocol.version (so the new version's default is used)
    String config = cm.getData().getOrDefault("server.config", "");
    StringBuilder newConfigBuilder = new StringBuilder();
    Arrays.stream(config.split(System.lineSeparator())).filter(line -> !line.startsWith(INTERBROKER_PROTOCOL_VERSION + "=")).forEach(line -> newConfigBuilder.append(line + System.lineSeparator()));
    String newConfig = newConfigBuilder.toString();

    log.info("{}: Upgrade: Removing Kafka config {}, will default to {}",
            reconciliation, INTERBROKER_PROTOCOL_VERSION, upgrade.to().protocolVersion());

    // Update to new proto version and rolling upgrade
    StatefulSet newSts = new StatefulSetBuilder(sts)
            .editMetadata()
                .withAnnotations(annotations)
            .endMetadata()
            .build();

    ConfigMap newCm = new ConfigMapBuilder(cm).build();
    newCm.getData().put("server.config", newConfig);

    // Reconcile the STS and perform a rolling update of the pods
    String stsName = KafkaCluster.kafkaClusterName(this.name);
    String cmName = KafkaCluster.metricAndLogConfigsName(this.name);
    log.info("{}: Upgrade: Patch + rolling update of {}", reconciliation, stsName);
    return CompositeFuture.join(kafkaSetOperations.reconcile(namespace, stsName, newSts), configMapOperations.reconcile(namespace, cmName, newCm))
            .compose(ignored -> kafkaSetOperations.maybeRollingUpdate(sts, pod -> {
                log.info("{}: Upgrade: Patch + rolling update of {}: Pod {}", reconciliation, stsName, pod.getMetadata().getName());
                return "Upgrade: Patch + rolling update of " + name + ": Pod " + pod.getMetadata().getName();
            }))
            .compose(ignored -> {
                log.info("{}: {}, phase 2 of 2 completed", reconciliation, upgrade);
                return Future.succeededFuture();
            });
}
 
Example #27
Source File: ControllerViaPluginConfigurationEnricher.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
private void mergeStatefulSetSpec(StatefulSetBuilder builder, StatefulSetSpec spec) {
    StatefulSetFluent.SpecNested<StatefulSetBuilder> specBuilder = builder.editSpec();
    KubernetesResourceUtil.mergeSimpleFields(specBuilder, spec);
    specBuilder.endSpec();
}
 
Example #28
Source File: MetadataVisitor.java    From jkube with Eclipse Public License 2.0 4 votes vote down vote up
@Override
protected ObjectMeta getOrCreateMetadata(StatefulSetBuilder item) {
    return addEmptyLabelsAndAnnotations(item::hasMetadata, item::withNewMetadata, item::editMetadata, item::buildMetadata)
            .endMetadata().buildMetadata();
}
 
Example #29
Source File: KubernetesAppDeployer.java    From spring-cloud-deployer-kubernetes with Apache License 2.0 2 votes vote down vote up
/**
 * Create a StatefulSet
 *
 * @param request the {@link AppDeploymentRequest}
 */
protected void createStatefulSet(AppDeploymentRequest request) {

	String appId = createDeploymentId(request);

	int externalPort = getExternalPort(request);

	Map<String, String> idMap = createIdMap(appId, request);

	int replicas = getCountFromRequest(request);

	Map<String, String> kubernetesDeployerProperties = request.getDeploymentProperties();

	logger.debug(String.format("Creating StatefulSet: %s on %d with %d replicas", appId, externalPort, replicas));

	Map<String, Quantity> storageResource = Collections.singletonMap("storage",
			new Quantity(this.deploymentPropertiesResolver.getStatefulSetStorage(kubernetesDeployerProperties)));

	String storageClassName = this.deploymentPropertiesResolver.getStatefulSetStorageClassName(kubernetesDeployerProperties);

	PersistentVolumeClaimBuilder persistentVolumeClaimBuilder = new PersistentVolumeClaimBuilder().withNewSpec().
			withStorageClassName(storageClassName).withAccessModes(Collections.singletonList("ReadWriteOnce"))
			.withNewResources().addToLimits(storageResource).addToRequests(storageResource).endResources()
			.endSpec().withNewMetadata().withName(appId).withLabels(idMap)
			.addToLabels(SPRING_MARKER_KEY, SPRING_MARKER_VALUE).endMetadata();

	PodSpec podSpec = createPodSpec(request);

	podSpec.getVolumes().add(new VolumeBuilder().withName("config").withNewEmptyDir().endEmptyDir().build());

	podSpec.getContainers().get(0).getVolumeMounts()
		.add(new VolumeMountBuilder().withName("config").withMountPath("/config").build());

	String statefulSetInitContainerImageName = this.deploymentPropertiesResolver.getStatefulSetInitContainerImageName(kubernetesDeployerProperties);

	podSpec.getInitContainers().add(createStatefulSetInitContainer(statefulSetInitContainerImageName));
	
	Map<String, String> deploymentLabels=  this.deploymentPropertiesResolver.getDeploymentLabels(request.getDeploymentProperties());
	
	StatefulSetSpec spec = new StatefulSetSpecBuilder().withNewSelector().addToMatchLabels(idMap)
			.addToMatchLabels(SPRING_MARKER_KEY, SPRING_MARKER_VALUE).endSelector()
			.withVolumeClaimTemplates(persistentVolumeClaimBuilder.build()).withServiceName(appId)
			.withPodManagementPolicy("Parallel").withReplicas(replicas).withNewTemplate().withNewMetadata()
			.withLabels(idMap).addToLabels(SPRING_MARKER_KEY, SPRING_MARKER_VALUE).addToLabels(deploymentLabels)
			.endMetadata().withSpec(podSpec).endTemplate().build();

	StatefulSet statefulSet = new StatefulSetBuilder().withNewMetadata().withName(appId).withLabels(idMap)
			.addToLabels(SPRING_MARKER_KEY, SPRING_MARKER_VALUE).addToLabels(deploymentLabels).endMetadata().withSpec(spec).build();

	client.apps().statefulSets().create(statefulSet);
}