fcvm 0.7.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.
fcvm-0.7.0/LICENSE ADDED
@@ -0,0 +1,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
fcvm-0.7.0/NOTICE ADDED
@@ -0,0 +1,12 @@
1
+ fcvm
2
+ Copyright 2026 Carlos Bravo
3
+ https://github.com/carlosbravoa/fcvm
4
+ https://cabra-consulting.com/
5
+
6
+ This product is licensed under the Apache License, Version 2.0 (see LICENSE).
7
+
8
+ It includes xterm.js and its fit addon (lib/web/static/vendor/):
9
+ Copyright (c) 2017-2019, The xterm.js authors
10
+ Copyright (c) 2014-2016, SourceLair Private Company
11
+ Copyright (c) 2012-2013, Christopher Jeffrey
12
+ licensed under the MIT License (see lib/web/static/vendor/LICENSE.xterm).
fcvm-0.7.0/PKG-INFO ADDED
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: fcvm
3
+ Version: 0.7.0
4
+ Summary: A client for the fcvm HTTP API: Firecracker microVM sandboxes from Python
5
+ Author: Carlos Bravo
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/carlosbravoa/fcvm
8
+ Project-URL: Documentation, https://github.com/carlosbravoa/fcvm/blob/main/sdk/README.md
9
+ Project-URL: Issues, https://github.com/carlosbravoa/fcvm/issues
10
+ Project-URL: Changelog, https://github.com/carlosbravoa/fcvm/blob/main/CHANGELOG.md
11
+ Keywords: firecracker,microvm,sandbox,ai-agents,virtualization,isolation
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Software Development :: Testing
18
+ Classifier: Topic :: System :: Emulators
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ License-File: NOTICE
23
+ Dynamic: license-file
24
+
25
+ # fcvm for Python
26
+
27
+ A client for the HTTP API of [fcvm](https://github.com/carlosbravoa/fcvm),
28
+ which runs disposable, isolated Firecracker microVMs with container
29
+ ergonomics. Use it to give an agent framework, a test harness or a build
30
+ pipeline real VM sandboxes: create one from any OCI image, run commands,
31
+ move files, snapshot it and fork running copies in about 150 ms.
32
+
33
+ The client has no dependencies and needs Python 3.9 or newer. The VMs run
34
+ on a Linux host with KVM where fcvm is installed; the client itself runs
35
+ anywhere that can reach that host's API.
36
+
37
+ ```sh
38
+ pip install fcvm
39
+ ```
40
+
41
+ ```python
42
+ from fcvm import Client
43
+
44
+ c = Client()
45
+ with c.create("box", template="python-sandbox", ttl="1h") as sb: # removed when the block ends
46
+ out = sb.run("pip install -q requests && python -c 'import requests; print(requests.__version__)'")
47
+ sb.write_file("/work/app.py", "print('hi')\n")
48
+ print(sb.exec("python /work/app.py").stdout) # ExecResult: exit_code, stdout, stderr
49
+ job = sb.exec("python -m http.server 8000", background=True) # a Job
50
+ port = sb.publish(8000) # http://127.0.0.1:{port} on the host
51
+ job.kill()
52
+
53
+ snap = c.sandbox("prepared").snapshot("ready")
54
+ forks = snap.fork("try", count=3) # three running Sandbox objects
55
+ ```
56
+
57
+ `Client()` finds the local fcvm service by itself. For another host, set
58
+ `FCVM_URL` and `FCVM_TOKEN`. The token gives full control of fcvm, so treat
59
+ it like an SSH key.
60
+
61
+ - [All methods](https://github.com/carlosbravoa/fcvm/blob/main/sdk/README.md)
62
+ - [The HTTP API](https://github.com/carlosbravoa/fcvm/blob/main/docs/api.md)
63
+ - [Installing fcvm](https://github.com/carlosbravoa/fcvm/blob/main/docs/getting-started.md)
64
+
65
+ Apache License 2.0.
fcvm-0.7.0/README.md ADDED
@@ -0,0 +1,41 @@
1
+ # fcvm for Python
2
+
3
+ A client for the HTTP API of [fcvm](https://github.com/carlosbravoa/fcvm),
4
+ which runs disposable, isolated Firecracker microVMs with container
5
+ ergonomics. Use it to give an agent framework, a test harness or a build
6
+ pipeline real VM sandboxes: create one from any OCI image, run commands,
7
+ move files, snapshot it and fork running copies in about 150 ms.
8
+
9
+ The client has no dependencies and needs Python 3.9 or newer. The VMs run
10
+ on a Linux host with KVM where fcvm is installed; the client itself runs
11
+ anywhere that can reach that host's API.
12
+
13
+ ```sh
14
+ pip install fcvm
15
+ ```
16
+
17
+ ```python
18
+ from fcvm import Client
19
+
20
+ c = Client()
21
+ with c.create("box", template="python-sandbox", ttl="1h") as sb: # removed when the block ends
22
+ out = sb.run("pip install -q requests && python -c 'import requests; print(requests.__version__)'")
23
+ sb.write_file("/work/app.py", "print('hi')\n")
24
+ print(sb.exec("python /work/app.py").stdout) # ExecResult: exit_code, stdout, stderr
25
+ job = sb.exec("python -m http.server 8000", background=True) # a Job
26
+ port = sb.publish(8000) # http://127.0.0.1:{port} on the host
27
+ job.kill()
28
+
29
+ snap = c.sandbox("prepared").snapshot("ready")
30
+ forks = snap.fork("try", count=3) # three running Sandbox objects
31
+ ```
32
+
33
+ `Client()` finds the local fcvm service by itself. For another host, set
34
+ `FCVM_URL` and `FCVM_TOKEN`. The token gives full control of fcvm, so treat
35
+ it like an SSH key.
36
+
37
+ - [All methods](https://github.com/carlosbravoa/fcvm/blob/main/sdk/README.md)
38
+ - [The HTTP API](https://github.com/carlosbravoa/fcvm/blob/main/docs/api.md)
39
+ - [Installing fcvm](https://github.com/carlosbravoa/fcvm/blob/main/docs/getting-started.md)
40
+
41
+ Apache License 2.0.
@@ -0,0 +1,65 @@
1
+ Metadata-Version: 2.4
2
+ Name: fcvm
3
+ Version: 0.7.0
4
+ Summary: A client for the fcvm HTTP API: Firecracker microVM sandboxes from Python
5
+ Author: Carlos Bravo
6
+ License-Expression: Apache-2.0
7
+ Project-URL: Homepage, https://github.com/carlosbravoa/fcvm
8
+ Project-URL: Documentation, https://github.com/carlosbravoa/fcvm/blob/main/sdk/README.md
9
+ Project-URL: Issues, https://github.com/carlosbravoa/fcvm/issues
10
+ Project-URL: Changelog, https://github.com/carlosbravoa/fcvm/blob/main/CHANGELOG.md
11
+ Keywords: firecracker,microvm,sandbox,ai-agents,virtualization,isolation
12
+ Classifier: Development Status :: 4 - Beta
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Operating System :: OS Independent
15
+ Classifier: Programming Language :: Python :: 3
16
+ Classifier: Topic :: Security
17
+ Classifier: Topic :: Software Development :: Testing
18
+ Classifier: Topic :: System :: Emulators
19
+ Requires-Python: >=3.9
20
+ Description-Content-Type: text/markdown
21
+ License-File: LICENSE
22
+ License-File: NOTICE
23
+ Dynamic: license-file
24
+
25
+ # fcvm for Python
26
+
27
+ A client for the HTTP API of [fcvm](https://github.com/carlosbravoa/fcvm),
28
+ which runs disposable, isolated Firecracker microVMs with container
29
+ ergonomics. Use it to give an agent framework, a test harness or a build
30
+ pipeline real VM sandboxes: create one from any OCI image, run commands,
31
+ move files, snapshot it and fork running copies in about 150 ms.
32
+
33
+ The client has no dependencies and needs Python 3.9 or newer. The VMs run
34
+ on a Linux host with KVM where fcvm is installed; the client itself runs
35
+ anywhere that can reach that host's API.
36
+
37
+ ```sh
38
+ pip install fcvm
39
+ ```
40
+
41
+ ```python
42
+ from fcvm import Client
43
+
44
+ c = Client()
45
+ with c.create("box", template="python-sandbox", ttl="1h") as sb: # removed when the block ends
46
+ out = sb.run("pip install -q requests && python -c 'import requests; print(requests.__version__)'")
47
+ sb.write_file("/work/app.py", "print('hi')\n")
48
+ print(sb.exec("python /work/app.py").stdout) # ExecResult: exit_code, stdout, stderr
49
+ job = sb.exec("python -m http.server 8000", background=True) # a Job
50
+ port = sb.publish(8000) # http://127.0.0.1:{port} on the host
51
+ job.kill()
52
+
53
+ snap = c.sandbox("prepared").snapshot("ready")
54
+ forks = snap.fork("try", count=3) # three running Sandbox objects
55
+ ```
56
+
57
+ `Client()` finds the local fcvm service by itself. For another host, set
58
+ `FCVM_URL` and `FCVM_TOKEN`. The token gives full control of fcvm, so treat
59
+ it like an SSH key.
60
+
61
+ - [All methods](https://github.com/carlosbravoa/fcvm/blob/main/sdk/README.md)
62
+ - [The HTTP API](https://github.com/carlosbravoa/fcvm/blob/main/docs/api.md)
63
+ - [Installing fcvm](https://github.com/carlosbravoa/fcvm/blob/main/docs/getting-started.md)
64
+
65
+ Apache License 2.0.
@@ -0,0 +1,9 @@
1
+ LICENSE
2
+ NOTICE
3
+ README.md
4
+ fcvm.py
5
+ pyproject.toml
6
+ fcvm.egg-info/PKG-INFO
7
+ fcvm.egg-info/SOURCES.txt
8
+ fcvm.egg-info/dependency_links.txt
9
+ fcvm.egg-info/top_level.txt
@@ -0,0 +1 @@
1
+ fcvm
fcvm-0.7.0/fcvm.py ADDED
@@ -0,0 +1,382 @@
1
+ """fcvm: a client for the fcvm HTTP API (fcvm serve, or the fcvm service).
2
+
3
+ from fcvm import Client
4
+
5
+ c = Client() # the local server: vms/.serve.json, or FCVM_URL + FCVM_TOKEN
6
+ with c.create("box", template="python-sandbox", ttl="1h") as sb:
7
+ r = sb.exec("pip install -q requests && python -c 'import requests; print(requests.__version__)'")
8
+ print(r.exit_code, r.stdout)
9
+ sb.write_file("/work/app.py", "print('hi')\\n")
10
+ job = sb.exec("python -m http.server 8000", background=True)
11
+ port = sb.publish(8000) # http://127.0.0.1:PORT on the host
12
+ # the sandbox is removed when the block ends
13
+
14
+ Everything maps onto the API documented in docs/api.md, which maps onto the
15
+ CLI. Standard library only; Python 3.9+.
16
+ """
17
+ import json
18
+ import os
19
+ import shutil
20
+ import subprocess
21
+ import time
22
+ import urllib.error
23
+ import urllib.parse
24
+ import urllib.request
25
+
26
+ __all__ = ["Client", "Sandbox", "Snapshot", "Job", "ServerJob", "ExecResult", "FcvmError"]
27
+ __version__ = "0.7.0"
28
+
29
+
30
+ class FcvmError(Exception):
31
+ """An error from the server: `status` is the HTTP status, the message fcvm's."""
32
+
33
+ def __init__(self, status, message):
34
+ super().__init__(message)
35
+ self.status = status
36
+
37
+
38
+ class ExecResult:
39
+ def __init__(self, d):
40
+ self.exit_code = d.get("exit_code")
41
+ self.stdout = d.get("stdout", "")
42
+ self.stderr = d.get("stderr", "")
43
+ self.timed_out = bool(d.get("timed_out"))
44
+
45
+ @property
46
+ def ok(self):
47
+ return self.exit_code == 0
48
+
49
+ def check(self):
50
+ """self, or FcvmError when the command failed."""
51
+ if not self.ok:
52
+ raise FcvmError(0, f"command exited {self.exit_code}: {self.stderr.strip() or self.stdout.strip()}")
53
+ return self
54
+
55
+ def __repr__(self):
56
+ return f"ExecResult(exit_code={self.exit_code}, stdout={self.stdout!r}, stderr={self.stderr!r})"
57
+
58
+
59
+ def discover():
60
+ """(url, token) of the local server, from the environment or vms/.serve.json."""
61
+ if os.environ.get("FCVM_URL") and os.environ.get("FCVM_TOKEN"):
62
+ return os.environ["FCVM_URL"].rstrip("/"), os.environ["FCVM_TOKEN"]
63
+ homes = [os.environ.get("FCVM_HOME"), os.path.join(os.environ.get("XDG_DATA_HOME") or os.path.expanduser("~/.local/share"), "fcvm")]
64
+ if shutil.which("fcvm"): # an fcvm run from a checkout keeps its state in the checkout
65
+ try:
66
+ homes.append(subprocess.run(["fcvm", "_home"], capture_output=True, text=True, timeout=10).stdout.strip())
67
+ except (OSError, subprocess.SubprocessError):
68
+ pass
69
+ for home in filter(None, homes):
70
+ try:
71
+ with open(os.path.join(home, "vms", ".serve.json")) as f:
72
+ s = json.load(f)
73
+ return s["url"].split("/?")[0], s["token"]
74
+ except (OSError, ValueError, KeyError):
75
+ continue
76
+ raise FcvmError(0, "no fcvm server found: run `fcvm serve` (or `fcvm service install`), or set FCVM_URL and FCVM_TOKEN")
77
+
78
+
79
+ class Client:
80
+ def __init__(self, url=None, token=None, timeout=600):
81
+ if not (url and token):
82
+ url, token = discover()
83
+ self.url, self.token, self.timeout = url.rstrip("/"), token, timeout
84
+
85
+ # --- plumbing ---------------------------------------------------------------------
86
+ def request(self, method, path, body=None, params=None, data=None, raw=False):
87
+ url = f"{self.url}/api/{path.lstrip('/')}"
88
+ if params:
89
+ url += "?" + urllib.parse.urlencode({k: v for k, v in params.items() if v is not None})
90
+ headers = {"Authorization": f"Bearer {self.token}"}
91
+ payload = data
92
+ if body is not None:
93
+ payload, headers["Content-Type"] = json.dumps(body).encode(), "application/json"
94
+ req = urllib.request.Request(url, data=payload, method=method, headers=headers)
95
+ try:
96
+ with urllib.request.urlopen(req, timeout=self.timeout) as r:
97
+ content = r.read()
98
+ except urllib.error.HTTPError as e:
99
+ try:
100
+ message = json.loads(e.read().decode())["error"]
101
+ except (ValueError, KeyError):
102
+ message = f"HTTP {e.code}"
103
+ raise FcvmError(e.code, message) from None
104
+ except urllib.error.URLError as e:
105
+ raise FcvmError(0, f"cannot reach {self.url}: {e.reason}") from None
106
+ if raw:
107
+ return content
108
+ return json.loads(content) if content else None
109
+
110
+ def get(self, path, /, **params): # positional-only: a query parameter may be named path
111
+ return self.request("GET", path, params=params or None)
112
+
113
+ def post(self, path, /, body=None):
114
+ return self.request("POST", path, body=body or {})
115
+
116
+ def delete(self, path, /, **params):
117
+ return self.request("DELETE", path, params=params or None)
118
+
119
+ # --- the host -------------------------------------------------------------------------
120
+ def host(self):
121
+ return self.get("host")
122
+
123
+ def vms(self):
124
+ return [Sandbox(self, v["name"], v) for v in self.get("vms")]
125
+
126
+ def sandbox(self, name):
127
+ """An existing VM by name (checked)."""
128
+ return Sandbox(self, name, self.get(f"vms/{name}"))
129
+
130
+ def images(self):
131
+ return self.get("images")
132
+
133
+ def templates(self):
134
+ return self.get("templates")
135
+
136
+ def snapshots(self):
137
+ return [Snapshot(self, s["name"], s) for s in self.get("snapshots")]
138
+
139
+ def volumes(self):
140
+ return self.get("volumes")
141
+
142
+ def pools(self):
143
+ return self.get("pools")
144
+
145
+ def import_image(self, ref, name=None):
146
+ """Start an import; returns a ServerJob to wait on."""
147
+ return ServerJob(self, self.post("images", {"ref": ref, **({"name": name} if name else {})}))
148
+
149
+ def create(self, name, image=None, template=None, start=True, **opts):
150
+ """Create (and start) a VM. opts are the fields of POST /vms: vcpus, mem_mib,
151
+ network ("full"|"none"|"restricted"), allow, ports, volumes, idle, command,
152
+ jail, restart, ttl, idle_stop, secrets ({NAME: value}), forward, cache, disk,
153
+ copy, entrypoint. With a template, its fields come first and opts override."""
154
+ body = {}
155
+ if template:
156
+ t = next((t for t in self.templates() if t["name"] == template), None)
157
+ if not t:
158
+ raise FcvmError(404, f"no template '{template}'")
159
+ body = {k: v for k, v in t.items() if k not in ("name", "builtin", "description", "process", "command", "secrets")}
160
+ if t["process"] == "idle":
161
+ body["idle"] = True
162
+ elif t["process"] == "command":
163
+ body["command"] = " ".join(_shell_quote(a) for a in t["command"])
164
+ secrets = {n: os.environ[n] for n in t.get("secrets", []) if n in os.environ}
165
+ if secrets:
166
+ body["secrets"] = secrets
167
+ if image:
168
+ body["image"] = image
169
+ if "image" not in body:
170
+ raise FcvmError(400, "give an image or a template")
171
+ if "command" in opts and isinstance(opts["command"], (list, tuple)):
172
+ opts["command"] = " ".join(_shell_quote(a) for a in opts["command"])
173
+ body.update({k: v for k, v in opts.items() if v is not None})
174
+ body.update({"name": name, "start": start})
175
+ return Sandbox(self, name, self.post("vms", body))
176
+
177
+ def claim(self, pool, ttl=None, idle_stop=None):
178
+ """A ready VM out of a warm pool."""
179
+ info = self.post(f"pools/{pool}/claim", {k: v for k, v in (("ttl", ttl), ("idle_stop", idle_stop)) if v})
180
+ return Sandbox(self, info["name"], info)
181
+
182
+
183
+ def _shell_quote(a):
184
+ import re
185
+ return a if re.fullmatch(r"[\w@%+=:,./-]+", a) else "'" + a.replace("'", "'\\''") + "'"
186
+
187
+
188
+ class Sandbox:
189
+ """A VM. Methods map onto the API's /vms/{name}/... endpoints."""
190
+
191
+ def __init__(self, client, name, info=None):
192
+ self.client, self.name, self._info = client, name, info
193
+
194
+ def __repr__(self):
195
+ return f"Sandbox({self.name!r})"
196
+
197
+ def __enter__(self):
198
+ return self
199
+
200
+ def __exit__(self, *exc):
201
+ self.remove()
202
+
203
+ def info(self):
204
+ self._info = self.client.get(f"vms/{self.name}")
205
+ return self._info
206
+
207
+ @property
208
+ def state(self):
209
+ return self.info()["state"]
210
+
211
+ @property
212
+ def ip(self):
213
+ return self.info().get("ip")
214
+
215
+ # commands ----------------------------------------------------------------------------
216
+ def exec(self, command=None, argv=None, workdir=None, env=None, user=None, stdin=None, timeout=300, background=False):
217
+ """Run a shell command (or an exact argv). Returns an ExecResult, or a Job with background=True."""
218
+ body = {"command": command, "argv": argv, "workdir": workdir, "env": env, "user": user,
219
+ "stdin": stdin, "timeout": timeout, "background": background}
220
+ r = self.client.post(f"vms/{self.name}/exec", {k: v for k, v in body.items() if v is not None and v is not False})
221
+ return Job(self, r["job"]) if background else ExecResult(r)
222
+
223
+ def run(self, command, **kw):
224
+ """exec, raising when the command fails; returns its stdout."""
225
+ return self.exec(command, **kw).check().stdout
226
+
227
+ def jobs(self):
228
+ return [Job(self, j["id"], j) for j in self.client.get(f"vms/{self.name}/jobs")]
229
+
230
+ def job(self, job_id):
231
+ return Job(self, job_id)
232
+
233
+ # files -------------------------------------------------------------------------------
234
+ def read_file(self, path):
235
+ return self.client.request("GET", f"vms/{self.name}/file", params={"path": path}, raw=True)
236
+
237
+ def read_text(self, path, encoding="utf-8"):
238
+ return self.read_file(path).decode(encoding)
239
+
240
+ def write_file(self, path, data, mode=None):
241
+ if isinstance(data, str):
242
+ data = data.encode()
243
+ return self.client.request("PUT", f"vms/{self.name}/file", params={"path": path, "mode": mode}, data=data)
244
+
245
+ def ls(self, path="/"):
246
+ return self.client.get(f"vms/{self.name}/files", path=path)["entries"]
247
+
248
+ def mkdir(self, path):
249
+ return self.client.post(f"vms/{self.name}/files", {"op": "mkdir", "path": path})
250
+
251
+ def remove_path(self, path):
252
+ return self.client.post(f"vms/{self.name}/files", {"op": "remove", "path": path})
253
+
254
+ def rename(self, path, to):
255
+ return self.client.post(f"vms/{self.name}/files", {"op": "rename", "path": path, "to": to})
256
+
257
+ def mount(self, host, path=None, ro=False):
258
+ return self.client.post(f"vms/{self.name}/mounts", {"host": host, "path": path or "", "ro": ro})
259
+
260
+ def umount(self, path):
261
+ return self.client.delete(f"vms/{self.name}/mounts", path=path)
262
+
263
+ # ports -------------------------------------------------------------------------------
264
+ def publish(self, guest_port, host_port=None, bind=None):
265
+ """Publish a port; returns the host port (a free one unless given)."""
266
+ spec = f"{bind + ':' if bind else ''}{host_port or ''}:{int(guest_port)}"
267
+ info = self.client.post(f"vms/{self.name}/ports", {"port": spec})
268
+ return int(info["ports"][-1].split(":")[-2])
269
+
270
+ def unpublish(self, host_port):
271
+ return self.client.delete(f"vms/{self.name}/ports", port=str(host_port))
272
+
273
+ # lifecycle ---------------------------------------------------------------------------
274
+ def start(self):
275
+ return self.client.post(f"vms/{self.name}/start")
276
+
277
+ def stop(self):
278
+ return self.client.post(f"vms/{self.name}/stop")
279
+
280
+ def restart(self):
281
+ return self.client.post(f"vms/{self.name}/restart")
282
+
283
+ def remove(self):
284
+ return self.client.delete(f"vms/{self.name}")
285
+
286
+ def update(self, **fields):
287
+ """restart, ttl, idle_stop (None clears), secrets ({NAME: value}), unset_secrets, forward."""
288
+ return self.client.post(f"vms/{self.name}/update", fields)
289
+
290
+ def snapshot(self, name):
291
+ self.client.post(f"vms/{self.name}/snapshot", {"name": name})
292
+ return Snapshot(self.client, name)
293
+
294
+ def commit(self, image):
295
+ self.client.post(f"vms/{self.name}/commit", {"image": image})
296
+ return image
297
+
298
+ def logs(self):
299
+ return self.client.get(f"vms/{self.name}/logs")["log"]
300
+
301
+ def egress(self):
302
+ return self.client.get(f"vms/{self.name}/egress")["text"]
303
+
304
+ def balloon(self, mib=None):
305
+ if mib is None:
306
+ return self.client.get(f"vms/{self.name}/balloon")
307
+ return self.client.post(f"vms/{self.name}/balloon", {"mib": int(mib)})
308
+
309
+ def processes(self):
310
+ return self.client.get(f"vms/{self.name}/processes")
311
+
312
+ def stats(self, range="10m"):
313
+ return self.client.get(f"vms/{self.name}/stats", range=range)
314
+
315
+
316
+ class Job:
317
+ """A background command (exec with background=True)."""
318
+
319
+ def __init__(self, sandbox, job_id, info=None):
320
+ self.sandbox, self.id, self._info = sandbox, job_id, info
321
+
322
+ def __repr__(self):
323
+ return f"Job({self.id!r} in {self.sandbox.name!r})"
324
+
325
+ def status(self, tail=200):
326
+ """{id, command, started, status: running|exited|lost, exit_code, stdout, stderr}."""
327
+ self._info = self.sandbox.client.get(f"vms/{self.sandbox.name}/jobs/{self.id}", tail=tail)
328
+ return self._info
329
+
330
+ def kill(self):
331
+ return self.sandbox.client.delete(f"vms/{self.sandbox.name}/jobs/{self.id}")
332
+
333
+ def wait(self, timeout=None, poll=1.0, tail=200):
334
+ """The job's final status (polling); TimeoutError after `timeout` seconds."""
335
+ deadline = time.monotonic() + timeout if timeout else None
336
+ while True:
337
+ s = self.status(tail)
338
+ if s["status"] != "running":
339
+ return s
340
+ if deadline and time.monotonic() > deadline:
341
+ raise TimeoutError(f"job {self.id} still running after {timeout} s")
342
+ time.sleep(poll)
343
+
344
+
345
+ class ServerJob:
346
+ """A server-side job (an image import or a build)."""
347
+
348
+ def __init__(self, client, info):
349
+ self.client, self.id, self._info = client, info["id"], info
350
+
351
+ def status(self):
352
+ self._info = self.client.get(f"jobs/{self.id}")
353
+ return self._info
354
+
355
+ def wait(self, timeout=None, poll=1.0):
356
+ deadline = time.monotonic() + timeout if timeout else None
357
+ while True:
358
+ s = self.status()
359
+ if s["status"] != "running":
360
+ if s["status"] == "failed":
361
+ raise FcvmError(0, f"job {s.get('title', self.id)} failed: " + "\n".join(s.get("lines", [])[-5:]))
362
+ return s
363
+ if deadline and time.monotonic() > deadline:
364
+ raise TimeoutError(f"job {self.id} still running after {timeout} s")
365
+ time.sleep(poll)
366
+
367
+
368
+ class Snapshot:
369
+ def __init__(self, client, name, info=None):
370
+ self.client, self.name, self._info = client, name, info
371
+
372
+ def __repr__(self):
373
+ return f"Snapshot({self.name!r})"
374
+
375
+ def fork(self, name=None, count=1):
376
+ """Running VMs from this snapshot; returns them (name, or name-1..name-N)."""
377
+ before = {v["name"] for v in self.client.get("vms")}
378
+ self.client.post(f"snapshots/{self.name}/fork", {"count": count, **({"name": name} if name else {})})
379
+ return [Sandbox(self.client, v["name"], v) for v in self.client.get("vms") if v["name"] not in before]
380
+
381
+ def remove(self):
382
+ return self.client.delete(f"snapshots/{self.name}")
@@ -0,0 +1,32 @@
1
+ [build-system]
2
+ requires = ["setuptools>=77"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "fcvm"
7
+ version = "0.7.0"
8
+ description = "A client for the fcvm HTTP API: Firecracker microVM sandboxes from Python"
9
+ readme = "README.md"
10
+ license = "Apache-2.0"
11
+ license-files = ["LICENSE", "NOTICE"]
12
+ authors = [{name = "Carlos Bravo"}]
13
+ requires-python = ">=3.9"
14
+ keywords = ["firecracker", "microvm", "sandbox", "ai-agents", "virtualization", "isolation"]
15
+ classifiers = [
16
+ "Development Status :: 4 - Beta",
17
+ "Intended Audience :: Developers",
18
+ "Operating System :: OS Independent",
19
+ "Programming Language :: Python :: 3",
20
+ "Topic :: Security",
21
+ "Topic :: Software Development :: Testing",
22
+ "Topic :: System :: Emulators",
23
+ ]
24
+
25
+ [project.urls]
26
+ Homepage = "https://github.com/carlosbravoa/fcvm"
27
+ Documentation = "https://github.com/carlosbravoa/fcvm/blob/main/sdk/README.md"
28
+ Issues = "https://github.com/carlosbravoa/fcvm/issues"
29
+ Changelog = "https://github.com/carlosbravoa/fcvm/blob/main/CHANGELOG.md"
30
+
31
+ [tool.setuptools]
32
+ py-modules = ["fcvm"]
fcvm-0.7.0/setup.cfg ADDED
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+