yifan-c commented on code in PR #256:
URL: https://github.com/apache/cassandra-sidecar/pull/256#discussion_r2380482950


##########
client-common/src/main/java/org/apache/cassandra/sidecar/common/data/LifecycleCassandraState.java:
##########
@@ -0,0 +1,53 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.cassandra.sidecar.common.data;
+
+import static 
org.apache.cassandra.sidecar.common.request.data.NodeCommandRequestPayload.State;
+
+/**
+ * Represents the lifecycle state of a Cassandra instance.
+ */
+public enum LifecycleCassandraState

Review Comment:
   How about `CassandraLifecycleState`? "CassandraLifecycle" modifies "State", 
indicating what kind of state it is.
   
   I noticed that you also have `LifecycleStatus`. Maybe your idea is to have 
the `Lifecycle` scope, and have `CassandraState` in the scope. In this case, 
maybe have something like this, which better indicates the scope, e.g. 
`Lifecycle.CassandraState`
   
   ```java
   class Lifecycle 
   {
       enum CassandraState { .. }
       enum OperationStatus { .. }
   }
   ```



##########
server/src/main/java/org/apache/cassandra/sidecar/handlers/LifecycleUpdateHandler.java:
##########
@@ -0,0 +1,122 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.handlers;
+
+import java.util.Collections;
+import java.util.Set;
+
+import com.google.inject.Inject;
+import com.google.inject.Singleton;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.http.HttpServerRequest;
+import io.vertx.core.json.Json;
+import io.vertx.core.net.SocketAddress;
+import io.vertx.ext.auth.authorization.Authorization;
+import io.vertx.ext.web.RoutingContext;
+import io.vertx.ext.web.handler.HttpException;
+import org.apache.cassandra.sidecar.acl.authorization.BasicPermissions;
+import org.apache.cassandra.sidecar.common.data.LifecycleCassandraState;
+import 
org.apache.cassandra.sidecar.common.request.data.NodeCommandRequestPayload;
+import org.apache.cassandra.sidecar.concurrent.ExecutorPools;
+import org.apache.cassandra.sidecar.exceptions.LifecycleTaskConflictException;
+import org.apache.cassandra.sidecar.lifecycle.LifecycleManager;
+import org.apache.cassandra.sidecar.utils.HttpExceptions;
+
+import org.apache.cassandra.sidecar.utils.InstanceMetadataFetcher;
+import org.jetbrains.annotations.NotNull;
+
+import static 
org.apache.cassandra.sidecar.common.data.LifecycleCassandraState.fromNodeCommandState;
+
+/**
+ * Handles {@code PUT /api/v1/cassandra/lifecycle} requests to start or stop a 
Cassandra node.
+ *
+ * <p> Expects a JSON payload:
+ * { "state": "start" } or { "state": "stop" }
+ * and will record the desired state. </p>
+ */
+@Singleton
+public class LifecycleUpdateHandler extends NodeCommandHandler implements 
AccessProtected
+{
+    private final LifecycleManager lifecycleManager;
+
+    @Inject
+    public LifecycleUpdateHandler(InstanceMetadataFetcher metadataFetcher, 
ExecutorPools executorPools, LifecycleManager lifecycleManager)
+    {
+        super(metadataFetcher, executorPools, null);
+        this.lifecycleManager = lifecycleManager;
+    }
+
+    @Override
+    public Set<Authorization> requiredAuthorizations()
+    {
+        return 
Collections.singleton(BasicPermissions.MODIFY_LIFECYCLE.toAuthorization());
+    }
+
+    @Override
+    protected void handleInternal(RoutingContext context,
+                                  HttpServerRequest httpRequest,
+                                  @NotNull String host,
+                                  SocketAddress remoteAddress,
+                                  NodeCommandRequestPayload request)
+    {
+        LifecycleCassandraState desiredState = 
fromNodeCommandState(request.state());
+        executorPools.service()
+                     .executeBlocking(() -> 
lifecycleManager.updateDesiredState(host, desiredState))
+                     .onSuccess(info ->
+                                {
+                                    switch (info.status())
+                                    {
+                                        case CONVERGED:
+                                            
context.response().putHeader("Content-Type", "application/json")
+                                                   
.setStatusCode(HttpResponseStatus.OK.code())
+                                                   .end(Json.encode(info));
+                                            break;
+                                        case CONVERGING:
+                                            
context.response().putHeader("Content-Type", "application/json")
+                                                   
.setStatusCode(HttpResponseStatus.ACCEPTED.code())
+                                                   .end(Json.encode(info));
+                                            break;
+                                        default:
+                                            logger.warn("{} request failed 
with unexpected result. request={}, remoteAddress={}, instance={}, 
lifecycleStatus={}",
+                                                        
this.getClass().getSimpleName(), request, remoteAddress, host, info.status());
+                                            
context.response().putHeader("Content-Type", "application/json")
+                                                   
.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code())
+                                                   .end(Json.encode(info));
+                                    }

Review Comment:
   nit: it could be simplified.
   
   ```suggestion
                                       HttpServerResponse response = 
context.response().putHeader("Content-Type", "application/json");
                                       switch (info.status())
                                       {
                                           case CONVERGED:
                                               
response.setStatusCode(HttpResponseStatus.OK.code());
                                               break;
                                           case CONVERGING:
                                               
response.setStatusCode(HttpResponseStatus.ACCEPTED.code());
                                               break;
                                           default:
                                               logger.warn("{} request failed 
with unexpected result. request={}, remoteAddress={}, instance={}, 
lifecycleStatus={}",
                                                           
this.getClass().getSimpleName(), request, remoteAddress, host, info.status());
                                               
response.setStatusCode(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
                                       }
                                       response.end(Json.encode(info));
   ```



##########
client-common/src/main/java/org/apache/cassandra/sidecar/common/data/LifecycleStatus.java:
##########
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.cassandra.sidecar.common.data;
+
+/**
+ * Represents the lifecycle status of this instance relative to the desired 
state.
+ */
+public enum LifecycleStatus
+{
+    /**
+     * The status when a desired lifecycle state has not been submitted yet
+     */
+    UNDEFINED,
+
+    /**
+     * The status when the current lifecycle state of an instance matches the 
desired lifecycle state
+     */
+    CONVERGED,
+
+    /**
+     * The status when the current lifecycle state of an instance does not 
match the desired lifecycle state
+     */
+    DIVERGED,
+
+    /**
+     * The status when an instance is starting or stopping to match the 
desired lifecycle state
+     */
+    CONVERGING;

Review Comment:
   How to distinguish `DIVERGED` and `CONVERGING`? They both means the target 
state does not match the current state. 



##########
client-common/src/main/java/org/apache/cassandra/sidecar/common/data/LifecycleStatus.java:
##########
@@ -0,0 +1,56 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+
+package org.apache.cassandra.sidecar.common.data;
+
+/**
+ * Represents the lifecycle status of this instance relative to the desired 
state.
+ */
+public enum LifecycleStatus

Review Comment:
   How about `LifecycleOperationStatus`? 
   
   (Although I feel that `State` and `Status` might be confusing.)



##########
integration-tests/src/integrationTest/org/apache/cassandra/sidecar/lifecycle/InJvmLifecycleProviderIntegrationTest.java:
##########
@@ -0,0 +1,86 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.lifecycle;
+
+import org.junit.jupiter.api.BeforeAll;
+import org.junit.jupiter.api.Test;
+
+import org.apache.cassandra.sidecar.cluster.instance.InstanceMetadata;
+import 
org.apache.cassandra.sidecar.testing.SharedClusterSidecarIntegrationTestBase;
+import org.apache.cassandra.sidecar.utils.SimpleCassandraVersion;
+import org.apache.cassandra.testing.ClusterBuilderConfiguration;
+
+import static org.assertj.core.api.Assumptions.assumeThat;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+
+/**
+ * Tests the {@link InJvmDTestLifecycleProvider} to ensure it can start and 
stop a Cassandra node
+ */
+public class InJvmLifecycleProviderIntegrationTest extends 
SharedClusterSidecarIntegrationTestBase
+{
+    static final InstanceMetadata LOCALHOST_METADATA = 
mock(InstanceMetadata.class);
+    private static final String JVM_LIFECYCLE_TEST_MIN_VERSION = "4.1";
+
+    @BeforeAll
+    static void beforeAll()
+    {
+        when(LOCALHOST_METADATA.host()).thenReturn("localhost");
+    }
+
+    @Override
+    protected ClusterBuilderConfiguration testClusterConfiguration()
+    {
+        return super.testClusterConfiguration().startCluster(false);
+    }
+
+    @Override
+    protected void beforeClusterProvisioning()
+    {
+        // JVM Distributed Test framework contains a bug with restarting nodes 
in version 4.0 (CASSANDRA-19729)
+        assumeThat(SimpleCassandraVersion.create(testVersion.version()))
+        .withFailMessage("JVM Distributed Test framework contains a bug with 
restarting nodes in version 4.0 (CASSANDRA-19729)")

Review Comment:
   I do not think you want to override the error message completely, and 
probably want to use `as(..)` instead.
   Please check out the difference between `as(..)` and `withFailMessage(..)`.



##########
server/src/test/java/org/apache/cassandra/sidecar/handlers/LifecycleUpdateHandlerTest.java:
##########
@@ -0,0 +1,205 @@
+/*
+ * Licensed to the Apache Software Foundation (ASF) under one
+ * or more contributor license agreements.  See the NOTICE file
+ * distributed with this work for additional information
+ * regarding copyright ownership.  The ASF licenses this file
+ * to you under the Apache License, Version 2.0 (the
+ * "License"); you may not use this file except in compliance
+ * with the License.  You may obtain a copy of the License at
+ *
+ *     http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+
+package org.apache.cassandra.sidecar.handlers;
+
+import java.util.concurrent.TimeUnit;
+
+import org.junit.jupiter.api.AfterEach;
+import org.junit.jupiter.api.BeforeEach;
+import org.junit.jupiter.api.Test;
+import org.junit.jupiter.api.extension.ExtendWith;
+
+import com.google.inject.AbstractModule;
+import com.google.inject.Guice;
+import com.google.inject.Injector;
+import com.google.inject.Module;
+import com.google.inject.Provides;
+import com.google.inject.Singleton;
+import com.google.inject.util.Modules;
+import io.netty.handler.codec.http.HttpResponseStatus;
+import io.vertx.core.Vertx;
+import io.vertx.core.json.JsonObject;
+import io.vertx.ext.web.client.WebClient;
+import io.vertx.junit5.VertxExtension;
+import io.vertx.junit5.VertxTestContext;
+import org.apache.cassandra.sidecar.TestModule;
+import org.apache.cassandra.sidecar.TestResourceReaper;
+import org.apache.cassandra.sidecar.common.data.LifecycleCassandraState;
+import org.apache.cassandra.sidecar.common.data.LifecycleStatus;
+import org.apache.cassandra.sidecar.common.response.LifecycleInfoResponse;
+import org.apache.cassandra.sidecar.exceptions.LifecycleTaskConflictException;
+import org.apache.cassandra.sidecar.lifecycle.LifecycleManager;
+import org.apache.cassandra.sidecar.modules.SidecarModules;
+import org.apache.cassandra.sidecar.server.Server;
+
+import static io.netty.handler.codec.http.HttpResponseStatus.ACCEPTED;
+import static io.netty.handler.codec.http.HttpResponseStatus.BAD_REQUEST;
+import static io.netty.handler.codec.http.HttpResponseStatus.CONFLICT;
+import static org.apache.cassandra.testing.utils.AssertionUtils.getBlocking;
+import static org.assertj.core.api.Assertions.assertThat;
+import static org.mockito.Mockito.doThrow;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.reset;
+import static org.mockito.Mockito.times;
+import static org.mockito.Mockito.verify;
+import static org.mockito.Mockito.when;
+
+/**
+ * Test for {@link LifecycleUpdateHandler}
+ */
+@ExtendWith(VertxExtension.class)
+public class LifecycleUpdateHandlerTest
+{
+    Vertx vertx;
+    Server server;
+    LifecycleManager mockLifecycleManager = mock(LifecycleManager.class);
+
+    @BeforeEach
+    void before() throws InterruptedException
+    {
+        Injector injector;
+        Module testOverride = Modules.override(new TestModule()).with(new 
LifecycleUpdateHandlerTestModule());
+        injector = 
Guice.createInjector(Modules.override(SidecarModules.all()).with(testOverride));
+        vertx = injector.getInstance(Vertx.class);
+        server = injector.getInstance(Server.class);
+        VertxTestContext context = new VertxTestContext();
+        server.start().onSuccess(s -> 
context.completeNow()).onFailure(context::failNow);
+        context.awaitCompletion(5, TimeUnit.SECONDS);
+        reset(mockLifecycleManager);
+    }
+
+    @AfterEach
+    void after() throws InterruptedException
+    {
+        getBlocking(TestResourceReaper.create().with(server).close(), 60, 
TimeUnit.SECONDS, "Closing server");
+    }
+
+    @Test
+    void testSuccessfulPutWithAcceptedResponse(VertxTestContext ctx) throws 
LifecycleTaskConflictException
+    {
+        WebClient client = WebClient.create(vertx);
+        JsonObject payload = JsonObject.of("state", "start");
+        LifecycleInfoResponse expectedResponse = new 
LifecycleInfoResponse(LifecycleCassandraState.STOPPED,
+                                                                           
LifecycleCassandraState.RUNNING,
+                                                                           
LifecycleStatus.CONVERGING,
+                                                                           
"Submitted task to start instance");
+        when(mockLifecycleManager.updateDesiredState("127.0.0.1", 
LifecycleCassandraState.RUNNING))
+                                                                               
 .thenReturn(expectedResponse);
+        client.put(server.actualPort(), "127.0.0.1", 
"/api/v1/cassandra/lifecycle")
+              .sendBuffer(payload.toBuffer(), ctx.succeeding(resp -> {
+                  ctx.verify(() -> {
+                      verify(mockLifecycleManager, 
times(1)).updateDesiredState("127.0.0.1", LifecycleCassandraState.RUNNING);
+                      
assertThat(resp.bodyAsJson(LifecycleInfoResponse.class)).isEqualTo(expectedResponse);
+                      assertThat(resp.statusCode()).isEqualTo(ACCEPTED.code());
+                  });
+                  ctx.completeNow();
+              }));
+    }
+
+    @Test
+    void testSuccessfulPutWithOKResponse(VertxTestContext ctx) throws 
LifecycleTaskConflictException
+    {
+        WebClient client = WebClient.create(vertx);
+        JsonObject payload = JsonObject.of("state", "stop");
+        LifecycleInfoResponse expectedResponse = new 
LifecycleInfoResponse(LifecycleCassandraState.STOPPED,
+                                                                           
LifecycleCassandraState.STOPPED,
+                                                                           
LifecycleStatus.CONVERGED,
+                                                                           
"Submitted task to stop instance");
+        when(mockLifecycleManager.updateDesiredState("127.0.0.1", 
LifecycleCassandraState.STOPPED)).thenReturn(expectedResponse);
+        client.put(server.actualPort(), "127.0.0.1", 
"/api/v1/cassandra/lifecycle")
+              .sendBuffer(payload.toBuffer(), ctx.succeeding(resp -> {
+                  ctx.verify(() -> {
+                      verify(mockLifecycleManager, 
times(1)).updateDesiredState("127.0.0.1", LifecycleCassandraState.STOPPED);
+                      
assertThat(resp.bodyAsJson(LifecycleInfoResponse.class)).isEqualTo(expectedResponse);
+                      
assertThat(resp.statusCode()).isEqualTo(HttpResponseStatus.OK.code());
+                  });
+                  ctx.completeNow();
+              }));
+    }
+
+    @Test
+    void testSuccessfulPutWithFailedResponse(VertxTestContext ctx) throws 
LifecycleTaskConflictException
+    {
+        WebClient client = WebClient.create(vertx);
+        JsonObject payload = JsonObject.of("state", "stop");
+        LifecycleInfoResponse expectedResponse = new 
LifecycleInfoResponse(LifecycleCassandraState.RUNNING,
+                                                                           
LifecycleCassandraState.STOPPED,
+                                                                           
LifecycleStatus.DIVERGED,
+                                                                           
"Error while stopping instance");
+        when(mockLifecycleManager.updateDesiredState("127.0.0.1", 
LifecycleCassandraState.STOPPED)).thenReturn(expectedResponse);
+        client.put(server.actualPort(), "127.0.0.1", 
"/api/v1/cassandra/lifecycle")
+              .sendBuffer(payload.toBuffer(), ctx.succeeding(resp -> {
+                  ctx.verify(() -> {
+                      verify(mockLifecycleManager, 
times(1)).updateDesiredState("127.0.0.1", LifecycleCassandraState.STOPPED);
+                      
assertThat(resp.bodyAsJson(LifecycleInfoResponse.class)).isEqualTo(expectedResponse);
+                      
assertThat(resp.statusCode()).isEqualTo(HttpResponseStatus.INTERNAL_SERVER_ERROR.code());
+                  });
+                  ctx.completeNow();
+              }));
+    }
+
+    @Test
+    void testInvalidState(VertxTestContext ctx)
+    {
+        WebClient client = WebClient.create(vertx);
+        JsonObject payload = JsonObject.of("state", "invalid");
+        client.put(server.actualPort(), "127.0.0.1", 
"/api/v1/cassandra/lifecycle")
+              .sendBuffer(payload.toBuffer(), ctx.succeeding(resp -> {
+                  ctx.verify(() -> {
+                      
assertThat(resp.statusCode()).isEqualTo(BAD_REQUEST.code());
+                      verify(mockLifecycleManager, 
times(0)).updateDesiredState("127.0.0.1", LifecycleCassandraState.RUNNING);
+                      verify(mockLifecycleManager, 
times(0)).updateDesiredState("127.0.0.1", LifecycleCassandraState.STOPPED);
+                  });
+                  ctx.completeNow();
+              }));
+    }
+
+    @Test
+    void testSubmitTaskAlreadyInProgress(VertxTestContext ctx) throws 
LifecycleTaskConflictException
+    {
+        // Setup mock to throw conflict exception
+        doThrow(new LifecycleTaskConflictException("Cannot start host 
127.0.0.1. Task already in progress for this host."))
+        .when(mockLifecycleManager).updateDesiredState("127.0.0.1", 
LifecycleCassandraState.RUNNING);
+
+        WebClient client = WebClient.create(vertx);
+        JsonObject payload = JsonObject.of("state", "start");
+        client.put(server.actualPort(), "127.0.0.1", 
"/api/v1/cassandra/lifecycle")
+              .sendBuffer(payload.toBuffer(), ctx.succeeding(resp -> {
+                  ctx.verify(() -> {
+                      assertThat(resp.statusCode()).isEqualTo(CONFLICT.code());
+                      verify(mockLifecycleManager, 
times(1)).updateDesiredState("127.0.0.1", LifecycleCassandraState.RUNNING);
+                  });
+                  ctx.completeNow();
+              }));
+    }
+
+    /**
+     * Test guice module for {@link LifecycleUpdateHandler} tests
+     */
+    class LifecycleUpdateHandlerTestModule extends AbstractModule
+    {
+
+        @Provides
+        @Singleton
+        public LifecycleManager intentManager()

Review Comment:
   nit: should the method be named `lifecycleManager()`? 



##########
server/src/main/java/org/apache/cassandra/sidecar/modules/SidecarModules.java:
##########
@@ -61,7 +61,8 @@ public static List<Module> all(@Nullable Path confPath)
                        new UtilitiesModule(),
                        new MultiBindingTypeResolverModule(),
                        new LiveMigrationModule(),
-                       new OpenApiModule());
+                       new OpenApiModule(),
+                       new LifecycleModule());

Review Comment:
   nit: the list of modules used to alphabetically ordered.



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to