-
Notifications
You must be signed in to change notification settings - Fork 0
/
SDKSpaceAdaptor.py
222 lines (196 loc) · 7.52 KB
/
SDKSpaceAdaptor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
import json
import os
from naas_python.domains.registry.RegistrySchema import RegistryConflictError
from naas_python.domains.space.SpaceSchema import (
ISpaceDomain,
ISpaceInvoker,
SpaceConflictError,
)
from naas_python.utils.cicd import Pipeline
class SDKSpaceAdaptor(ISpaceInvoker):
domain: ISpaceDomain
def __init__(self, domain: ISpaceDomain):
self.domain = domain
def create(
self,
name: str,
namespace: str,
image: str,
user_id: str,
env: dict,
resources: dict,
):
"""Create a space with the given name"""
space = self.domain.create(
name=name,
namespace=namespace,
image=image,
user_id=user_id,
env=env,
resources=resources,
)
return space
def get(self, name: str, namespace: str):
"""Get a space with the given name"""
space = self.domain.get(name=name, namespace=namespace)
return space
def list(self, user_id: str, namespace: str):
"""List all spaces for the current user"""
space_list = self.domain.list(user_id=user_id, namespace=namespace)
return space_list
def delete(self, name: str, namespace: str):
"""Delete a space by name"""
self.domain.delete(name=name, namespace=namespace)
def update(
self,
name: str,
image: str,
domain: str = None,
env: dict = None,
port: int = 5080,
cpu: int = 2,
memory: str = "2Gi",
):
space = self.domain.update(
name=name,
domain=domain,
containers=[
{
"name": name,
"image": image,
"env": json.loads(env) if env else None,
"cpu": cpu,
"memory": memory,
"port": port,
}
],
)
return space
def add(
self,
space_name: str,
space_type: str = "docker",
dockerfile_path: str = None,
docker_context: str = None,
container_port: str or int = 5080,
generate_ci: bool = True,
skip_registry: bool = False,
registry_name: str = None,
ci_type: str = "github-actions",
image: str = None,
cpu: str or int = 2,
memory: str = "2Gi",
):
"""
Adds a new space and generates a CI/CD configuration for management.
If requested, a new Docker registry will also be created and the CI/CD
configuration will be updated accordingly.
"""
registry_name = registry_name if registry_name else f"{space_name}-registry"
# Step 1: Create a new Registry on space.naas.ai if requested
if not skip_registry:
print(f"Creating Docker Registry '{registry_name}'...")
from naas_python.domains.registry.handlers.PythonHandler import (
primaryAdaptor as RegistryHandler,
)
# Supposes that no registry exists for the given name, else retrieve it.
try:
registry = RegistryHandler.create(name=registry_name)
except RegistryConflictError:
print(
f"A registry with the name '{registry_name}' already exists. Proceeding with existing registry."
)
registry = RegistryHandler.get(name=registry_name)
# Get credentials for the registry (will create a credentials file if it doesn't exist)
# and set up docker login for the registry (if type is docker)
if space_type == "docker":
print(f"Retrieving credentials for Docker Registry...")
RegistryHandler.get_credentials(name=registry_name)
# Step 2.a: Build and push image to registry container if requested:
if space_type == "docker":
print(f"Building Docker Image for '{space_name}'...")
os.system(
f"docker build -t {registry.registry.uri}:latest -f {dockerfile_path} {docker_context}"
)
print("Pushing Docker Image...")
os.system(f"docker push {registry.registry.uri}:latest")
# Step 2.b: Create a new space on space.naas.ai
print(f"Creating Naas Space '{space_name}'...")
try:
self.domain.create(
name=space_name,
domain=f"{space_name}.naas.ai",
containers=[
{
"name": space_name,
"image": image if image else f"{registry.registry.uri}:latest",
"env": {},
"cpu": cpu,
"memory": memory,
"port": container_port,
}
],
)
except SpaceConflictError as e:
print(
f"A space with the name '{space_name}' already exists. Proceeding with existing space."
)
self.domain.get(name=space_name)
# Step 3: Generate CI/CD configuration if requested
if generate_ci:
pipeline = Pipeline(name=f"ci-{space_name}")
# Check for naas_python cli help command
pipeline.add_job(
"Validate that naas_python works",
[
"name: Validate that naas_python works",
"run: |",
" naas_python --help",
],
)
# Check Naas Space status
pipeline.add_job(
"Check Naas Space status",
[
"name: Check Naas Space status",
"run: |",
f" naas_python space get --name { space_name }",
],
)
# Check Naas Registry status
pipeline.add_job(
"Check Naas Registry status",
[
"name: Check Naas Registry status",
"run: |",
f" naas_python registry get --name { registry_name }",
],
)
# Add custom jobs for CI/CD configuration
if space_type == "docker":
# Retrieve credentials from registry and login into docker
pipeline.add_job(
"Login to Docker Registry",
[
"name: Login to Docker Registry",
"run: |",
f" naas_python registry docker-login --name { registry_name }",
],
)
try:
_build_command = f" docker build -t {registry.registry.uri}:latest -f {dockerfile_path} {docker_context}"
except ValueError as e:
raise ValueError(
"When space_type is 'docker', dockerfile_path and docker_context must be provided. Please provide these values and try again"
) from e
docker_steps = [
"name: Build and Push Docker Image",
f'if: ${{ github.event_name == "push" }}',
"run: |",
_build_command,
f" docker push { registry.registry.uri }:latest",
]
pipeline.add_job("Build and Push Docker Image", docker_steps)
# Render the CI/CD configuration
pipeline.render()
print("Generated CI/CD configuration.")