aboutsummaryrefslogtreecommitdiff
path: root/rwa/support/sessionservice/session.py
diff options
context:
space:
mode:
Diffstat (limited to 'rwa/support/sessionservice/session.py')
-rw-r--r--rwa/support/sessionservice/session.py61
1 files changed, 30 insertions, 31 deletions
diff --git a/rwa/support/sessionservice/session.py b/rwa/support/sessionservice/session.py
index 1dfb6bb..d6dbc82 100644
--- a/rwa/support/sessionservice/session.py
+++ b/rwa/support/sessionservice/session.py
@@ -24,18 +24,18 @@
# along with this program. If not, see <https://www.gnu.org/licenses/>.
import os
-import random
import secrets
import signal
import string
-import subprocess
-from typing import Dict, Union, Any
+import subprocess # noqa
+from typing import Dict, Union
import port_for
import psutil
import requests
from .config import settings
+from .lock import TEMP_DIR_PATH
from .log import logging
from .vnc import run_vnc, save_password
@@ -50,17 +50,13 @@ logging.info(f"Load API config: {API_SERVER}")
def random_digits(length: int):
- return "".join(random.choice(string.digits) for _ in range(length))
+ return "".join(secrets.choice(string.digits) for _ in range(length))
def get_desktop_dir():
"""Get desktop directory from xdg vars."""
- return (
- subprocess.check_output(["xdg-user-dir", "DESKTOP"])
- .decode()
- .strip()
- .replace("\n", "")
- )
+ output = subprocess.check_output(["xdg-user-dir", "DESKTOP"]).decode() # noqa
+ return output.strip().replace("\n", "")
class Session:
@@ -94,6 +90,12 @@ class Session:
def _api_headers(self) -> Dict[str, str]:
return {"Authorization": f"Token {self.api_token}"}
+ @property
+ def _mock_lock_file_path(self) -> str:
+ return os.path.join(
+ TEMP_DIR_PATH, f"{self.ws_port}-{self.vnc_port}-{self.ws_pid}-{self.vnc_pid}.lock",
+ )
+
def _generate_password(self):
"""Generate password for x11vnc and save it."""
self.password = secrets.token_urlsafe(20)
@@ -125,8 +127,7 @@ class Session:
logging.info("The lock file for mocking a VNC server has been created.")
# Create a temporary file to indicate that this process is still 'Running'
- filename = f"/tmp/rwa/{str(self.ws_port) + str(self.vnc_port) + str(self.ws_pid) + str(self.vnc_pid)}.lock"
- new_file = open(filename, "w")
+ new_file = open(self._mock_lock_file_path, "w")
new_file.write("this session is running")
def _register_session(self):
@@ -145,7 +146,8 @@ class Session:
raise ConnectionError()
logging.info(
- f"The session has been registered in RWA.Support.WebApp with status code {r.status_code} and response {r.content.decode()}."
+ "The session has been registered in RWA.Support.WebApp "
+ f"with status code {r.status_code} and response {r.content.decode()}."
)
if r.status_code != 200:
@@ -156,10 +158,10 @@ class Session:
self.web_url = self.meta["url"]
self.api_token = self.meta["token"]
else:
- logging.info(f"The session has pretended that he had created a session.")
+ logging.info("The session has pretended that he had created a session.")
self.meta = {}
self.session_id = int(random_digits(10))
- self.web_url = "http://example.com:" + random_digits(5) + "/app/rwasupport/test/"
+ self.web_url = f"http://example.com:{random_digits(5)}/app/rwasupport/test/"
self.api_token = secrets.token_urlsafe(10)
self.pin = int(random_digits(4))
@@ -174,8 +176,8 @@ class Session:
"trigger_token": self.trigger_token,
}
-
return False
+
def pull(self):
"""Update status: Get status from Django."""
if not self.mockup_session:
@@ -185,7 +187,8 @@ class Session:
)
logging.info(
- f"The session has received its status from RWA.Support.WebApp with status code {r.status_code} and response {r.content.decode()}."
+ "The session has received its status from RWA.Support.WebApp "
+ f"with status code {r.status_code} and response {r.content.decode()}."
)
except requests.ConnectionError:
pass
@@ -208,10 +211,8 @@ class Session:
def _do_file_job(self, job):
"""Download a file from server to the user's desktop."""
- logging.info(
- f"The session has received a file job and is downloading it now ({job}):"
- )
- subprocess.Popen(["wget", job["file"], "-P", self.desktop_dir])
+ logging.info(f"The session has received a file job and is downloading it now ({job}):")
+ subprocess.Popen(["wget", job["file"], "-P", self.desktop_dir]) # noqa
self._mark_job_as_done(job)
def _mark_job_as_done(self, job):
@@ -219,12 +220,11 @@ class Session:
self.done_jobs.append(job["job_id"])
try:
r = requests.post(
- MARK_JOB_AS_DONE_URL,
- params={"id": job["job_id"]},
- headers=self._api_headers,
+ MARK_JOB_AS_DONE_URL, params={"id": job["job_id"]}, headers=self._api_headers,
)
logging.info(
- f"The session has marked the job {job} as done in RWA.Support.WebApp with status code {r.status_code} and response {r.content.decode()}."
+ f"The session has marked the job {job} as done in RWA.Support.WebApp "
+ f"with status code {r.status_code} and response {r.content.decode()}."
)
except requests.ConnectionError:
pass
@@ -237,9 +237,8 @@ class Session:
"""Stop session and clean up."""
if self.mockup_session:
logging.info("Mock session has been stopped by deleting its lock file.")
- filename = f"/tmp/rwa/{str(self.ws_port) + str(self.vnc_port) + str(self.ws_pid) + str(self.vnc_pid)}.lock"
- if os.path.isfile(filename):
- os.remove(filename)
+ if os.path.isfile(self._mock_lock_file_path):
+ os.remove(self._mock_lock_file_path)
# Delete self
del self
@@ -268,7 +267,8 @@ class Session:
STOP_URL, params={"id": self.session_id}, headers=self._api_headers
)
logging.info(
- f"The stop action has been registered in RWA.Support.WebApp with status code {r.status_code} and response {r.content.decode()}."
+ "The stop action has been registered in RWA.Support.WebApp "
+ f"with status code {r.status_code} and response {r.content.decode()}."
)
except requests.ConnectionError:
pass
@@ -282,8 +282,7 @@ class Session:
def vnc_process_running(self) -> bool:
"""Check if the VNC process is still running."""
if self.mockup_session:
- filename = f"/tmp/rwa/{str(self.ws_port) + str(self.vnc_port) + str(self.ws_pid) + str(self.vnc_pid)}.lock"
- return os.path.isfile(filename)
+ return os.path.isfile(self._mock_lock_file_path)
if self.vnc_pid in psutil.pids():
p = psutil.Process(self.vnc_pid)