nebu 0.1.0__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.
nebu-0.1.0/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
nebu-0.1.0/PKG-INFO ADDED
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.4
2
+ Name: nebu
3
+ Version: 0.1.0
4
+ Summary: A globally distributed container runtime
5
+ Requires-Python: >=3.10.14
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: openai>=1.68.2
9
+ Requires-Dist: pydantic>=2.10.6
10
+ Requires-Dist: pyyaml>=6.0.2
11
+ Requires-Dist: requests>=2.32.3
12
+ Dynamic: license-file
13
+
14
+ # nebulous-py
15
+ A python library for the [Nebulous runtime](https://github.com/agentsea/nebulous)
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install nebu
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+ from nebu import Container, V1EnvVar, V1ResourceMeta
27
+
28
+ container = Container(
29
+ metadata=V1ResourceMeta(
30
+ name="pytorch-example",
31
+ namespace="test",
32
+ ),
33
+ image="pytorch/pytorch:latest",
34
+ platform="runpod",
35
+ env=[V1EnvVar(name="MY_ENV_VAR", value="my-value")],
36
+ command="nvidia-smi",
37
+ accelerators=["1:A100_SXM"],
38
+ proxy_port=8080,
39
+ )
40
+
41
+ while container.status.status.lower() != "running":
42
+ print(f"Container '{container.metadata.name}' is not running, it is '{container.status.status}', waiting...")
43
+ time.sleep(1)
44
+
45
+ print(f"Container '{container.metadata.name}' is running")
46
+
47
+ print(f"You can access the container at {container.status.tailnet_url}")
48
+ ```
49
+
50
+ ## Contributing
51
+
52
+ Please open an issue or a PR to contribute to the project.
53
+
54
+ ## Development
55
+
56
+ ```bash
57
+ make test
58
+ ```
nebu-0.1.0/README.md ADDED
@@ -0,0 +1,45 @@
1
+ # nebulous-py
2
+ A python library for the [Nebulous runtime](https://github.com/agentsea/nebulous)
3
+
4
+ ## Installation
5
+
6
+ ```bash
7
+ pip install nebu
8
+ ```
9
+
10
+ ## Usage
11
+
12
+ ```python
13
+ from nebu import Container, V1EnvVar, V1ResourceMeta
14
+
15
+ container = Container(
16
+ metadata=V1ResourceMeta(
17
+ name="pytorch-example",
18
+ namespace="test",
19
+ ),
20
+ image="pytorch/pytorch:latest",
21
+ platform="runpod",
22
+ env=[V1EnvVar(name="MY_ENV_VAR", value="my-value")],
23
+ command="nvidia-smi",
24
+ accelerators=["1:A100_SXM"],
25
+ proxy_port=8080,
26
+ )
27
+
28
+ while container.status.status.lower() != "running":
29
+ print(f"Container '{container.metadata.name}' is not running, it is '{container.status.status}', waiting...")
30
+ time.sleep(1)
31
+
32
+ print(f"Container '{container.metadata.name}' is running")
33
+
34
+ print(f"You can access the container at {container.status.tailnet_url}")
35
+ ```
36
+
37
+ ## Contributing
38
+
39
+ Please open an issue or a PR to contribute to the project.
40
+
41
+ ## Development
42
+
43
+ ```bash
44
+ make test
45
+ ```
@@ -0,0 +1,24 @@
1
+ [project]
2
+ name = "nebu"
3
+ version = "0.1.0"
4
+ description = "A globally distributed container runtime"
5
+ readme = "README.md"
6
+ requires-python = ">=3.10.14"
7
+ dependencies = [
8
+ "openai>=1.68.2",
9
+ "pydantic>=2.10.6",
10
+ "pyyaml>=6.0.2",
11
+ "requests>=2.32.3",
12
+ ]
13
+
14
+ [dependency-groups]
15
+ dev = [
16
+ "pytest>=8.3.5",
17
+ ]
18
+
19
+ [tool.pyright]
20
+ reportUnknownParameterType = false
21
+ reportMissingTypeArgument = false
22
+ reportUnknownMemberType = false
23
+ reportUnknownVariableType = false
24
+ reportUnknownArgumentType = false
nebu-0.1.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,9 @@
1
+ # type: ignore
2
+ # pylint: disable=all
3
+ # ruff: noqa: F401
4
+ # ruff: noqa: F403
5
+
6
+ from .config import *
7
+ from .containers.container import Container
8
+ from .containers.models import *
9
+ from .meta import *
@@ -0,0 +1,135 @@
1
+ from __future__ import annotations
2
+
3
+ import os
4
+ from dataclasses import dataclass, field
5
+ from typing import List, Optional
6
+
7
+ import yaml
8
+
9
+
10
+ @dataclass
11
+ class ServerConfig:
12
+ """
13
+ Python equivalent of the Rust ServerConfig struct.
14
+ """
15
+
16
+ name: Optional[str] = None
17
+ api_key: Optional[str] = None
18
+ server: Optional[str] = None
19
+ auth_server: Optional[str] = None
20
+
21
+
22
+ @dataclass
23
+ class GlobalConfig:
24
+ """
25
+ Python equivalent of the Rust GlobalConfig struct.
26
+ Manages multiple ServerConfig entries and a current_server pointer.
27
+ """
28
+
29
+ servers: List[ServerConfig] = field(default_factory=list)
30
+ current_server: Optional[str] = None
31
+
32
+ @classmethod
33
+ def read(cls) -> GlobalConfig:
34
+ """
35
+ Read the config from ~/.agentsea/nebu.yaml, or create a default if it doesn’t exist.
36
+ Then ensure that we either find or create a matching server from environment variables,
37
+ and set that as the `current_server` if relevant (mimicking the Rust logic).
38
+ """
39
+ path = _get_config_file_path()
40
+ path_exists = os.path.exists(path)
41
+
42
+ # Load from disk or create a default
43
+ if path_exists:
44
+ with open(path, "r") as yaml_file:
45
+ data = yaml.safe_load(yaml_file) or {}
46
+ # Convert each server entry into a ServerConfig
47
+ servers_data = data.get("servers", [])
48
+ servers = [ServerConfig(**srv) for srv in servers_data]
49
+ current_server = data.get("current_server")
50
+ config = cls(servers=servers, current_server=current_server)
51
+ else:
52
+ config = cls() # default
53
+
54
+ # Collect environment variables (no fallback defaults here)
55
+ env_api_key = os.environ.get("NEBU_API_KEY") or os.environ.get(
56
+ "AGENTSEA_API_KEY"
57
+ )
58
+ env_server = os.environ.get("NEBU_SERVER") or os.environ.get("AGENTSEA_SERVER")
59
+ env_auth_server = os.environ.get("NEBU_AUTH_SERVER") or os.environ.get(
60
+ "AGENTSEA_AUTH_SERVER"
61
+ )
62
+
63
+ # Only proceed if all three environment variables are present
64
+ if env_api_key and env_server and env_auth_server:
65
+ # Find a matching server
66
+ found_server = None
67
+ for srv in config.servers:
68
+ if (
69
+ srv.api_key == env_api_key
70
+ and srv.server == env_server
71
+ and srv.auth_server == env_auth_server
72
+ ):
73
+ found_server = srv
74
+ break
75
+
76
+ server_name = "env-based-server"
77
+ if found_server:
78
+ # Ensure it has a name, so we can set current_server to it
79
+ if found_server.name is None:
80
+ found_server.name = server_name
81
+ # Use that server’s name as current
82
+ config.current_server = found_server.name
83
+ else:
84
+ # Create a new server entry
85
+ new_server = ServerConfig(
86
+ name=server_name,
87
+ api_key=env_api_key,
88
+ server=env_server,
89
+ auth_server=env_auth_server,
90
+ )
91
+ config.servers.append(new_server)
92
+ config.current_server = server_name
93
+
94
+ # Write if the file didn't already exist
95
+ if not path_exists:
96
+ config.write()
97
+
98
+ return config
99
+
100
+ def write(self) -> None:
101
+ """
102
+ Write the current GlobalConfig to disk as YAML.
103
+ """
104
+ path = _get_config_file_path()
105
+ # Create parent directories if they don't exist
106
+ os.makedirs(os.path.dirname(path), exist_ok=True)
107
+
108
+ # Convert our dataclass-based objects into simple dictionaries
109
+ data = {
110
+ "servers": [srv.__dict__ for srv in self.servers],
111
+ "current_server": self.current_server,
112
+ }
113
+
114
+ with open(path, "w") as yaml_file:
115
+ yaml.dump(data, yaml_file)
116
+ yaml_file.flush()
117
+
118
+ def get_current_server_config(self) -> Optional[ServerConfig]:
119
+ """
120
+ Get the server config for the current_server name, or None if unset/missing.
121
+ """
122
+ if self.current_server:
123
+ for srv in self.servers:
124
+ if srv.name == self.current_server:
125
+ return srv
126
+ return None
127
+
128
+
129
+ def _get_config_file_path() -> str:
130
+ """
131
+ Return the path to ~/.agentsea/nebu.yaml
132
+ """
133
+ home = os.path.expanduser("~")
134
+ config_dir = os.path.join(home, ".agentsea")
135
+ return os.path.join(config_dir, "nebu.yaml")
@@ -0,0 +1,241 @@
1
+ from typing import List, Optional
2
+
3
+ import requests
4
+
5
+ from nebu.config import GlobalConfig # or wherever your GlobalConfig is defined
6
+ from nebu.containers.models import (
7
+ DEFAULT_RESTART_POLICY,
8
+ V1AuthzConfig,
9
+ V1Container,
10
+ V1ContainerRequest,
11
+ V1ContainerResources,
12
+ V1Containers,
13
+ V1EnvVar,
14
+ V1Meter,
15
+ V1PortRequest,
16
+ V1ResourceMetaRequest,
17
+ V1SSHKey,
18
+ V1VolumePath,
19
+ )
20
+
21
+
22
+ class Container:
23
+ def __init__(
24
+ self,
25
+ name: str,
26
+ namespace: str = "default",
27
+ platform: Optional[str] = None,
28
+ image: str = "",
29
+ env: Optional[List[V1EnvVar]] = None,
30
+ command: Optional[str] = None,
31
+ volumes: Optional[List[V1VolumePath]] = None,
32
+ accelerators: Optional[List[str]] = None,
33
+ resources: Optional[V1ContainerResources] = None,
34
+ meters: Optional[List[V1Meter]] = None,
35
+ restart: str = DEFAULT_RESTART_POLICY,
36
+ queue: Optional[str] = None,
37
+ timeout: Optional[str] = None,
38
+ ssh_keys: Optional[List[V1SSHKey]] = None,
39
+ ports: Optional[List[V1PortRequest]] = None,
40
+ proxy_port: Optional[int] = None,
41
+ authz: Optional[V1AuthzConfig] = None,
42
+ config: Optional[GlobalConfig] = None,
43
+ ):
44
+ # Fallback to a default config if none is provided
45
+ config = config or GlobalConfig.read()
46
+ current_server = config.get_current_server_config()
47
+ if not current_server:
48
+ raise ValueError("No current server config found")
49
+ self.api_key = current_server.api_key
50
+ self.nebu_host = current_server.server
51
+
52
+ # print(f"nebu_host: {self.nebu_host}")
53
+ # print(f"api_key: {self.api_key}")
54
+
55
+ # Construct the containers base URL
56
+ self.containers_url = f"{self.nebu_host}/v1/containers"
57
+
58
+ # Attempt to find an existing container
59
+ response = requests.get(
60
+ self.containers_url,
61
+ headers={"Authorization": f"Bearer {self.api_key}"},
62
+ )
63
+ response.raise_for_status()
64
+
65
+ meta_request = V1ResourceMetaRequest(
66
+ name=name,
67
+ namespace=namespace,
68
+ )
69
+
70
+ containers = V1Containers.model_validate(response.json())
71
+ print(f"containers: {containers}")
72
+ existing = next(
73
+ (
74
+ c
75
+ for c in containers.containers
76
+ if c.metadata.name == name and c.metadata.namespace == namespace
77
+ ),
78
+ None,
79
+ )
80
+
81
+ print(f"existing: {existing}")
82
+
83
+ if not existing:
84
+ # If there's no existing container, create one:
85
+ if not image:
86
+ raise ValueError("An 'image' is required to create a new container.")
87
+
88
+ create_request = V1ContainerRequest(
89
+ kind="Container",
90
+ platform=platform,
91
+ metadata=meta_request,
92
+ image=image,
93
+ env=env,
94
+ command=command,
95
+ volumes=volumes,
96
+ accelerators=accelerators,
97
+ resources=resources,
98
+ meters=meters,
99
+ restart=restart,
100
+ queue=queue,
101
+ timeout=timeout,
102
+ ssh_keys=ssh_keys,
103
+ ports=ports,
104
+ proxy_port=proxy_port,
105
+ authz=authz,
106
+ )
107
+ create_response = requests.post(
108
+ self.containers_url,
109
+ json=create_request.model_dump(),
110
+ headers={"Authorization": f"Bearer {self.api_key}"},
111
+ )
112
+ create_response.raise_for_status()
113
+ self.container = V1Container.model_validate(create_response.json())
114
+ print(f"Created container {self.container.metadata.name}")
115
+ else:
116
+ # If container is found, check if anything has changed
117
+ # Gather the updated fields from the function arguments
118
+ updated_image = image or existing.image
119
+ updated_env = env if env is not None else existing.env
120
+ updated_command = command if command is not None else existing.command
121
+ updated_volumes = volumes if volumes is not None else existing.volumes
122
+ updated_accelerators = (
123
+ accelerators if accelerators is not None else existing.accelerators
124
+ )
125
+ updated_resources = (
126
+ resources if resources is not None else existing.resources
127
+ )
128
+ updated_meters = meters if meters is not None else existing.meters
129
+ updated_restart = restart if restart else existing.restart
130
+ updated_queue = queue if queue else existing.queue
131
+ updated_timeout = timeout if timeout else existing.timeout
132
+ updated_proxy_port = proxy_port if proxy_port else existing.proxy_port
133
+ updated_authz = authz if authz else existing.authz
134
+
135
+ # Determine if fields differ. You can adapt these checks as needed
136
+ # (for example, deep comparison for complex field structures).
137
+ fields_changed = (
138
+ existing.image != updated_image
139
+ or existing.env != updated_env
140
+ or existing.command != updated_command
141
+ or existing.volumes != updated_volumes
142
+ or existing.accelerators != updated_accelerators
143
+ or existing.resources != updated_resources
144
+ or existing.meters != updated_meters
145
+ or existing.restart != updated_restart
146
+ or existing.queue != updated_queue
147
+ or existing.timeout != updated_timeout
148
+ or existing.proxy_port != updated_proxy_port
149
+ or existing.authz != updated_authz
150
+ )
151
+
152
+ if not fields_changed:
153
+ # Nothing changed—do nothing
154
+ print(f"No changes detected for container {existing.metadata.name}.")
155
+ self.container = existing
156
+ return
157
+
158
+ print(
159
+ f"Detected changes for container {existing.metadata.name}, deleting and recreating."
160
+ )
161
+
162
+ # Construct the URL to delete the existing container
163
+ delete_url = (
164
+ f"{self.containers_url}/{existing.metadata.namespace}/{existing.metadata.name}"
165
+ if existing.metadata.namespace
166
+ else f"{self.containers_url}/{existing.metadata.name}"
167
+ )
168
+
169
+ # Delete the existing container
170
+ delete_response = requests.delete(
171
+ delete_url,
172
+ headers={"Authorization": f"Bearer {self.api_key}"},
173
+ )
174
+ delete_response.raise_for_status()
175
+ print(f"Deleted container {existing.metadata.name}")
176
+
177
+ # Now recreate the container using the updated parameters
178
+ create_request = V1ContainerRequest(
179
+ kind="Container",
180
+ platform=platform,
181
+ metadata=meta_request,
182
+ image=updated_image,
183
+ env=updated_env,
184
+ command=updated_command,
185
+ volumes=updated_volumes,
186
+ accelerators=updated_accelerators,
187
+ resources=updated_resources,
188
+ meters=updated_meters,
189
+ restart=updated_restart,
190
+ queue=updated_queue,
191
+ timeout=updated_timeout,
192
+ ssh_keys=ssh_keys,
193
+ ports=ports,
194
+ proxy_port=updated_proxy_port,
195
+ authz=updated_authz,
196
+ )
197
+ create_response = requests.post(
198
+ self.containers_url,
199
+ json=create_request.model_dump(),
200
+ headers={"Authorization": f"Bearer {self.api_key}"},
201
+ )
202
+ create_response.raise_for_status()
203
+ self.container = V1Container.model_validate(create_response.json())
204
+ print(f"Recreated container {self.container.metadata.name}")
205
+
206
+ # Save constructor params to `self` for reference, like you do in ReplayBuffer.
207
+ self.kind = "Container"
208
+ self.namespace = namespace
209
+ self.name = name
210
+ self.platform = platform
211
+ self.metadata = meta_request
212
+ self.image = image
213
+ self.env = env
214
+ self.command = command
215
+ self.volumes = volumes
216
+ self.accelerators = accelerators
217
+ self.resources = resources
218
+ self.meters = meters
219
+ self.restart = restart
220
+ self.queue = queue
221
+ self.timeout = timeout
222
+ self.ssh_keys = ssh_keys
223
+
224
+ @classmethod
225
+ def from_request(cls, request: V1ContainerRequest) -> V1Container:
226
+ return V1Container(**request.model_dump())
227
+
228
+ def delete(self) -> None:
229
+ """
230
+ Deletes the container by making a DELETE request to /v1/containers/:namespace/:name.
231
+ """
232
+ # Construct the url using instance attributes
233
+ delete_url = f"{self.containers_url}/{self.namespace}/{self.name}"
234
+
235
+ # Perform the deletion
236
+ response = requests.delete(
237
+ delete_url,
238
+ headers={"Authorization": f"Bearer {self.api_key}"},
239
+ )
240
+ response.raise_for_status()
241
+ print(f"Deleted container {self.name} in namespace {self.namespace}")
@@ -0,0 +1,187 @@
1
+ from enum import Enum
2
+ from typing import Dict, List, Optional
3
+
4
+ from pydantic import BaseModel, Field
5
+
6
+ from nebu.meta import V1ResourceMeta, V1ResourceMetaRequest
7
+
8
+
9
+ # 1) If you're still using V1ErrorResponse, no change needed here.
10
+ class V1ErrorResponse(BaseModel):
11
+ response_type: str = Field(default="ErrorResponse", alias="type")
12
+ request_id: str
13
+ error: str
14
+ traceback: Optional[str] = None
15
+
16
+
17
+ class V1Meter(BaseModel):
18
+ cost: Optional[float] = None
19
+ costp: Optional[float] = None
20
+ currency: str
21
+ unit: str
22
+ metric: str
23
+ json_path: Optional[str] = None
24
+
25
+
26
+ class V1EnvVar(BaseModel):
27
+ key: str
28
+ value: Optional[str] = None
29
+ secret_name: Optional[str] = None
30
+
31
+
32
+ class V1ContainerResources(BaseModel):
33
+ min_cpu: Optional[float] = None
34
+ min_memory: Optional[float] = None
35
+ max_cpu: Optional[float] = None
36
+ max_memory: Optional[float] = None
37
+
38
+
39
+ class V1SSHKey(BaseModel):
40
+ public_key: Optional[str] = None
41
+ public_key_secret: Optional[str] = None
42
+ copy_local: Optional[bool] = None
43
+
44
+
45
+ DEFAULT_RESTART_POLICY = "Never"
46
+
47
+
48
+ class V1VolumeDriver(str, Enum):
49
+ RCLONE_SYNC = "RCLONE_SYNC"
50
+ RCLONE_BISYNC = "RCLONE_BISYNC"
51
+ RCLONE_MOUNT = "RCLONE_MOUNT"
52
+ RCLONE_COPY = "RCLONE_COPY"
53
+
54
+
55
+ class V1VolumePath(BaseModel):
56
+ source: str
57
+ dest: str
58
+ resync: bool = False
59
+ continuous: bool = False
60
+ driver: V1VolumeDriver = V1VolumeDriver.RCLONE_SYNC
61
+
62
+
63
+ class V1VolumeConfig(BaseModel):
64
+ paths: List[V1VolumePath]
65
+ cache_dir: str = "/nebu/cache"
66
+
67
+
68
+ class V1ContainerStatus(BaseModel):
69
+ status: Optional[str] = None
70
+ message: Optional[str] = None
71
+ accelerator: Optional[str] = None
72
+ public_ip: Optional[str] = None
73
+ cost_per_hr: Optional[float] = None
74
+
75
+
76
+ class V1AuthzSecretRef(BaseModel):
77
+ name: Optional[str] = None
78
+ key: Optional[str] = None
79
+
80
+
81
+ class V1AuthzJwt(BaseModel):
82
+ secret_ref: Optional[V1AuthzSecretRef] = None
83
+
84
+
85
+ class V1AuthzPathMatch(BaseModel):
86
+ path: Optional[str] = None
87
+ pattern: Optional[str] = None
88
+
89
+
90
+ class V1AuthzFieldMatch(BaseModel):
91
+ json_path: Optional[str] = None
92
+ pattern: Optional[str] = None
93
+
94
+
95
+ class V1AuthzRuleMatch(BaseModel):
96
+ roles: Optional[List[str]] = None
97
+
98
+
99
+ class V1AuthzRule(BaseModel):
100
+ name: str
101
+ rule_match: Optional[V1AuthzRuleMatch] = Field(default=None, alias="match")
102
+ allow: bool
103
+ field_match: Optional[List[V1AuthzFieldMatch]] = None
104
+ path_match: Optional[List[V1AuthzPathMatch]] = None
105
+
106
+
107
+ class V1AuthzConfig(BaseModel):
108
+ enabled: bool = False
109
+ default_action: str = "deny"
110
+ auth_type: str = "jwt"
111
+ jwt: Optional[V1AuthzJwt] = None
112
+ rules: Optional[List[V1AuthzRule]] = None
113
+
114
+
115
+ class V1PortRequest(BaseModel):
116
+ port: int
117
+ protocol: Optional[str] = None
118
+ public: Optional[bool] = None
119
+
120
+
121
+ class V1Port(BaseModel):
122
+ port: int
123
+ protocol: Optional[str] = None
124
+ public_ip: Optional[str] = None
125
+
126
+
127
+ class V1ContainerRequest(BaseModel):
128
+ kind: str = Field(default="Container")
129
+ platform: Optional[str] = None
130
+ metadata: Optional[V1ResourceMetaRequest] = None
131
+ image: str
132
+ env: Optional[List[V1EnvVar]] = None
133
+ command: Optional[str] = None
134
+ volumes: Optional[List[V1VolumePath]] = None
135
+ accelerators: Optional[List[str]] = None
136
+ resources: Optional[V1ContainerResources] = None
137
+ meters: Optional[List[V1Meter]] = None
138
+ restart: str = Field(default=DEFAULT_RESTART_POLICY)
139
+ queue: Optional[str] = None
140
+ timeout: Optional[str] = None
141
+ ssh_keys: Optional[List[V1SSHKey]] = None
142
+ ports: Optional[List[V1PortRequest]] = None
143
+ proxy_port: Optional[int] = None
144
+ authz: Optional[V1AuthzConfig] = None
145
+
146
+
147
+ class V1Container(BaseModel):
148
+ kind: str = Field(default="Container")
149
+ platform: str
150
+ metadata: V1ResourceMeta
151
+ image: str
152
+ env: Optional[List[V1EnvVar]] = None
153
+ command: Optional[str] = None
154
+ volumes: Optional[List[V1VolumePath]] = None
155
+ accelerators: Optional[List[str]] = None
156
+ meters: Optional[List[V1Meter]] = None
157
+ restart: str = Field(default=DEFAULT_RESTART_POLICY)
158
+ queue: Optional[str] = None
159
+ timeout: Optional[str] = None
160
+ resources: Optional[V1ContainerResources] = None
161
+ status: Optional[V1ContainerStatus] = None
162
+ ssh_keys: Optional[List[V1SSHKey]] = None
163
+ ports: Optional[List[V1Port]] = None
164
+ proxy_port: Optional[int] = None
165
+ authz: Optional[V1AuthzConfig] = None
166
+
167
+
168
+ class V1UpdateContainer(BaseModel):
169
+ image: Optional[str] = None
170
+ env: Optional[List[V1EnvVar]] = None
171
+ command: Optional[str] = None
172
+ volumes: Optional[List[V1VolumePath]] = None
173
+ accelerators: Optional[List[str]] = None
174
+ labels: Optional[Dict[str, str]] = None
175
+ cpu_request: Optional[str] = None
176
+ memory_request: Optional[str] = None
177
+ platform: Optional[str] = None
178
+ meters: Optional[List[V1Meter]] = None
179
+ restart: Optional[str] = None
180
+ queue: Optional[str] = None
181
+ timeout: Optional[str] = None
182
+ resources: Optional[V1ContainerResources] = None
183
+ proxy_port: Optional[int] = None
184
+
185
+
186
+ class V1Containers(BaseModel):
187
+ containers: List[V1Container]
@@ -0,0 +1,24 @@
1
+ from typing import Dict, Optional
2
+
3
+ from pydantic import BaseModel
4
+
5
+
6
+ # Match Rust "V1ResourceMetaRequest" struct
7
+ class V1ResourceMetaRequest(BaseModel):
8
+ name: Optional[str] = None
9
+ namespace: Optional[str] = None
10
+ labels: Optional[Dict[str, str]] = None
11
+ owner: Optional[str] = None
12
+ owner_ref: Optional[str] = None
13
+
14
+
15
+ class V1ResourceMeta(BaseModel):
16
+ name: str
17
+ namespace: str
18
+ id: str
19
+ owner: str
20
+ created_at: int
21
+ updated_at: int
22
+ created_by: str
23
+ owner_ref: Optional[str] = None
24
+ labels: Optional[Dict[str, str]] = None
@@ -0,0 +1,67 @@
1
+ from typing import Any, Optional
2
+
3
+ from pydantic import BaseModel, Field
4
+
5
+ from nebu.containers.models import V1Container
6
+ from nebu.meta import V1ResourceMeta, V1ResourceMetaRequest
7
+
8
+ # If these are in another module, import them as:
9
+ # from .containers import V1Container, V1ResourceMeta, V1ResourceMetaRequest
10
+ # For demonstration, simply assume they're available in scope:
11
+ # class V1Container(BaseModel): ...
12
+ # class V1ResourceMeta(BaseModel): ...
13
+ # class V1ResourceMetaRequest(BaseModel): ...
14
+
15
+
16
+ class V1ProcessorStatus(BaseModel):
17
+ status: Optional[str] = None
18
+ message: Optional[str] = None
19
+ pressure: Optional[int] = None
20
+
21
+
22
+ class V1ScaleUp(BaseModel):
23
+ above_pressure: Optional[int] = None
24
+ duration: Optional[str] = None
25
+
26
+
27
+ class V1ScaleDown(BaseModel):
28
+ below_pressure: Optional[int] = None
29
+ duration: Optional[str] = None
30
+
31
+
32
+ class V1ScaleZero(BaseModel):
33
+ duration: Optional[str] = None
34
+
35
+
36
+ class V1Scale(BaseModel):
37
+ up: Optional[V1ScaleUp] = None
38
+ down: Optional[V1ScaleDown] = None
39
+ zero: Optional[V1ScaleZero] = None
40
+
41
+
42
+ DEFAULT_PROCESSOR_KIND = "Processor"
43
+
44
+
45
+ class V1Processor(BaseModel):
46
+ kind: str = Field(default=DEFAULT_PROCESSOR_KIND)
47
+ metadata: V1ResourceMeta
48
+ container: Optional["V1Container"] = None
49
+ stream: Optional[str] = None
50
+ schema_: Optional[Any] = None # Or Dict[str, Any], if you know the schema format
51
+ common_schema: Optional[str] = None
52
+ min_replicas: Optional[int] = None
53
+ max_replicas: Optional[int] = None
54
+ scale: Optional[V1Scale] = None
55
+ status: Optional[V1ProcessorStatus] = None
56
+
57
+
58
+ class V1ProcessorRequest(BaseModel):
59
+ kind: str = Field(default=DEFAULT_PROCESSOR_KIND)
60
+ metadata: V1ResourceMetaRequest
61
+ container: Optional["V1Container"] = None
62
+ stream: Optional[str] = None
63
+ schema_: Optional[Any] = None
64
+ common_schema: Optional[str] = None
65
+ min_replicas: Optional[int] = None
66
+ max_replicas: Optional[int] = None
67
+ scale: Optional[V1Scale] = None
File without changes
@@ -0,0 +1,45 @@
1
+ from typing import Optional
2
+
3
+ from openai.types.chat.completion_create_params import CompletionCreateParamsBase
4
+ from openai.types.responses import Response
5
+ from pydantic import BaseModel
6
+
7
+
8
+ class V1StreamMessage(BaseModel):
9
+ kind: str = "V1StreamMessage"
10
+ id: str
11
+ content: dict # type: ignore
12
+ created_at: int
13
+ return_stream: Optional[str] = None
14
+ user_id: Optional[str] = None
15
+ organizations: Optional[dict] = None # type: ignore
16
+ handle: Optional[str] = None
17
+ adapter: Optional[str] = None
18
+
19
+
20
+ class V1StreamResponseMessage(BaseModel):
21
+ kind: str = "V1StreamResponseMessage"
22
+ id: str
23
+ content: dict # type: ignore
24
+ created_at: int
25
+ user_id: Optional[str] = None
26
+
27
+
28
+ class V1OpenAIStreamMessage(BaseModel):
29
+ kind: str = "V1OpenAIStreamMessage"
30
+ id: str
31
+ content: CompletionCreateParamsBase
32
+ created_at: int
33
+ return_stream: Optional[str] = None
34
+ user_id: Optional[str] = None
35
+ organizations: Optional[dict] = None # type: ignore
36
+ handle: Optional[str] = None
37
+ adapter: Optional[str] = None
38
+
39
+
40
+ class V1OpenAIStreamResponse(BaseModel):
41
+ kind: str = "V1OpenAIStreamResponse"
42
+ id: str
43
+ content: Response
44
+ created_at: int
45
+ user_id: Optional[str] = None
File without changes
@@ -0,0 +1,58 @@
1
+ Metadata-Version: 2.4
2
+ Name: nebu
3
+ Version: 0.1.0
4
+ Summary: A globally distributed container runtime
5
+ Requires-Python: >=3.10.14
6
+ Description-Content-Type: text/markdown
7
+ License-File: LICENSE
8
+ Requires-Dist: openai>=1.68.2
9
+ Requires-Dist: pydantic>=2.10.6
10
+ Requires-Dist: pyyaml>=6.0.2
11
+ Requires-Dist: requests>=2.32.3
12
+ Dynamic: license-file
13
+
14
+ # nebulous-py
15
+ A python library for the [Nebulous runtime](https://github.com/agentsea/nebulous)
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ pip install nebu
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ```python
26
+ from nebu import Container, V1EnvVar, V1ResourceMeta
27
+
28
+ container = Container(
29
+ metadata=V1ResourceMeta(
30
+ name="pytorch-example",
31
+ namespace="test",
32
+ ),
33
+ image="pytorch/pytorch:latest",
34
+ platform="runpod",
35
+ env=[V1EnvVar(name="MY_ENV_VAR", value="my-value")],
36
+ command="nvidia-smi",
37
+ accelerators=["1:A100_SXM"],
38
+ proxy_port=8080,
39
+ )
40
+
41
+ while container.status.status.lower() != "running":
42
+ print(f"Container '{container.metadata.name}' is not running, it is '{container.status.status}', waiting...")
43
+ time.sleep(1)
44
+
45
+ print(f"Container '{container.metadata.name}' is running")
46
+
47
+ print(f"You can access the container at {container.status.tailnet_url}")
48
+ ```
49
+
50
+ ## Contributing
51
+
52
+ Please open an issue or a PR to contribute to the project.
53
+
54
+ ## Development
55
+
56
+ ```bash
57
+ make test
58
+ ```
@@ -0,0 +1,18 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/nebu/__init__.py
5
+ src/nebu/config.py
6
+ src/nebu/meta.py
7
+ src/nebu.egg-info/PKG-INFO
8
+ src/nebu.egg-info/SOURCES.txt
9
+ src/nebu.egg-info/dependency_links.txt
10
+ src/nebu.egg-info/requires.txt
11
+ src/nebu.egg-info/top_level.txt
12
+ src/nebu/containers/container.py
13
+ src/nebu/containers/models.py
14
+ src/nebu/processors/models.py
15
+ src/nebu/processors/processor.py
16
+ src/nebu/redis/models.py
17
+ src/nebu/services/service.py
18
+ tests/test_containers.py
@@ -0,0 +1,4 @@
1
+ openai>=1.68.2
2
+ pydantic>=2.10.6
3
+ pyyaml>=6.0.2
4
+ requests>=2.32.3
@@ -0,0 +1 @@
1
+ nebu
@@ -0,0 +1,84 @@
1
+ import random
2
+ import string
3
+
4
+ import pytest
5
+
6
+ from nebu.config import GlobalConfig
7
+ from nebu.containers.container import Container
8
+
9
+
10
+ @pytest.fixture
11
+ def random_container_name() -> str:
12
+ """Generate a random container name to avoid collisions."""
13
+ suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
14
+ return f"test-container-{suffix}"
15
+
16
+
17
+ @pytest.fixture
18
+ def global_config() -> GlobalConfig:
19
+ """
20
+ Set your real API key and server here or ensure GlobalConfig.read()
21
+ is retrieving valid values for these.
22
+ """
23
+ return GlobalConfig.read()
24
+
25
+
26
+ def test_container_integration(global_config: GlobalConfig, random_container_name: str):
27
+ """
28
+ Single end-to-end test that:
29
+ 1) Creates a container.
30
+ 2) Creates it again with no changes (should detect no differences).
31
+ 3) Updates a field (should trigger a recreate).
32
+ 4) Deletes the container.
33
+ """
34
+
35
+ # 1) Create container
36
+ container_instance = Container(
37
+ name=random_container_name,
38
+ image="pytorch/pytorch:latest",
39
+ command="nvidia-smi",
40
+ platform="runpod",
41
+ accelerators=["1:L4"],
42
+ config=global_config,
43
+ restart="Never",
44
+ )
45
+ assert container_instance.container is not None, "Container object should be set."
46
+ assert container_instance.container.metadata.name == random_container_name
47
+ print(f"Created container {random_container_name}")
48
+
49
+ # 2) Attempt to create again with no changes
50
+ same_params_instance = Container(
51
+ name=random_container_name,
52
+ image="pytorch/pytorch:latest",
53
+ command="nvidia-smi",
54
+ platform="runpod",
55
+ accelerators=["1:L4"],
56
+ config=global_config,
57
+ restart="Never",
58
+ )
59
+ assert (
60
+ same_params_instance.container is not None
61
+ ), "Container object should remain set for no-change scenario."
62
+ # If your code prints something like "No changes detected..." this is good.
63
+ print(f"No changes detected for container {random_container_name}")
64
+
65
+ # 3) Update the image to trigger a recreate
66
+ updated_container_instance = Container(
67
+ name=random_container_name,
68
+ image="pytorch/pytorch:latest",
69
+ command="ls -la /",
70
+ platform="runpod",
71
+ accelerators=["1:L4"],
72
+ config=global_config,
73
+ restart="Never",
74
+ )
75
+ assert (
76
+ updated_container_instance.container is not None
77
+ ), "Updated container should be set."
78
+ assert (
79
+ updated_container_instance.container.command == "ls -la /"
80
+ ), "Container image should have been updated."
81
+ print(f"Updated container image to python:3.10-slim for {random_container_name}")
82
+
83
+ # 4) Delete the container
84
+ updated_container_instance.delete() # Hypothetical method you plan to add