Pochatkin commented on code in PR #7122:
URL: https://github.com/apache/ignite-3/pull/7122#discussion_r2642336126


##########
examples/java/src/main/java/org/apache/ignite/example/util/DeployComputeUnit.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * 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.ignite.example.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+
+/**
+ * Utility class for building and deploying Ignite compute units.
+ */
+public class DeployComputeUnit {
+
+    private static final String BASE_URL = "http://localhost:10300";;
+    private static final HttpClient HTTP = HttpClient.newHttpClient();
+
+    /**
+     * Builds a JAR file by packaging all compiled classes present in the 
given directory.
+     *
+     * @param classesDir Directory containing compiled .class files.
+     * @param jarPath Target JAR file path to create.
+     * @throws IOException If building the JAR fails.
+     */
+    public static void buildJar(Path classesDir, Path jarPath) throws 
IOException {
+        if (!Files.exists(classesDir)) {
+            throw new IllegalArgumentException("Compiled classes not found: " 
+ classesDir);
+        }
+
+        Files.createDirectories(jarPath.getParent());
+
+        try (OutputStream fos = Files.newOutputStream(jarPath);
+                JarOutputStream jar = new JarOutputStream(fos, 
createManifest())) {
+
+            Files.walk(classesDir).filter(Files::isRegularFile).forEach(path 
-> {
+                String entry = 
classesDir.relativize(path).toString().replace("\\", "/");
+                try (InputStream is = Files.newInputStream(path)) {
+                    jar.putNextEntry(new JarEntry(entry));
+                    is.transferTo(jar);
+                    jar.closeEntry();
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+            });
+        }
+
+        System.out.println("JAR built: " + jarPath);
+    }
+
+    /**
+     * Creates a simple manifest declaring manifest version.
+     *
+     * @return Manifest object.
+     */
+    private static Manifest createManifest() {
+        Manifest m = new Manifest();
+        m.getMainAttributes().putValue("Manifest-Version", "1.0");
+        return m;
+    }
+
+    /**
+     * Deploys a unit only if it is not already deployed.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @param jar Path to the JAR file.
+     * @throws Exception If deployment fails.
+     */
+    public static void deployUnitIfNeeded(String unitId, String version, Path 
jar) throws Exception {
+        if (deploymentExists(unitId, version)) {
+            System.out.println("Deployment unit already active. Skipping 
deployment.");
+            return;
+        }
+        deployUnit(unitId, version, jar);
+        System.out.println("Deployment completed.");
+    }
+
+    /**
+     * Checks if a deployment unit already exists on the cluster.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @return True if active deployment exists.
+     * @throws Exception If request fails.
+     */
+    public static boolean deploymentExists(String unitId, String version) 
throws Exception {
+        HttpRequest req = HttpRequest.newBuilder()
+                .uri(new URI(BASE_URL + 
"/management/v1/deployment/cluster/units/" + unitId))
+                .GET().build();
+
+        HttpResponse<String> resp = HTTP.send(req, 
HttpResponse.BodyHandlers.ofString());
+        return resp.statusCode() == 200 && 
resp.body().contains("\"version\":\"" + version + "\"");
+    }
+
+    /**
+     * Deploys a unit to the Ignite cluster.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @param jar Path to the JAR file to upload.
+     * @throws Exception If deployment fails.
+     */
+    public static void deployUnit(String unitId, String version, Path jar) 
throws Exception {
+        String boundary = "igniteBoundary";
+
+        byte[] jarBytes = Files.readAllBytes(jar);
+
+        String start =
+                "--" + boundary + "\r\n" +
+                        "Content-Disposition: form-data; name=\"unitContent\"; 
filename=\"" + jar.getFileName() + "\"\r\n" +
+                        "Content-Type: application/java-archive\r\n\r\n";
+
+        String end = "\r\n--" + boundary + "--\r\n";
+
+        byte[] startBytes = start.getBytes();
+        byte[] endBytes = end.getBytes();
+
+        byte[] full = new byte[startBytes.length + jarBytes.length + 
endBytes.length];
+
+        System.arraycopy(startBytes, 0, full, 0, startBytes.length);
+        System.arraycopy(jarBytes, 0, full, startBytes.length, 
jarBytes.length);
+        System.arraycopy(endBytes, 0, full, startBytes.length + 
jarBytes.length, endBytes.length);
+
+        HttpRequest req = HttpRequest.newBuilder()
+                .uri(new URI(BASE_URL + "/management/v1/deployment/units/" + 
unitId + "/" + version + "?deployMode=ALL"))
+                .header("Content-Type", "multipart/form-data; boundary=" + 
boundary)
+                .POST(HttpRequest.BodyPublishers.ofByteArray(full))
+                .build();
+
+        HttpResponse<String> resp = HTTP.send(req, 
HttpResponse.BodyHandlers.ofString());
+
+        Thread.sleep(500);

Review Comment:
   What a reason for this sleep?



##########
examples/java/src/main/java/org/apache/ignite/example/code/deployment/AbstractDeploymentUnitExample.java:
##########
@@ -0,0 +1,57 @@
+package org.apache.ignite.example.code.deployment;
+
+import java.io.IOException;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.util.Map;
+import org.apache.ignite.example.util.DeployComputeUnit;
+
+public class AbstractDeploymentUnitExample {
+
+    // Root path of ignite-examples/
+    private static final Path projectRoot =
+            Paths.get("").toAbsolutePath();
+
+    // Compiled class output when running from IDE/CLI
+    private static final Path DEFAULT_CLASSES_DIR =
+            projectRoot.resolve("examples/java/build/classes/java/main");
+
+    // Default JAR output
+    private static final Path DEFAULT_JAR_PATH =
+            Path.of("build/libs/deploymentunit-example-1.0.0.jar");
+
+    protected static String jarPathAsString = "";
+    protected static Path jarPath = DEFAULT_JAR_PATH;
+    protected static boolean runFromIDE = true;
+    // ---------------------------------------------------
+
+    /**
+     * Processes the deployment unit.
+     *
+     * @param args Arguments passed to the deployment process.
+     * @throws IOException if any error occurs.
+     */
+    protected static void processDeploymentUnit(String[] args)
+            throws IOException {
+
+        Map<String, Object> p = DeployComputeUnit.processArguments(args);
+
+        boolean newRunFromIDE = (boolean) p.get("runFromIDE");
+        String newJarPathStr = (String) p.get("jarPath");
+
+        runFromIDE = newRunFromIDE;
+
+        // Use isBlank() instead of trim().isEmpty() to avoid creating a new 
String
+        if (newJarPathStr != null && !newJarPathStr.isBlank()) {
+            jarPathAsString = newJarPathStr;
+            jarPath = Path.of(newJarPathStr);
+        }
+
+        if (runFromIDE) {
+            DeployComputeUnit.buildJar(

Review Comment:
   Why do you build jar each time on runtime? Could you create a prebuilded jar 
and put it to resources? Or if you want to have unit code and work with it, 
then you need to achieve it in another way. Please take a look into 
`modules/compute` and how we manage units, espacially unit1 and unit2 source 
sets.



##########
examples/java/src/main/java/org/apache/ignite/example/util/DeployComputeUnit.java:
##########
@@ -0,0 +1,263 @@
+/*
+ * 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.ignite.example.util;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.OutputStream;
+import java.net.URI;
+import java.net.http.HttpClient;
+import java.net.http.HttpRequest;
+import java.net.http.HttpResponse;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.jar.JarEntry;
+import java.util.jar.JarOutputStream;
+import java.util.jar.Manifest;
+
+/**
+ * Utility class for building and deploying Ignite compute units.
+ */
+public class DeployComputeUnit {
+
+    private static final String BASE_URL = "http://localhost:10300";;
+    private static final HttpClient HTTP = HttpClient.newHttpClient();
+
+    /**
+     * Builds a JAR file by packaging all compiled classes present in the 
given directory.
+     *
+     * @param classesDir Directory containing compiled .class files.
+     * @param jarPath Target JAR file path to create.
+     * @throws IOException If building the JAR fails.
+     */
+    public static void buildJar(Path classesDir, Path jarPath) throws 
IOException {
+        if (!Files.exists(classesDir)) {
+            throw new IllegalArgumentException("Compiled classes not found: " 
+ classesDir);
+        }
+
+        Files.createDirectories(jarPath.getParent());
+
+        try (OutputStream fos = Files.newOutputStream(jarPath);
+                JarOutputStream jar = new JarOutputStream(fos, 
createManifest())) {
+
+            Files.walk(classesDir).filter(Files::isRegularFile).forEach(path 
-> {
+                String entry = 
classesDir.relativize(path).toString().replace("\\", "/");
+                try (InputStream is = Files.newInputStream(path)) {
+                    jar.putNextEntry(new JarEntry(entry));
+                    is.transferTo(jar);
+                    jar.closeEntry();
+                } catch (Exception e) {
+                    throw new RuntimeException(e);
+                }
+            });
+        }
+
+        System.out.println("JAR built: " + jarPath);
+    }
+
+    /**
+     * Creates a simple manifest declaring manifest version.
+     *
+     * @return Manifest object.
+     */
+    private static Manifest createManifest() {
+        Manifest m = new Manifest();
+        m.getMainAttributes().putValue("Manifest-Version", "1.0");
+        return m;
+    }
+
+    /**
+     * Deploys a unit only if it is not already deployed.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @param jar Path to the JAR file.
+     * @throws Exception If deployment fails.
+     */
+    public static void deployUnitIfNeeded(String unitId, String version, Path 
jar) throws Exception {
+        if (deploymentExists(unitId, version)) {
+            System.out.println("Deployment unit already active. Skipping 
deployment.");
+            return;
+        }
+        deployUnit(unitId, version, jar);
+        System.out.println("Deployment completed.");
+    }
+
+    /**
+     * Checks if a deployment unit already exists on the cluster.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @return True if active deployment exists.
+     * @throws Exception If request fails.
+     */
+    public static boolean deploymentExists(String unitId, String version) 
throws Exception {
+        HttpRequest req = HttpRequest.newBuilder()
+                .uri(new URI(BASE_URL + 
"/management/v1/deployment/cluster/units/" + unitId))
+                .GET().build();
+
+        HttpResponse<String> resp = HTTP.send(req, 
HttpResponse.BodyHandlers.ofString());
+        return resp.statusCode() == 200 && 
resp.body().contains("\"version\":\"" + version + "\"");
+    }
+
+    /**
+     * Deploys a unit to the Ignite cluster.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @param jar Path to the JAR file to upload.
+     * @throws Exception If deployment fails.
+     */
+    public static void deployUnit(String unitId, String version, Path jar) 
throws Exception {
+        String boundary = "igniteBoundary";
+
+        byte[] jarBytes = Files.readAllBytes(jar);
+
+        String start =
+                "--" + boundary + "\r\n" +
+                        "Content-Disposition: form-data; name=\"unitContent\"; 
filename=\"" + jar.getFileName() + "\"\r\n" +
+                        "Content-Type: application/java-archive\r\n\r\n";
+
+        String end = "\r\n--" + boundary + "--\r\n";
+
+        byte[] startBytes = start.getBytes();
+        byte[] endBytes = end.getBytes();
+
+        byte[] full = new byte[startBytes.length + jarBytes.length + 
endBytes.length];
+
+        System.arraycopy(startBytes, 0, full, 0, startBytes.length);
+        System.arraycopy(jarBytes, 0, full, startBytes.length, 
jarBytes.length);
+        System.arraycopy(endBytes, 0, full, startBytes.length + 
jarBytes.length, endBytes.length);
+
+        HttpRequest req = HttpRequest.newBuilder()
+                .uri(new URI(BASE_URL + "/management/v1/deployment/units/" + 
unitId + "/" + version + "?deployMode=ALL"))
+                .header("Content-Type", "multipart/form-data; boundary=" + 
boundary)
+                .POST(HttpRequest.BodyPublishers.ofByteArray(full))
+                .build();
+
+        HttpResponse<String> resp = HTTP.send(req, 
HttpResponse.BodyHandlers.ofString());
+
+        Thread.sleep(500);
+
+        if (resp.statusCode() != 200 && resp.statusCode() != 409) {
+            throw new RuntimeException("Deployment failed: " + 
resp.statusCode() + "\n" + resp.body());
+        }
+    }
+
+    /**
+     * Undeploys the given deployment unit from the cluster.
+     *
+     * @param unitId Deployment unit ID.
+     * @param version Deployment version.
+     * @throws Exception If undeployment fails.
+     */
+    public static void undeployUnit(String unitId, String version) throws 
Exception {
+        HttpRequest req = HttpRequest.newBuilder()
+                .uri(new URI(BASE_URL + "/management/v1/deployment/units/" + 
unitId + "/" + version))
+                .DELETE()
+                .build();
+
+        HttpResponse<String> resp = HTTP.send(req, 
HttpResponse.BodyHandlers.ofString());
+
+        if (resp.statusCode() != 200 && resp.statusCode() != 404) {
+            throw new RuntimeException("Undeploy failed: " + resp.statusCode() 
+ "\n" + resp.body());
+        }
+
+        for (int i = 0; i < 10; i++) {
+            if (!deploymentExists(unitId, version)) {
+                System.out.println("Unit successfully undeployed.");
+                return;
+            }
+            Thread.sleep(300);

Review Comment:
   What a reason for this sleep?



-- 
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]

Reply via email to