daemon: updated environment reading to leverage pathlib, also added .coregui user environment as a possibility

This commit is contained in:
Blake Harnden 2020-10-11 08:22:33 -07:00
parent ae336c2cf8
commit ea44f1b6e7
2 changed files with 25 additions and 25 deletions

View file

@ -12,6 +12,7 @@ import sys
import tempfile import tempfile
import threading import threading
import time import time
from pathlib import Path
from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, TypeVar from typing import Any, Callable, Dict, List, Optional, Set, Tuple, Type, TypeVar
from core import constants, utils from core import constants, utils
@ -978,15 +979,6 @@ class Session:
corexmldeployment.CoreXmlDeployment(self, xml_writer.scenario) corexmldeployment.CoreXmlDeployment(self, xml_writer.scenario)
xml_writer.write(xml_file_name) xml_writer.write(xml_file_name)
@staticmethod
def merge_environment(f, env, title):
try:
if os.path.isfile(f):
utils.load_config(f, env)
except IOError:
logging.warning(f"{title} file does not exist: {f}")
return env
def get_environment(self, state: bool = True) -> Dict[str, str]: def get_environment(self, state: bool = True) -> Dict[str, str]:
""" """
Get an environment suitable for a subprocess.Popen call. Get an environment suitable for a subprocess.Popen call.
@ -1007,16 +999,25 @@ class Session:
if state: if state:
env["SESSION_STATE"] = str(self.state) env["SESSION_STATE"] = str(self.state)
# try reading and merging optional environments from: # try reading and merging optional environments from:
# /etc/core/environment # /etc/core/environment
# /home/user/.core/environment # /home/user/.core/environment
# /tmp/session.nnnnn/environment # /tmp/pycore.<session id>/environment
env_file = os.path.join(constants.CORE_CONF_DIR, "environment") core_env_path = Path(constants.CORE_CONF_DIR) / "environment"
env = self.merge_environment(env_file, env, "environment configuration") session_env_path = Path(self.session_dir) / "environment"
if self.user: if self.user:
env_user_file = os.path.join("/home", self.user, ".core", "environment") user_home_path = Path(f"~{self.user}").expanduser()
env = self.merge_environment(env_user_file, env, "user environemnt") user_env1 = user_home_path / ".core" / "environment"
session_env_file = os.path.join(self.session_dir, "environment") user_env2 = user_home_path / ".coregui" / "environment"
env = self.merge_environment(session_env_file, env, "session environemnt") paths = [core_env_path, user_env1, user_env2, session_env_path]
else:
paths = [core_env_path, session_env_path]
for path in paths:
if path.is_file():
try:
logging.info("loading environment config: %s", path)
utils.load_config(path, env)
except IOError:
logging.exception("error reading environment file: %s", path)
return env return env
def set_thumbnail(self, thumb_file: str) -> None: def set_thumbnail(self, thumb_file: str) -> None:

View file

@ -15,6 +15,7 @@ import random
import shlex import shlex
import shutil import shutil
import sys import sys
from pathlib import Path
from subprocess import PIPE, STDOUT, Popen from subprocess import PIPE, STDOUT, Popen
from typing import ( from typing import (
TYPE_CHECKING, TYPE_CHECKING,
@ -315,27 +316,25 @@ def sysctl_devname(devname: str) -> Optional[str]:
return devname.replace(".", "/") return devname.replace(".", "/")
def load_config(filename: str, d: Dict[str, str]) -> None: def load_config(file_path: Path, d: Dict[str, str]) -> None:
""" """
Read key=value pairs from a file, into a dict. Skip comments; strip newline Read key=value pairs from a file, into a dict. Skip comments; strip newline
characters and spacing. characters and spacing.
:param filename: file to read into a dictionary :param file_path: file path to read data from
:param d: dictionary to read file into :param d: dictionary to config into
:return: nothing :return: nothing
""" """
with open(filename, "r") as f: with file_path.open("r") as f:
lines = f.readlines() lines = f.readlines()
for line in lines: for line in lines:
if line[:1] == "#": if line[:1] == "#":
continue continue
try: try:
key, value = line.split("=", 1) key, value = line.split("=", 1)
d[key] = value.strip() d[key] = value.strip()
except ValueError: except ValueError:
logging.exception("error reading file to dict: %s", filename) logging.exception("error reading file to dict: %s", file_path)
def load_classes(path: str, clazz: Generic[T]) -> T: def load_classes(path: str, clazz: Generic[T]) -> T: