primitive 0.1.12__tar.gz → 0.1.14__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (55) hide show
  1. {primitive-0.1.12 → primitive-0.1.14}/PKG-INFO +1 -1
  2. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/__about__.py +1 -1
  3. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/agent/actions.py +4 -4
  4. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/cli.py +8 -0
  5. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/client.py +6 -0
  6. primitive-0.1.14/src/primitive/daemons/actions.py +75 -0
  7. primitive-0.1.14/src/primitive/daemons/commands.py +65 -0
  8. primitive-0.1.14/src/primitive/daemons/launch_agents.py +144 -0
  9. primitive-0.1.14/src/primitive/daemons/launch_service.py +170 -0
  10. {primitive-0.1.12/src/primitive/projects → primitive-0.1.14/src/primitive/jobs}/actions.py +133 -5
  11. primitive-0.1.14/src/primitive/jobs/commands.py +41 -0
  12. primitive-0.1.14/src/primitive/organizations/actions.py +84 -0
  13. primitive-0.1.14/src/primitive/organizations/commands.py +24 -0
  14. primitive-0.1.14/src/primitive/projects/actions.py +79 -0
  15. primitive-0.1.14/src/primitive/projects/commands.py +24 -0
  16. {primitive-0.1.12 → primitive-0.1.14}/.git-hooks/pre-commit +0 -0
  17. {primitive-0.1.12 → primitive-0.1.14}/.gitattributes +0 -0
  18. {primitive-0.1.12 → primitive-0.1.14}/.github/workflows/lint.yml +0 -0
  19. {primitive-0.1.12 → primitive-0.1.14}/.github/workflows/publish.yml +0 -0
  20. {primitive-0.1.12 → primitive-0.1.14}/.gitignore +0 -0
  21. {primitive-0.1.12 → primitive-0.1.14}/.vscode/settings.json +0 -0
  22. {primitive-0.1.12 → primitive-0.1.14}/LICENSE.txt +0 -0
  23. {primitive-0.1.12 → primitive-0.1.14}/Makefile +0 -0
  24. {primitive-0.1.12 → primitive-0.1.14}/README.md +0 -0
  25. {primitive-0.1.12 → primitive-0.1.14}/linux setup.md +0 -0
  26. {primitive-0.1.12 → primitive-0.1.14}/pyproject.toml +0 -0
  27. {primitive-0.1.12 → primitive-0.1.14}/requirements.txt +0 -0
  28. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/__init__.py +0 -0
  29. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/agent/commands.py +0 -0
  30. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/auth/__init__.py +0 -0
  31. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/auth/actions.py +0 -0
  32. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/auth/commands.py +0 -0
  33. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/files/actions.py +0 -0
  34. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/files/commands.py +0 -0
  35. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/git/__init__.py +0 -0
  36. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/git/actions.py +0 -0
  37. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/git/commands.py +0 -0
  38. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/graphql/__init__.py +0 -0
  39. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/graphql/sdk.py +0 -0
  40. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/hardware/actions.py +0 -0
  41. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/hardware/commands.py +0 -0
  42. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/lint/actions.py +0 -0
  43. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/lint/commands.py +0 -0
  44. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/projects/__init__.py +0 -0
  45. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/simulations/__init__.py +0 -0
  46. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/simulations/actions.py +0 -0
  47. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/actions.py +0 -0
  48. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/config.py +0 -0
  49. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/files.py +0 -0
  50. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/git.py +0 -0
  51. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/memory_size.py +0 -0
  52. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/printer.py +0 -0
  53. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/shell.py +0 -0
  54. {primitive-0.1.12 → primitive-0.1.14}/src/primitive/utils/verible.py +0 -0
  55. {primitive-0.1.12 → primitive-0.1.14}/tests/__init__.py +0 -0
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.3
2
2
  Name: primitive
3
- Version: 0.1.12
3
+ Version: 0.1.14
4
4
  Project-URL: Documentation, https://github.com//primitivecorp/primitive-cli#readme
5
5
  Project-URL: Issues, https://github.com//primitivecorp/primitive-cli/issues
6
6
  Project-URL: Source, https://github.com//primitivecorp/primitive-cli
@@ -1,4 +1,4 @@
1
1
  # SPDX-FileCopyrightText: 2024-present Dylan Stein <dylan@steins.studio>
2
2
  #
3
3
  # SPDX-License-Identifier: MIT
4
- __version__ = "0.1.12"
4
+ __version__ = "0.1.14"
@@ -32,7 +32,7 @@ class Agent(BaseAction):
32
32
  sleep(5)
33
33
  continue
34
34
 
35
- job_runs_data = self.primitive.projects.get_job_runs(
35
+ job_runs_data = self.primitive.jobs.get_job_runs(
36
36
  status="pending", first=1, reservation_id=active_reservation_id
37
37
  )
38
38
 
@@ -52,7 +52,7 @@ class Agent(BaseAction):
52
52
  )
53
53
 
54
54
  github_access_token = (
55
- self.primitive.projects.github_access_token_for_job_run(
55
+ self.primitive.jobs.github_access_token_for_job_run(
56
56
  job_run["id"]
57
57
  )
58
58
  )
@@ -68,7 +68,7 @@ class Agent(BaseAction):
68
68
  if job_run["job"]["slug"] == "lint":
69
69
  logger.debug("Executing Lint Job")
70
70
 
71
- self.primitive.projects.job_run_update(
71
+ self.primitive.jobs.job_run_update(
72
72
  job_run["id"], status="request_in_progress"
73
73
  )
74
74
 
@@ -79,7 +79,7 @@ class Agent(BaseAction):
79
79
  conclusion = "success"
80
80
  else:
81
81
  conclusion = "failure"
82
- self.primitive.projects.job_run_update(
82
+ self.primitive.jobs.job_run_update(
83
83
  job_run["id"],
84
84
  status="request_completed",
85
85
  conclusion=conclusion,
@@ -9,6 +9,10 @@ from .hardware.commands import cli as hardware_commands
9
9
  from .lint.commands import cli as lint_commands
10
10
  from .agent.commands import cli as agent_commands
11
11
  from .git.commands import cli as git_commands
12
+ from .daemons.commands import cli as daemons_commands
13
+ from .jobs.commands import cli as jobs_commands
14
+ from .organizations.commands import cli as organizations_commands
15
+ from .projects.commands import cli as projects_commands
12
16
 
13
17
 
14
18
  @click.group()
@@ -59,6 +63,10 @@ cli.add_command(hardware_commands, "hardware")
59
63
  cli.add_command(lint_commands, "lint")
60
64
  cli.add_command(agent_commands, "agent")
61
65
  cli.add_command(git_commands, "git")
66
+ cli.add_command(daemons_commands, "daemons")
67
+ cli.add_command(jobs_commands, "jobs")
68
+ cli.add_command(organizations_commands, "organizations")
69
+ cli.add_command(projects_commands, "projects")
62
70
 
63
71
  if __name__ == "__main__":
64
72
  cli(obj={})
@@ -9,6 +9,9 @@ from .hardware.actions import Hardware
9
9
  from .lint.actions import Lint
10
10
  from .agent.actions import Agent
11
11
  from .git.actions import Git
12
+ from .daemons.actions import Daemons
13
+ from .jobs.actions import Jobs
14
+ from .organizations.actions import Organizations
12
15
 
13
16
  from loguru import logger
14
17
 
@@ -54,13 +57,16 @@ class Primitive:
54
57
  )
55
58
 
56
59
  self.auth: Auth = Auth(self)
60
+ self.organizations: Organizations = Organizations(self)
57
61
  self.projects: Projects = Projects(self)
62
+ self.jobs: Jobs = Jobs(self)
58
63
  self.files: Files = Files(self)
59
64
  self.simulations: Simulations = Simulations(self)
60
65
  self.hardware: Hardware = Hardware(self)
61
66
  self.lint: Lint = Lint(self)
62
67
  self.agent: Agent = Agent(self)
63
68
  self.git: Git = Git(self)
69
+ self.daemons: Daemons = Daemons(self)
64
70
 
65
71
  def get_host_config(self):
66
72
  self.full_config = read_config_file()
@@ -0,0 +1,75 @@
1
+ import platform
2
+ import typing
3
+
4
+ if typing.TYPE_CHECKING:
5
+ from ..client import Primitive
6
+
7
+ from .launch_agents import (
8
+ full_launch_agent_install,
9
+ full_launch_agent_uninstall,
10
+ start_launch_agent,
11
+ stop_launch_agent,
12
+ view_launch_agent_logs,
13
+ )
14
+
15
+ from .launch_service import (
16
+ full_service_install,
17
+ full_service_uninstall,
18
+ start_service,
19
+ stop_service,
20
+ view_service_logs,
21
+ )
22
+
23
+
24
+ class Daemons:
25
+ def __init__(self, primitive) -> None:
26
+ self.primitive: Primitive = primitive
27
+ self.os_family = platform.system()
28
+
29
+ def install(self):
30
+ result = True
31
+ if self.os_family == "Darwin":
32
+ full_launch_agent_install()
33
+ elif self.os_family == "Linux":
34
+ full_service_install()
35
+ elif self.os_family == "Windows":
36
+ print("Not Implemented")
37
+ return result
38
+
39
+ def uninstall(self):
40
+ result = True
41
+ if self.os_family == "Darwin":
42
+ full_launch_agent_uninstall()
43
+ elif self.os_family == "Linux":
44
+ full_service_uninstall()
45
+ elif self.os_family == "Windows":
46
+ print("Not Implemented")
47
+ return result
48
+
49
+ def stop(self) -> bool:
50
+ result = True
51
+ if self.os_family == "Darwin":
52
+ result = stop_launch_agent()
53
+ elif self.os_family == "Linux":
54
+ stop_service()
55
+ elif self.os_family == "Windows":
56
+ print("Not Implemented")
57
+ return result
58
+
59
+ def start(self) -> bool:
60
+ result = True
61
+ if self.os_family == "Darwin":
62
+ result = start_launch_agent()
63
+ elif self.os_family == "Linux":
64
+ start_service()
65
+ elif self.os_family == "Windows":
66
+ print("Not Implemented")
67
+ return result
68
+
69
+ def logs(self):
70
+ if self.os_family == "Darwin":
71
+ view_launch_agent_logs()
72
+ elif self.os_family == "Linux":
73
+ view_service_logs()
74
+ elif self.os_family == "Windows":
75
+ print("Not Implemented")
@@ -0,0 +1,65 @@
1
+ import click
2
+
3
+ from ..utils.printer import print_result
4
+ import typing
5
+
6
+ if typing.TYPE_CHECKING:
7
+ from ..client import Primitive
8
+
9
+
10
+ @click.group()
11
+ @click.pass_context
12
+ def cli(context):
13
+ """Daemon"""
14
+ pass
15
+
16
+
17
+ @cli.command("install")
18
+ @click.pass_context
19
+ def install_daemon_command(context):
20
+ """Install the full primitive daemon"""
21
+ primitive: Primitive = context.obj.get("PRIMITIVE")
22
+ result = primitive.daemons.install()
23
+ print_result(message=result, context=context)
24
+
25
+
26
+ @cli.command("uninstall")
27
+ @click.pass_context
28
+ def uninstall_daemon_command(context):
29
+ """Uninstall the full primitive Daemon"""
30
+ primitive: Primitive = context.obj.get("PRIMITIVE")
31
+ result = primitive.daemons.uninstall()
32
+ print_result(message=result, context=context)
33
+
34
+
35
+ @cli.command("stop")
36
+ @click.pass_context
37
+ def stop_daemon_command(context):
38
+ """Stop primitive Daemon"""
39
+ primitive: Primitive = context.obj.get("PRIMITIVE")
40
+ result = primitive.daemons.stop()
41
+ message = "stopping primitive daemon"
42
+ if context.obj["JSON"]:
43
+ message = result
44
+ print_result(message=message, context=context)
45
+
46
+
47
+ @cli.command("start")
48
+ @click.pass_context
49
+ def start_daemon_command(context):
50
+ """Start primitive Daemon"""
51
+ primitive: Primitive = context.obj.get("PRIMITIVE")
52
+ result = primitive.daemons.start()
53
+ message = "starting primitive daemon"
54
+ if context.obj["JSON"]:
55
+ message = result
56
+ print_result(message=message, context=context)
57
+
58
+
59
+ @cli.command("logs")
60
+ @click.pass_context
61
+ def log_daemon_command(context):
62
+ """Logs from primitive Daemon"""
63
+ primitive: Primitive = context.obj.get("PRIMITIVE")
64
+ result = primitive.daemons.logs()
65
+ print_result(message=result, context=context)
@@ -0,0 +1,144 @@
1
+ import os
2
+ from pathlib import Path
3
+ import subprocess
4
+
5
+ HOME_DIRECTORY = Path.home()
6
+ CURRENT_USER = str(HOME_DIRECTORY.expanduser()).lstrip("/Users/")
7
+
8
+ PRIMITIVE_BINARY_PATH = Path(HOME_DIRECTORY / ".pyenv" / "shims" / "primitive")
9
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH = Path(
10
+ HOME_DIRECTORY / "Library" / "LaunchAgents" / "tech.primitive.agent.plist"
11
+ )
12
+ PRIMITIVE_LAUNCH_AGENT_LOGS = Path(
13
+ HOME_DIRECTORY / "Library" / "Logs" / "tech.primitive.agent.log"
14
+ )
15
+ PRIMITIVE_LAUNCH_AGENT_LABEL = "tech.primitive.agent"
16
+ PRIMITIVE_LAUNCH_AGENT_WORKING_DIR = Path(
17
+ HOME_DIRECTORY / "Logs" / "tech.primitive.agent.log"
18
+ )
19
+
20
+
21
+ def stop_launch_agent():
22
+ try:
23
+ stop_existing_process = f"launchctl stop {PRIMITIVE_LAUNCH_AGENT_LABEL}"
24
+ subprocess.check_output(stop_existing_process.split(" "))
25
+ return True
26
+ except subprocess.CalledProcessError as exception:
27
+ print("stop_launch_agent: ", exception)
28
+ return False
29
+
30
+
31
+ def start_launch_agent():
32
+ try:
33
+ start_new_agent = f"launchctl start {PRIMITIVE_LAUNCH_AGENT_LABEL}"
34
+ subprocess.check_output(start_new_agent.split(" "))
35
+ return True
36
+ except subprocess.CalledProcessError as exception:
37
+ print("start_launch_agent: ", exception)
38
+ return False
39
+
40
+
41
+ def unload_launch_agent():
42
+ try:
43
+ remove_existing_agent = f"launchctl unload -w {PRIMITIVE_LAUNCH_AGENT_FILEPATH}"
44
+ subprocess.check_output(remove_existing_agent.split(" "))
45
+ return True
46
+ except subprocess.CalledProcessError as exception:
47
+ print("remove_launch_agent: ", exception)
48
+ return False
49
+
50
+
51
+ def load_launch_agent():
52
+ try:
53
+ load_new_plist = f"launchctl load -w {PRIMITIVE_LAUNCH_AGENT_FILEPATH}"
54
+ subprocess.check_output(load_new_plist.split(" "))
55
+ return True
56
+ except subprocess.CalledProcessError as exception:
57
+ print("load_launch_agent: ", exception)
58
+ return False
59
+
60
+
61
+ def create_stdout_file():
62
+ if not PRIMITIVE_LAUNCH_AGENT_LOGS.exists():
63
+ PRIMITIVE_LAUNCH_AGENT_LOGS.parent.mkdir(parents=True, exist_ok=True)
64
+ PRIMITIVE_LAUNCH_AGENT_LOGS.touch()
65
+
66
+
67
+ def delete_stdout_file():
68
+ if PRIMITIVE_LAUNCH_AGENT_LOGS.exists():
69
+ PRIMITIVE_LAUNCH_AGENT_LOGS.unlink()
70
+
71
+
72
+ def populate_fresh_launch_agent():
73
+ PRIMITIVE_LAUNCH_AGENT_LOGS.parent.mkdir(parents=True, exist_ok=True)
74
+ PRIMITIVE_LAUNCH_AGENT_LOGS.touch()
75
+
76
+ if PRIMITIVE_LAUNCH_AGENT_FILEPATH.exists():
77
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH.unlink()
78
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH.parent.mkdir(parents=True, exist_ok=True)
79
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH.touch()
80
+
81
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH.write_text(
82
+ f"""<?xml version="1.0" encoding="UTF-8"?>
83
+ <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
84
+ <plist version="1.0">
85
+ <dict>
86
+ <key>KeepAlive</key>
87
+ <true/>
88
+ <key>Label</key>
89
+ <string>{PRIMITIVE_LAUNCH_AGENT_LABEL}</string>
90
+ <key>LimitLoadToSessionType</key>
91
+ <array>
92
+ <string>Aqua</string>
93
+ <string>Background</string>
94
+ <string>LoginWindow</string>
95
+ <string>StandardIO</string>
96
+ </array>
97
+ <key>ProgramArguments</key>
98
+ <array>
99
+ <string>{PRIMITIVE_BINARY_PATH}</string>
100
+ <string>agent</string>
101
+ </array>
102
+ <key>RunAtLoad</key>
103
+ <true/>
104
+ <key>StandardErrorPath</key>
105
+ <string>{PRIMITIVE_LAUNCH_AGENT_LOGS}</string>
106
+ <key>StandardOutPath</key>
107
+ <string>{PRIMITIVE_LAUNCH_AGENT_LOGS}</string>
108
+ </dict>
109
+ </plist>""" # noqa: E501
110
+ )
111
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH.chmod(0o644)
112
+ verify_launch_agent()
113
+
114
+
115
+ def verify_launch_agent():
116
+ plutil_check = f"plutil -lint {PRIMITIVE_LAUNCH_AGENT_FILEPATH}"
117
+ try:
118
+ subprocess.check_output(plutil_check.split(" "))
119
+ return True
120
+ except subprocess.CalledProcessError as exception:
121
+ print("verify_launch_agent: ", exception)
122
+ return False
123
+
124
+
125
+ def view_launch_agent_logs():
126
+ follow_logs = f"tail -f -n +1 {PRIMITIVE_LAUNCH_AGENT_LOGS}"
127
+ os.system(follow_logs)
128
+
129
+
130
+ def full_launch_agent_install():
131
+ stop_launch_agent()
132
+ unload_launch_agent()
133
+ populate_fresh_launch_agent()
134
+ create_stdout_file()
135
+ load_launch_agent()
136
+ start_launch_agent()
137
+
138
+
139
+ def full_launch_agent_uninstall():
140
+ stop_launch_agent()
141
+ unload_launch_agent()
142
+ if PRIMITIVE_LAUNCH_AGENT_FILEPATH.exists():
143
+ PRIMITIVE_LAUNCH_AGENT_FILEPATH.unlink()
144
+ delete_stdout_file()
@@ -0,0 +1,170 @@
1
+ import os
2
+ import configparser
3
+ import subprocess
4
+ from pathlib import Path
5
+
6
+ HOME_DIRECTORY = Path.home()
7
+
8
+ PRIMITIVE_BINARY_PATH = Path(HOME_DIRECTORY / ".pyenv" / "shims" / "primitive")
9
+
10
+ PRIMITIVE_AGENT_SERVICE = "tech.primitive.agent.service"
11
+ PRIMITIVE_AGENT_LOGS = "tech.primitive.agent.log"
12
+ PRIMITIVE_AGENT_SERVICE_FILEPATH = Path(
13
+ HOME_DIRECTORY / ".config" / "systemd" / "user" / PRIMITIVE_AGENT_SERVICE
14
+ )
15
+ PRIMITIVE_AGENT_LOGS_FILEPATH = Path(
16
+ HOME_DIRECTORY / ".cache" / "primitive" / PRIMITIVE_AGENT_LOGS
17
+ )
18
+
19
+
20
+ def stop_service():
21
+ try:
22
+ if is_service_active():
23
+ stop_existing_service = f"systemctl --user stop {PRIMITIVE_AGENT_SERVICE}"
24
+ subprocess.check_output(stop_existing_service.split(" "))
25
+ return True
26
+ except subprocess.CalledProcessError as exception:
27
+ print("stop_service: ", exception)
28
+ return False
29
+
30
+
31
+ def is_service_active():
32
+ try:
33
+ is_service_active = (
34
+ f"systemctl --user show {PRIMITIVE_AGENT_SERVICE} -p ActiveState --value"
35
+ )
36
+ output = subprocess.check_output(is_service_active.split(" ")).decode().strip()
37
+ return output == "active"
38
+ except subprocess.CalledProcessError as exception:
39
+ print("is_service_active: ", exception)
40
+ return False
41
+
42
+
43
+ def disable_service():
44
+ try:
45
+ if is_service_enabled():
46
+ disable_existing_service = (
47
+ f"systemctl --user disable {PRIMITIVE_AGENT_SERVICE}"
48
+ )
49
+ subprocess.check_output(disable_existing_service.split(" "))
50
+ return True
51
+ except subprocess.CalledProcessError as exception:
52
+ print("disable_service: ", exception)
53
+ return False
54
+
55
+
56
+ def is_service_enabled():
57
+ try:
58
+ is_service_active = (
59
+ f"systemctl --user show {PRIMITIVE_AGENT_SERVICE} -p UnitFileState --value" # noqa
60
+ )
61
+ output = subprocess.check_output(is_service_active.split(" ")).decode().strip()
62
+ return output == "enabled"
63
+ except subprocess.CalledProcessError as exception:
64
+ print("is_service_enabled: ", exception)
65
+ return False
66
+
67
+
68
+ def populate_service_file():
69
+ PRIMITIVE_AGENT_LOGS_FILEPATH.parent.mkdir(parents=True, exist_ok=True)
70
+ PRIMITIVE_AGENT_LOGS_FILEPATH.touch()
71
+
72
+ if PRIMITIVE_AGENT_SERVICE_FILEPATH.exists():
73
+ PRIMITIVE_AGENT_SERVICE_FILEPATH.unlink()
74
+ PRIMITIVE_AGENT_SERVICE_FILEPATH.parent.mkdir(parents=True, exist_ok=True)
75
+ PRIMITIVE_AGENT_SERVICE_FILEPATH.touch()
76
+
77
+ config = configparser.ConfigParser()
78
+ config.optionxform = str # type: ignore
79
+
80
+ config["Unit"] = {
81
+ "Description": "Primitive Agent",
82
+ "After": "network.target",
83
+ }
84
+
85
+ config["Service"] = {
86
+ "ExecStart": f"{PRIMITIVE_BINARY_PATH} agent",
87
+ "Restart": "always",
88
+ "StandardError": f"append:{PRIMITIVE_AGENT_LOGS_FILEPATH}",
89
+ "StandardOutput": f"append:{PRIMITIVE_AGENT_LOGS_FILEPATH}",
90
+ }
91
+
92
+ config["Install"] = {
93
+ "WantedBy": "default.target",
94
+ }
95
+
96
+ try:
97
+ with open(PRIMITIVE_AGENT_SERVICE_FILEPATH, "w") as service_file:
98
+ config.write(service_file)
99
+ except IOError as exception:
100
+ print(f"populate_service_file: {exception}")
101
+
102
+ PRIMITIVE_AGENT_SERVICE_FILEPATH.chmod(0o644)
103
+ verify_service_file()
104
+
105
+
106
+ def verify_service_file():
107
+ systemctl_check = (
108
+ f"systemctl --user show {PRIMITIVE_AGENT_SERVICE} -p CanStart --value"
109
+ )
110
+ try:
111
+ output = subprocess.check_output(systemctl_check.split(" ")).decode().strip()
112
+ if output == "no":
113
+ raise Exception(f"{systemctl_check} yielded {output}")
114
+ return True
115
+ except subprocess.CalledProcessError as exception:
116
+ print("verify_service_file: ", exception)
117
+ return False
118
+
119
+
120
+ def create_stdout_file():
121
+ if not PRIMITIVE_AGENT_LOGS_FILEPATH.exists():
122
+ PRIMITIVE_AGENT_LOGS_FILEPATH.parent.mkdir(parents=True, exist_ok=True)
123
+ PRIMITIVE_AGENT_LOGS_FILEPATH.touch()
124
+
125
+
126
+ def delete_stdout_file():
127
+ if PRIMITIVE_AGENT_LOGS_FILEPATH.exists():
128
+ PRIMITIVE_AGENT_LOGS_FILEPATH.unlink()
129
+
130
+
131
+ def enable_service():
132
+ try:
133
+ enable_service = f"systemctl --user enable {PRIMITIVE_AGENT_SERVICE}"
134
+ subprocess.check_output(enable_service.split(" "))
135
+ return True
136
+ except subprocess.CalledProcessError as exception:
137
+ print("enable_service: ", exception)
138
+ return False
139
+
140
+
141
+ def start_service():
142
+ try:
143
+ start_new_service = f"systemctl --user start {PRIMITIVE_AGENT_SERVICE}"
144
+ subprocess.check_output(start_new_service.split(" "))
145
+ return True
146
+ except subprocess.CalledProcessError as exception:
147
+ print("start_service: ", exception)
148
+ return False
149
+
150
+
151
+ def view_service_logs():
152
+ follow_logs = f"tail -f -n +1 {PRIMITIVE_AGENT_LOGS_FILEPATH}"
153
+ os.system(follow_logs)
154
+
155
+
156
+ def full_service_install():
157
+ stop_service()
158
+ disable_service()
159
+ populate_service_file()
160
+ create_stdout_file()
161
+ enable_service()
162
+ start_service()
163
+
164
+
165
+ def full_service_uninstall():
166
+ stop_service()
167
+ disable_service()
168
+ if PRIMITIVE_AGENT_SERVICE_FILEPATH.exists():
169
+ PRIMITIVE_AGENT_SERVICE_FILEPATH.unlink()
170
+ delete_stdout_file()
@@ -5,7 +5,88 @@ from gql import gql
5
5
  from primitive.utils.actions import BaseAction
6
6
 
7
7
 
8
- class Projects(BaseAction):
8
+ class Jobs(BaseAction):
9
+ def get_jobs(
10
+ self,
11
+ organization_id: Optional[str] = None,
12
+ project_id: Optional[str] = None,
13
+ job_id: Optional[str] = None,
14
+ slug: Optional[str] = None,
15
+ first: Optional[int] = 1,
16
+ last: Optional[int] = None,
17
+ ):
18
+ query = gql(
19
+ """
20
+ fragment PageInfoFragment on PageInfo {
21
+ hasNextPage
22
+ hasPreviousPage
23
+ startCursor
24
+ endCursor
25
+ }
26
+
27
+ fragment JobFragment on Job {
28
+ id
29
+ pk
30
+ slug
31
+ name
32
+ createdAt
33
+ updatedAt
34
+ }
35
+
36
+ query jobs(
37
+ $before: String
38
+ $after: String
39
+ $first: Int
40
+ $last: Int
41
+ $filters: JobFilters
42
+ ) {
43
+ jobs(
44
+ before: $before
45
+ after: $after
46
+ first: $first
47
+ last: $last
48
+ filters: $filters
49
+ ) {
50
+ totalCount
51
+ pageInfo {
52
+ ...PageInfoFragment
53
+ }
54
+ edges {
55
+ cursor
56
+ node {
57
+ ...JobFragment
58
+ }
59
+ }
60
+ }
61
+ }
62
+ """
63
+ )
64
+
65
+ filters = {}
66
+ if organization_id:
67
+ filters["organization"] = {"id": organization_id}
68
+ if project_id:
69
+ filters["project"] = {"id": project_id}
70
+ if job_id:
71
+ filters["id"] = job_id
72
+ if slug:
73
+ filters["slug"] = {"exact": slug}
74
+
75
+ variables = {
76
+ "first": first,
77
+ "last": last,
78
+ "filters": filters,
79
+ "order": {
80
+ "createdAt": "DESC",
81
+ },
82
+ }
83
+
84
+ result = self.primitive.session.execute(
85
+ query, variable_values=variables, get_execution_result=True
86
+ )
87
+ jobs = [edge["node"] for edge in result.data["jobs"]["edges"]]
88
+ return jobs
89
+
9
90
  def get_job_runs(
10
91
  self,
11
92
  organization_id: Optional[str] = None,
@@ -114,12 +195,34 @@ query jobRuns(
114
195
  def get_job_run(self, id: str):
115
196
  query = gql(
116
197
  """
198
+ fragment JobRunFragment on JobRun {
199
+ id
200
+ pk
201
+ createdAt
202
+ updatedAt
203
+ completedAt
204
+ startedAt
205
+ status
206
+ conclusion
207
+ stdout
208
+ job {
209
+ id
210
+ pk
211
+ slug
212
+ name
213
+ createdAt
214
+ updatedAt
215
+ }
216
+ gitCommit {
217
+ sha
218
+ branch
219
+ repoFullName
220
+ }
221
+ }
222
+
117
223
  query jobRun($id: GlobalID!) {
118
224
  jobRun(id: $id) {
119
- id
120
- organization {
121
- id
122
- }
225
+ ...JobRunFragment
123
226
  }
124
227
  }
125
228
  """
@@ -173,3 +276,28 @@ query ghAppTokenForJobRun($jobRunId: GlobalID!) {
173
276
  variables = {"jobRunId": job_run_id}
174
277
  result = self.primitive.session.execute(query, variable_values=variables)
175
278
  return result["ghAppTokenForJobRun"]
279
+
280
+ def get_latest_job_run_for_job(
281
+ self, job_slug: Optional[str] = None, job_id: Optional[str] = None
282
+ ):
283
+ if not job_slug and not job_id:
284
+ raise ValueError("job_slug or job_id is required")
285
+ jobs_results = self.get_jobs(slug=job_slug)
286
+ jobs = [edge["node"] for edge in jobs_results.data["jobs"]["edges"]]
287
+
288
+ job_id = jobs.id
289
+ job_run_results = self.get_job_runs(job_id=job_id, first=1)
290
+ job_run = [edge["node"] for edge in job_run_results.data["job_runs"]["edges"]][
291
+ 0
292
+ ]
293
+ return job_run
294
+
295
+ def job_run_start(
296
+ self,
297
+ job_slug: str,
298
+ job_id: str,
299
+ ):
300
+ if not job_slug and not job_id:
301
+ raise ValueError("job_slug or job_id is required")
302
+
303
+ self.get_jobs(slug=job_slug)
@@ -0,0 +1,41 @@
1
+ import click
2
+
3
+ from ..utils.printer import print_result
4
+
5
+ import typing
6
+
7
+ if typing.TYPE_CHECKING:
8
+ from ..client import Primitive
9
+
10
+
11
+ @click.group()
12
+ @click.pass_context
13
+ def cli(context):
14
+ """Jobs Commands"""
15
+ pass
16
+
17
+
18
+ @cli.command("list")
19
+ @click.pass_context
20
+ def list(
21
+ context,
22
+ organization_slug: str = None,
23
+ organization_id: str = None,
24
+ ):
25
+ """List Job"""
26
+ primitive: Primitive = context.obj.get("PRIMITIVE")
27
+ message = primitive.jobs.get_jobs()
28
+ print_result(message=message, context=context)
29
+
30
+
31
+ @cli.command("details")
32
+ @click.argument("job_slug")
33
+ @click.pass_context
34
+ def details(
35
+ context,
36
+ job_slug: str = None,
37
+ ):
38
+ """List Job"""
39
+ primitive: Primitive = context.obj.get("PRIMITIVE")
40
+ message = primitive.jobs.get_jobs(slug=job_slug)
41
+ print_result(message=message, context=context)
@@ -0,0 +1,84 @@
1
+ from typing import Optional
2
+ from gql import gql
3
+
4
+
5
+ from primitive.utils.actions import BaseAction
6
+
7
+
8
+ class Organizations(BaseAction):
9
+ def get_organizations(
10
+ self,
11
+ organization_id: Optional[str] = None,
12
+ slug: Optional[str] = None,
13
+ first: Optional[int] = 1,
14
+ last: Optional[int] = None,
15
+ ):
16
+ query = gql(
17
+ """
18
+ fragment PageInfoFragment on PageInfo {
19
+ hasNextPage
20
+ hasPreviousPage
21
+ startCursor
22
+ endCursor
23
+ }
24
+
25
+ fragment OrganizationFragment on Organization {
26
+ id
27
+ pk
28
+ slug
29
+ name
30
+ createdAt
31
+ updatedAt
32
+ }
33
+
34
+ query organizations(
35
+ $before: String
36
+ $after: String
37
+ $first: Int
38
+ $last: Int
39
+ $filters: OrganizationFilters
40
+ $order: OrganizationOrder
41
+ ) {
42
+ organizations(
43
+ before: $before
44
+ after: $after
45
+ first: $first
46
+ last: $last
47
+ filters: $filters
48
+ order: $order
49
+ ) {
50
+ totalCount
51
+ pageInfo {
52
+ ...PageInfoFragment
53
+ }
54
+ edges {
55
+ cursor
56
+ node {
57
+ ...OrganizationFragment
58
+ }
59
+ }
60
+ }
61
+ }
62
+ """
63
+ )
64
+
65
+ filters = {}
66
+ if organization_id:
67
+ filters["organization"] = {"id": organization_id}
68
+ if slug:
69
+ filters["slug"] = {"exact": slug}
70
+
71
+ variables = {
72
+ "first": first,
73
+ "last": last,
74
+ "filters": filters,
75
+ "order": {
76
+ "createdAt": "DESC",
77
+ },
78
+ }
79
+
80
+ result = self.primitive.session.execute(
81
+ query, variable_values=variables, get_execution_result=True
82
+ )
83
+ organizations = [edge["node"] for edge in result.data["organizations"]["edges"]]
84
+ return organizations
@@ -0,0 +1,24 @@
1
+ import click
2
+
3
+ from ..utils.printer import print_result
4
+
5
+ import typing
6
+
7
+ if typing.TYPE_CHECKING:
8
+ from ..client import Primitive
9
+
10
+
11
+ @click.group()
12
+ @click.pass_context
13
+ def cli(context):
14
+ """Organizations Commands"""
15
+ pass
16
+
17
+
18
+ @cli.command("list")
19
+ @click.pass_context
20
+ def details(context):
21
+ """List Organizations"""
22
+ primitive: Primitive = context.obj.get("PRIMITIVE")
23
+ message = primitive.organizations.get_organizations()
24
+ print_result(message=message, context=context)
@@ -0,0 +1,79 @@
1
+ from gql import gql
2
+
3
+ from typing import Optional
4
+ from primitive.utils.actions import BaseAction
5
+
6
+
7
+ class Projects(BaseAction):
8
+
9
+ def get_projects(
10
+ self,
11
+ organization_id: Optional[str] = None,
12
+ slug: Optional[str] = None,
13
+ first: Optional[int] = 1,
14
+ last: Optional[int] = None,
15
+ ):
16
+ query = gql(
17
+ """
18
+ fragment PageInfoFragment on PageInfo {
19
+ hasNextPage
20
+ hasPreviousPage
21
+ startCursor
22
+ endCursor
23
+ }
24
+
25
+ fragment ProjectFragment on Project {
26
+ id
27
+ pk
28
+ slug
29
+ name
30
+ createdAt
31
+ updatedAt
32
+ }
33
+
34
+ query projects(
35
+ $before: String
36
+ $after: String
37
+ $first: Int
38
+ $last: Int
39
+ $filters: ProjectFilters
40
+ ) {
41
+ projects(
42
+ before: $before
43
+ after: $after
44
+ first: $first
45
+ last: $last
46
+ filters: $filters
47
+ ) {
48
+ totalCount
49
+ pageInfo {
50
+ ...PageInfoFragment
51
+ }
52
+ edges {
53
+ cursor
54
+ node {
55
+ ...ProjectFragment
56
+ }
57
+ }
58
+ }
59
+ }
60
+ """
61
+ )
62
+
63
+ filters = {}
64
+ if organization_id:
65
+ filters["organization"] = {"id": organization_id}
66
+ if slug:
67
+ filters["slug"] = {"exact": slug}
68
+
69
+ variables = {
70
+ "first": first,
71
+ "last": last,
72
+ "filters": filters,
73
+ }
74
+
75
+ result = self.primitive.session.execute(
76
+ query, variable_values=variables, get_execution_result=True
77
+ )
78
+ projects = [edge["node"] for edge in result.data["projects"]["edges"]]
79
+ return projects
@@ -0,0 +1,24 @@
1
+ import click
2
+
3
+ from ..utils.printer import print_result
4
+
5
+ import typing
6
+
7
+ if typing.TYPE_CHECKING:
8
+ from ..client import Primitive
9
+
10
+
11
+ @click.group()
12
+ @click.pass_context
13
+ def cli(context):
14
+ """Projects Commands"""
15
+ pass
16
+
17
+
18
+ @cli.command("list")
19
+ @click.pass_context
20
+ def list(context):
21
+ """List Projects"""
22
+ primitive: Primitive = context.obj.get("PRIMITIVE")
23
+ message = primitive.projects.get_projects()
24
+ print_result(message=message, context=context)
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes
File without changes