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


##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveManager.scala:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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
+import org.apache.texera.amber.config.UdfConfig
+
+/**
+  * 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))

Review Comment:
   I don't think we even need `system-packages.txt` file. Just simply run 
`python -m  pip freeze` (the python binary should be the one from `udf.conf`) 
and we get all the system packages. In that case, we can show the system 
packages in the frontend without creating a virtual environment. I don't think 
running pip freeze is an expensive operation. I think this is much cleaner and 
more intuitive. What do you think?



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveManager.scala:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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
+import org.apache.texera.amber.config.UdfConfig
+
+/**
+  * 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:
+    * Creates a fresh venv and installs dependencies
+    *
+    * Steps:
+    * 2. Install system dependencies
+    * 3. Record installed packages as system metadata
+    *
+    * Logs progress to the provided queue.
+    */
+  def createNewPve(
+      cuid: Int,
+      queue: BlockingQueue[String],
+      pveName: String,
+      isLocal: Boolean
+  ): 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 pythonPath = UdfConfig.pythonPath.trim
+    val createVenvPython = if (pythonPath.isEmpty) "python3" else pythonPath
+
+    val requirementsPath =
+      if (isLocal) Paths.get("amber", "requirements.txt")
+      else Paths.get("/tmp", "requirements.txt")

Review Comment:
   This path is based on the path from `computing-unit-master.dockerfile`. Add 
a comment that this path is based on `computing-unit-master.dockerfile` and 
needs to be updated when `computing-unit-master.dockerfile` changes the path of 
the requirements.txt file.



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveManager.scala:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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
+import org.apache.texera.amber.config.UdfConfig
+
+/**
+  * 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:
+    * Creates a fresh venv and installs dependencies
+    *
+    * Steps:
+    * 2. Install system dependencies
+    * 3. Record installed packages as system metadata
+    *
+    * Logs progress to the provided queue.
+    */
+  def createNewPve(
+      cuid: Int,
+      queue: BlockingQueue[String],
+      pveName: String,
+      isLocal: Boolean
+  ): 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 pythonPath = UdfConfig.pythonPath.trim
+    val createVenvPython = if (pythonPath.isEmpty) "python3" else pythonPath
+
+    val requirementsPath =
+      if (isLocal) Paths.get("amber", "requirements.txt")
+      else Paths.get("/tmp", "requirements.txt")
+
+    val operatorRequirementsPath =
+      if (isLocal) Paths.get("amber", "operator-requirements.txt")
+      else Paths.get("/tmp", "operator-requirements.txt")
+
+    Files.createDirectories(venvDirPath.getParent)
+
+    val createCode = Process(Seq(createVenvPython, "-m", "venv", 
venvDirPath.toString)).!(
+      ProcessLogger(
+        out => queue.put(s"[pve] $out"),
+        err => queue.put(s"[pve][ERR] $err")
+      )
+    )
+
+    queue.put(s"[pve] venv creation finished with exit code $createCode")
+
+    if (createCode != 0) {
+      queue.put(s"[PVE][ERR] Failed to create venv (exit=$createCode)")
+      return
+    }
+
+    if (!Files.exists(requirementsPath)) {
+      queue.put(s"[PVE][ERR] requirements.txt not found at 
${requirementsPath.toAbsolutePath}")
+      return
+    }
+
+    if (!Files.exists(operatorRequirementsPath)) {
+      queue.put(
+        s"[PVE][ERR] operator-requirements.txt not found at 
${operatorRequirementsPath.toAbsolutePath}"
+      )
+      return
+    }
+
+    Files.createDirectories(metadataDir(cuid, pveName))
+
+    queue.put(s"[PVE] Installing requirements from 
${requirementsPath.toAbsolutePath}")
+
+    val installReqCode = Process(
+      Seq(
+        python,
+        "-u",
+        "-m",
+        "pip",
+        "install",
+        "--progress-bar",
+        "off",
+        "-r",
+        requirementsPath.toString
+      ),
+      None,
+      envVars.toSeq: _*
+    ).!(
+      ProcessLogger(
+        out => queue.put(s"[pip] $out"),
+        err => queue.put(s"[pip][ERR] $err")
+      )
+    )
+
+    queue.put(s"[PVE] requirements install finished with exit code 
$installReqCode")
+
+    if (installReqCode != 0) {
+      queue.put(s"[PVE][ERR] Failed to install requirements.txt 
(exit=$installReqCode)")
+      return
+    }
+
+    queue.put(
+      s"[PVE] Installing operator requirements from 
${operatorRequirementsPath.toAbsolutePath}"
+    )
+
+    val installOperatorReqCode = Process(
+      Seq(
+        python,
+        "-u",
+        "-m",
+        "pip",
+        "install",
+        "--progress-bar",
+        "off",
+        "-r",
+        operatorRequirementsPath.toString
+      ),
+      None,
+      envVars.toSeq: _*
+    ).!(
+      ProcessLogger(
+        out => queue.put(s"[pip] $out"),
+        err => queue.put(s"[pip][ERR] $err")
+      )
+    )
+
+    queue.put(
+      s"[PVE] operator requirements install finished with exit code 
$installOperatorReqCode"
+    )
+
+    if (installOperatorReqCode != 0) {
+      queue.put(
+        s"[PVE][ERR] Failed to install operator-requirements.txt 
(exit=$installOperatorReqCode)"
+      )
+      return
+    }
+
+    queue.put("[PVE] Running pip freeze")
+
+    val freezeOutput = Process(Seq(python, "-m", "pip", "freeze"), None, 
envVars.toSeq: _*).!!
+    val installedLines = 
freezeOutput.split("\n").map(_.trim).filter(_.nonEmpty).toSeq
+
+    writeMetadata(systemPackagesPath(cuid, pveName), installedLines)

Review Comment:
   We can remove metadata folder and metadata-related methods if you agree on 
my comment above.



##########
frontend/src/app/workspace/component/power-button/computing-unit-selection.component.html:
##########
@@ -427,3 +435,127 @@
     </div>
   </div>
 </ng-template>
+
+<!-- Modal for adding packages -->
+<nz-modal
+  nzWrapClassName="pve-modal"
+  nzClassName="pve-modal"
+  [nzVisible]="pveModalVisible"
+  nzTitle="Python Environments"
+  (nzOnCancel)="closePveModal()"
+  [nzFooter]="customFooter">
+  <ng-template #customFooter>
+    <div class="footer-all">
+      <button
+        nz-button
+        nzType="default"
+        (click)="closePveModal()">
+        Close
+      </button>
+      <button
+        nz-button
+        nzType="primary"
+        (click)="addEnvironment()">
+        Add Environment
+      </button>
+    </div>
+  </ng-template>
+
+  <ng-container *nzModalContent>
+    <!-- Shared system packages -->
+    <div class="system-section">
+      <nz-collapse>
+        <ng-template #systemHeaderTpl>
+          <div class="system-header">
+            <div class="title">System Packages (read-only)</div>
+            <div class="subtitle">Packages will appear here after an 
environment is created.</div>
+          </div>
+        </ng-template>
+        <nz-collapse-panel [nzHeader]="systemHeaderTpl">
+          <div class="system-panel-inner">
+            <div
+              *ngFor="let pkg of systemPackages"
+              class="package-row system-row">
+              <div class="package-inputs">
+                <div class="field">
+                  <label>Package</label>

Review Comment:
   One suggestion on the UI improvement: Instead of showing the two labels 
"Package" and "Version" redundantly for each package, just show labels once and 
then list all the packages and version below (also remove vertical spaces 
between packages) so that the UI can be more compact and less scroll-down for 
the users.



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveManager.scala:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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
+import org.apache.texera.amber.config.UdfConfig
+
+/**
+  * 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:
+    * Creates a fresh venv and installs dependencies
+    *
+    * Steps:
+    * 2. Install system dependencies
+    * 3. Record installed packages as system metadata
+    *
+    * Logs progress to the provided queue.
+    */
+  def createNewPve(
+      cuid: Int,
+      queue: BlockingQueue[String],
+      pveName: String,
+      isLocal: Boolean
+  ): 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 pythonPath = UdfConfig.pythonPath.trim
+    val createVenvPython = if (pythonPath.isEmpty) "python3" else pythonPath
+
+    val requirementsPath =
+      if (isLocal) Paths.get("amber", "requirements.txt")
+      else Paths.get("/tmp", "requirements.txt")
+
+    val operatorRequirementsPath =
+      if (isLocal) Paths.get("amber", "operator-requirements.txt")
+      else Paths.get("/tmp", "operator-requirements.txt")

Review Comment:
   ditto



##########
amber/src/main/scala/org/apache/texera/web/resource/pythonvirtualenvironment/PveManager.scala:
##########
@@ -0,0 +1,282 @@
+/*
+ * 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
+import org.apache.texera.amber.config.UdfConfig
+
+/**
+  * 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:
+    * Creates a fresh venv and installs dependencies
+    *
+    * Steps:
+    * 2. Install system dependencies
+    * 3. Record installed packages as system metadata
+    *
+    * Logs progress to the provided queue.
+    */
+  def createNewPve(
+      cuid: Int,
+      queue: BlockingQueue[String],
+      pveName: String,
+      isLocal: Boolean
+  ): 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 pythonPath = UdfConfig.pythonPath.trim
+    val createVenvPython = if (pythonPath.isEmpty) "python3" else pythonPath
+
+    val requirementsPath =
+      if (isLocal) Paths.get("amber", "requirements.txt")
+      else Paths.get("/tmp", "requirements.txt")
+
+    val operatorRequirementsPath =
+      if (isLocal) Paths.get("amber", "operator-requirements.txt")
+      else Paths.get("/tmp", "operator-requirements.txt")
+
+    Files.createDirectories(venvDirPath.getParent)
+
+    val createCode = Process(Seq(createVenvPython, "-m", "venv", 
venvDirPath.toString)).!(
+      ProcessLogger(
+        out => queue.put(s"[pve] $out"),
+        err => queue.put(s"[pve][ERR] $err")
+      )
+    )
+
+    queue.put(s"[pve] venv creation finished with exit code $createCode")
+
+    if (createCode != 0) {
+      queue.put(s"[PVE][ERR] Failed to create venv (exit=$createCode)")
+      return
+    }
+
+    if (!Files.exists(requirementsPath)) {
+      queue.put(s"[PVE][ERR] requirements.txt not found at 
${requirementsPath.toAbsolutePath}")
+      return
+    }
+
+    if (!Files.exists(operatorRequirementsPath)) {
+      queue.put(
+        s"[PVE][ERR] operator-requirements.txt not found at 
${operatorRequirementsPath.toAbsolutePath}"
+      )
+      return
+    }
+
+    Files.createDirectories(metadataDir(cuid, pveName))
+
+    queue.put(s"[PVE] Installing requirements from 
${requirementsPath.toAbsolutePath}")
+
+    val installReqCode = Process(
+      Seq(
+        python,
+        "-u",
+        "-m",
+        "pip",
+        "install",
+        "--progress-bar",
+        "off",
+        "-r",
+        requirementsPath.toString
+      ),
+      None,
+      envVars.toSeq: _*
+    ).!(
+      ProcessLogger(
+        out => queue.put(s"[pip] $out"),
+        err => queue.put(s"[pip][ERR] $err")
+      )
+    )
+
+    queue.put(s"[PVE] requirements install finished with exit code 
$installReqCode")
+
+    if (installReqCode != 0) {
+      queue.put(s"[PVE][ERR] Failed to install requirements.txt 
(exit=$installReqCode)")
+      return
+    }
+
+    queue.put(
+      s"[PVE] Installing operator requirements from 
${operatorRequirementsPath.toAbsolutePath}"
+    )
+
+    val installOperatorReqCode = Process(
+      Seq(
+        python,
+        "-u",
+        "-m",
+        "pip",
+        "install",
+        "--progress-bar",
+        "off",
+        "-r",
+        operatorRequirementsPath.toString
+      ),
+      None,
+      envVars.toSeq: _*
+    ).!(

Review Comment:
   Merge this command with line 166. You can install both .txt files in a 
single command. Then you can remove all the redundant codes below.



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