kunwp1 commented on code in PR #4484:
URL: https://github.com/apache/texera/pull/4484#discussion_r3149226734


##########
frontend/src/app/workspace/component/power-button/computing-unit-selection.component.ts:
##########
@@ -637,4 +660,241 @@ export class ComputingUnitSelectionComponent implements 
OnInit {
       this.computingUnitStatusService.refreshComputingUnitList();
     }
   }
+
+  private makeEmptyPve(expanded: boolean): PveDraft {
+    return {
+      name: "",
+      pipOutput: "",
+      prettyPipOutput: "",
+      expanded,
+      isInstalling: false,
+    };
+  }
+
+  trackByIndex(index: number): number {
+    return index;
+  }
+
+  addEnvironment(): void {
+    this.pves.push(this.makeEmptyPve(true));
+  }
+
+  showPVEmodalVisible(): void {
+    this.pveModalVisible = true;
+    this.getPVEs();
+  }
+
+  closePveModal(): void {
+    this.pves.forEach(pve => {
+      pve.socket?.close();
+      pve.socket = undefined;
+      pve.isInstalling = false;
+    });
+
+    this.pveModalVisible = false;
+  }
+
+  getPVEs(): void {
+    const cuId = this.selectedComputingUnit?.computingUnit.cuid;
+
+    if (cuId == null) {
+      this.notificationService.error("No computing unit selected.");

Review Comment:
   I don't understand on how to reproduce this notification error. Can you 
explain me a test scenario so I can test it? Please test it before providing 
the scenario. Also, the error message isn't very friendly because at this point 
the user selected the computing unit.



##########
amber/src/main/scala/org/apache/texera/web/TexeraWebApplication.scala:
##########


Review Comment:
   Revert this change.



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResource.scala:
##########
@@ -0,0 +1,79 @@
+/*
+ * 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.texera.web.resource.pythonvirtualenvironment
+
+import javax.websocket._
+import javax.websocket.server.ServerEndpoint
+import java.util.concurrent.LinkedBlockingQueue
+import scala.concurrent.Future
+import scala.concurrent.ExecutionContext.Implicits.global
+
+@ServerEndpoint("/wsapi/pve")
+class PveWebsocketResource {
+
+  @OnOpen
+  def onOpen(session: Session): Unit = {
+
+    val params = session.getRequestParameterMap
+
+    val cuid = params.get("cuid").get(0).toInt
+    val pveName = params.get("pveName").get(0)
+
+    val queue = new LinkedBlockingQueue[String]()
+
+    // Run PVE creation in background
+    Future {
+      try {
+        PveManager.createNewPve(cuid, queue, pveName)
+      } catch {
+        case e: Exception =>
+          queue.put(s"[ERR] ${e.getMessage}")
+      } finally {
+        queue.put("__DONE__")
+      }
+    }
+
+    // Stream logs to frontend
+    Future {
+      var done = false
+
+      while (!done && session.isOpen) {
+        val line = queue.take()
+
+        session.getBasicRemote.sendText(line)
+
+        if (line == "__DONE__") {
+          done = true
+          session.close()
+        }
+      }
+    }
+  }
+
+  @OnError
+  def onError(session: Session, throwable: Throwable): Unit = {
+    println(s"[PVE WS ERROR] ${throwable.getMessage}")
+  }
+
+  @OnClose
+  def onClose(session: Session): Unit = {
+    println("[PVE WS CLOSED]")
+  }
+}

Review Comment:
   Remove them because the messages aren't very descriptive and useful.



##########
frontend/src/app/workspace/component/power-button/computing-unit-selection.component.ts:
##########
@@ -637,4 +660,241 @@ export class ComputingUnitSelectionComponent implements 
OnInit {
       this.computingUnitStatusService.refreshComputingUnitList();
     }
   }
+
+  private makeEmptyPve(expanded: boolean): PveDraft {
+    return {
+      name: "",
+      pipOutput: "",
+      prettyPipOutput: "",
+      expanded,
+      isInstalling: false,
+    };
+  }
+
+  trackByIndex(index: number): number {
+    return index;
+  }
+
+  addEnvironment(): void {
+    this.pves.push(this.makeEmptyPve(true));
+  }
+
+  showPVEmodalVisible(): void {
+    this.pveModalVisible = true;
+    this.getPVEs();
+  }
+
+  closePveModal(): void {
+    this.pves.forEach(pve => {
+      pve.socket?.close();
+      pve.socket = undefined;
+      pve.isInstalling = false;
+    });
+
+    this.pveModalVisible = false;
+  }
+
+  getPVEs(): void {
+    const cuId = this.selectedComputingUnit?.computingUnit.cuid;
+
+    if (cuId == null) {
+      this.notificationService.error("No computing unit selected.");
+      return;
+    }
+
+    this.workflowPveService
+      .fetchPVEs(cuId)
+      .pipe(untilDestroyed(this))
+      .subscribe({
+        next: (resp: PvePackageResponse[]) => {
+          this.pves = resp.map(pve => ({
+            name: pve.pveName,
+            expanded: false,
+            isInstalling: false,
+            pipOutput: "",
+            prettyPipOutput: "",
+          }));
+
+          if (resp.length > 0) {
+            this.workflowPveService
+              .getInstalledPackages(cuId, resp[0].pveName)
+              .pipe(untilDestroyed(this))
+              .subscribe({
+                next: installedResp => {
+                  this.systemPackages = installedResp.system.map(pkgStr => {
+                    const [name, version] = pkgStr.split("==");
+                    return {
+                      name: name.trim(),
+                      version: (version ?? "").trim(),
+                    };
+                  });
+                },
+                error: (err: unknown) => {
+                  console.error("Failed to fetch system packages:", err);
+                  this.systemPackages = [];
+                },
+              });
+          } else {
+            this.systemPackages = [];
+          }
+        },
+        error: (err: unknown) => {
+          console.error("Failed to fetch PVEs:", err);
+          this.pves = [];
+          this.systemPackages = [];
+        },
+      });
+  }
+
+  scrollToBottomOfPipModal(index: number) {
+    setTimeout(() => {
+      const pre = document.getElementById(`pip-log-${index}`) as HTMLElement | 
null;
+      if (pre) {
+        pre.scrollTop = pre.scrollHeight;
+      }
+    }, 50);
+  }
+
+  // Converts raw pip output for UI rendering by escaping unsafe characters and
+  // applying styling to exit codes, errors, warnings, and common success 
messages.
+  updatePrettyPipOutput(index: number) {
+    const env = this.pves[index];
+
+    const escapeHtml = (s: string) =>
+      s
+        .replace(/&/g, "&")
+        .replace(/</g, "&lt;")
+        .replace(/>/g, "&gt;")
+        .replace(/"/g, "&quot;")
+        .replace(/'/g, "&#39;");
+
+    const raw = env.pipOutput ?? "";
+    const safe = escapeHtml(raw);
+
+    env.prettyPipOutput = safe
+      .replace(/^(\[pip\].*finished with exit code\s+0.*)$/gm, "<span 
class=\"pip-exit ok\"><strong>$1</strong></span>")
+      .replace(/^(\[pip\].*finished with exit code\s+1.*)$/gm, "<span 
class=\"pip-exit err\"><strong>$1</strong></span>")
+      .replace(
+        /^(\[pip\].*finished with exit code\s+([2-9]\d*).*)$/gm,
+        "<span class=\"pip-exit err\"><strong>$1</strong></span>"
+      )
+      .replace(/ERROR/g, "<span class=\"error\">ERROR</span>")
+      .replace(/WARNING/g, "<span class=\"warning\">WARNING</span>")
+      .replace(/already satisfied/g, "<span class=\"success\">already 
satisfied</span>")
+      .replace(/\n/g, "<br/>");
+  }
+
+  createVirtualEnvironment(index: number): void {
+    const cuId = this.selectedComputingUnit?.computingUnit.cuid;
+    const env = this.pves[index];
+
+    if (cuId == null) {
+      this.notificationService.error("No computing unit selected.");

Review Comment:
   Same here.



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveManager.scala:
##########
@@ -0,0 +1,329 @@
+/*
+ * 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.texera.web.resource.pythonvirtualenvironment
+
+import java.nio.file.{Files, Path, Paths, StandardOpenOption}
+import java.util.concurrent.BlockingQueue
+import scala.collection.mutable.Map
+import scala.jdk.CollectionConverters._
+import scala.sys.process._
+import java.util.Comparator
+
+/**
+  * PveManager is responsible for managing Python Virtual Environments (PVEs)
+  * for each Computing Unit
+  *
+  * It supports:
+  * - Creating and initializing isolated Python environments
+  * - Installing and uninstalling Python packages
+  * - Tracking system vs user-installed packages via metadata files
+  * - Streaming pip output logs back to the caller
+  *
+  * Each PVE is stored under:
+  *   /tmp/texera-pve/venvs/{cuid}/{pveName}/
+  *
+  * The structure includes:
+  * - pve/              -> actual virtual environment
+  * - metadata/         -> package tracking (system + user)
+  */
+
+object PveManager {
+
+  private val VenvRoot: Path = Paths.get("/tmp/texera-pve/venvs")
+
+  private def cuidDir(cuid: Int, pveName: String): Path = {
+    VenvRoot.resolve(cuid.toString).resolve(pveName)
+  }
+
+  private def pveDir(cuid: Int, pveName: String): Path =
+    cuidDir(cuid, pveName).resolve("pve")
+
+  private def pythonBinPath(cuid: Int, pveName: String): Path =
+    pveDir(cuid, pveName).resolve("bin").resolve("python")
+
+  private def metadataDir(cuid: Int, pveName: String): Path =
+    pveDir(cuid, pveName).resolve("metadata")
+
+  private def systemPackagesPath(cuid: Int, pveName: String): Path =
+    metadataDir(cuid, pveName).resolve("system-packages.txt")
+
+  private def writeMetadata(path: Path, lines: Seq[String]): Unit = {
+    if (path.getParent != null) {
+      Files.createDirectories(path.getParent)
+    }
+    Files.write(
+      path,
+      lines.asJava,
+      StandardOpenOption.CREATE,
+      StandardOpenOption.TRUNCATE_EXISTING,
+      StandardOpenOption.WRITE
+    )
+  }
+
+  private def readMetadataList(path: Path): List[String] = {
+    if (!Files.exists(path)) return Nil
+    Files.readAllLines(path).asScala.map(_.trim).filter(_.nonEmpty).toList
+  }
+
+  private def pipEnv: Map[String, String] =
+    Map(
+      "PYTHONUNBUFFERED" -> "1",
+      "PIP_PROGRESS_BAR" -> "off",
+      "PIP_DISABLE_PIP_VERSION_CHECK" -> "1",
+      "PIP_NO_INPUT" -> "1"
+    )
+
+  def getSystemPackages(cuid: Int, pveName: String): (Seq[String]) = {
+    val sys = readMetadataList(systemPackagesPath(cuid, pveName))
+    (sys)
+  }
+
+  /**
+    * Creates a new PVE for a CU.
+    *
+    * Behavior:
+    * - If a base PVE exists (PVE_BASE), it clones it for faster setup
+    * - Otherwise, creates a fresh venv and installs dependencies
+    *
+    * Steps:
+    * 1. Create or copy base environment
+    * 2. Install system + operator dependencies
+    * 3. Record installed packages as system metadata
+    *
+    * Logs progress to the provided queue.
+    */
+  def createNewPve(cuid: Int, queue: BlockingQueue[String], pveName: String): 
Unit = {
+    queue.put(s"[PVE] Creating new PVE for cuid=$cuid with name=$pveName")
+
+    val venvDirPath = pveDir(cuid, pveName).toAbsolutePath
+    val python = pythonBinPath(cuid, pveName).toAbsolutePath.toString
+    val envVars = pipEnv
+
+    val pveBase = sys.env.getOrElse("PVE_BASE", "/opt/pve-base")
+    val basePython = Paths.get(pveBase).resolve("bin").resolve("python")
+    val hasBasePve = Files.exists(basePython)
+
+    val requirementsPath =
+      if (!hasBasePve) Paths.get("amber", "requirements.txt")
+      else Paths.get("/tmp", "requirements.txt")
+
+    val operatorRequirementsPath =
+      if (!hasBasePve) Paths.get("amber", "operator-requirements.txt")
+      else Paths.get("/tmp", "operator-requirements.txt")
+
+    if (!hasBasePve) {
+      Files.createDirectories(venvDirPath.getParent)
+
+      val createCode = Process(Seq("python3", "-m", "venv", 
venvDirPath.toString)).!(

Review Comment:
   I see that you are using default python3 path but in `udf.conf`, we can 
specify the python3 path. We should use that path instead of a default python3. 
Please refer to `PythonWorkflowWorker.scala` and mimic how it uses the python3 
path from `udf.conf`. I suggest you to refactor that code snippet to reduce 
duplicate codes. 



##########
frontend/src/app/workspace/component/power-button/computing-unit-selection.component.ts:
##########
@@ -637,4 +669,255 @@ export class ComputingUnitSelectionComponent implements 
OnInit {
       this.computingUnitStatusService.refreshComputingUnitList();
     }
   }
+
+  private makeEmptyPve(expanded: boolean): PveDraft {

Review Comment:
   Better to inline this function because it's only called once.



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveWebsocketResource.scala:
##########


Review Comment:
   I am guessing you added this web socket after a first pass. Can you explain 
why you added this and why do we need two connections: web socket and http 
endpoints?



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