Coretex
cron.py
1 # Copyright (C) 2023 Coretex LLC
2 
3 # This file is part of Coretex.ai
4 
5 # This program is free software: you can redistribute it and/or modify
6 # it under the terms of the GNU Affero General Public License as
7 # published by the Free Software Foundation, either version 3 of the
8 # License, or (at your option) any later version.
9 
10 # This program is distributed in the hope that it will be useful,
11 # but WITHOUT ANY WARRANTY; without even the implied warranty of
12 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 # GNU Affero General Public License for more details.
14 
15 # You should have received a copy of the GNU Affero General Public License
16 # along with this program. If not, see <https://www.gnu.org/licenses/>.
17 
18 from typing import List
19 
20 from ...utils import command
21 from ...configuration import CONFIG_DIR
22 
23 
24 def getExisting() -> List[str]:
25  _, output, error = command(["crontab", "-l"], ignoreStdout = True, ignoreStderr = True, check = False)
26  if error is not None and "no crontab for" in error:
27  return []
28  if output is not None:
29  return [line.strip() for line in output.split("\n") if line.strip()]
30 
31  raise ValueError("\"crontab\" is not installed. To enable automatic updates please install \"crontab\"")
32 
33 
34 def jobExists(script: str) -> bool:
35  existingLines = getExisting()
36  return any(script in line for line in existingLines)
37 
38 
39 def scheduleJob(scriptName: str) -> None:
40  existingLines = getExisting()
41  cronJob = f"*/30 * * * * {CONFIG_DIR / scriptName} >> {CONFIG_DIR}/logs/ctx_autoupdate.log 2>&1\n"
42  existingLines.append(cronJob)
43 
44  tempCronFilePath = CONFIG_DIR / "temp.cron"
45  with tempCronFilePath.open("w") as tempCronFile:
46  tempCronFile.write("\n".join(existingLines))
47 
48  command(["crontab", str(tempCronFilePath)])
49  tempCronFilePath.unlink()