├── .github
└── workflows
│ └── build-binaries.yml
├── .gitignore
├── LICENSE
├── Makefile
├── README.md
├── api
├── chv-api.yaml
└── server-api.yaml
├── cmd
├── client
│ └── main.go
├── cmdserver
│ └── main.go
├── guestinit
│ └── main.go
├── restserver
│ └── main.go
├── rootfsmaker
│ └── main.go
├── vsockclient
│ ├── cmdclient
│ │ └── main.go
│ └── main.go
└── vsockserver
│ └── main.go
├── config.yaml
├── docs
├── detailed-README.md
└── images
│ ├── arrakis-gui.png
│ ├── arrakis-logo.png
│ └── high-level-architecture-arrakis.png
├── go.mod
├── go.sum
├── initramfs
├── create-initramfs.sh
└── init.sh
├── pkg
├── cmdserver
│ └── cmdserver.go
├── config
│ └── config.go
└── server
│ ├── cidallocator
│ └── cidallocator.go
│ ├── fountain
│ └── fountain.go
│ ├── ipallocator
│ └── ipallocator.go
│ ├── portallocator
│ └── portallocator.go
│ └── server.go
├── resources
├── arrakis-cmdserver.service
├── arrakis-guestinit.service
├── arrakis-vncserver.service
├── arrakis-vsockserver.service
└── scripts
│ └── rootfs
│ └── Dockerfile
└── setup
├── gcp-instructions.md
├── install-deps.sh
├── install-images.py
└── setup.sh
/.github/workflows/build-binaries.yml:
--------------------------------------------------------------------------------
1 | name: Build Arrakis Binaries
2 |
3 | on:
4 | push:
5 | branches: [ "main", "ci-cd-test" ]
6 | pull_request:
7 | branches: [ "main" ]
8 |
9 | # Add permissions needed for creating releases.
10 | permissions:
11 | contents: write
12 | packages: write
13 |
14 | jobs:
15 | build:
16 | runs-on: ubuntu-latest
17 | steps:
18 | - uses: actions/checkout@v4
19 |
20 | - name: Set up Go
21 | uses: actions/setup-go@v5
22 | with:
23 | go-version: '1.23.1'
24 | check-latest: true
25 |
26 | - name: Install OpenAPI Generator CLI
27 | run: |
28 | # Install default JDK (as per project's install-deps.sh)
29 | sudo apt-get update
30 | sudo apt-get install -y default-jdk
31 |
32 | # Install OpenAPI Generator using npm (as per project's install-deps.sh)
33 | npm install @openapitools/openapi-generator-cli -g
34 |
35 | # Verify installation
36 | openapi-generator-cli version
37 |
38 | - name: Download required binaries
39 | run: |
40 | mkdir -p resources/bin
41 | # Download busybox for initramfs creation
42 | curl -L -o resources/bin/busybox https://raw.githubusercontent.com/abshkbh/arrakis-images/main/busybox
43 | chmod +x resources/bin/busybox
44 |
45 | - name: Build API clients
46 | run: make serverapi chvapi
47 |
48 | - name: Build Go binaries
49 | run: make restserver client guestinit rootfsmaker cmdserver vsockserver vsockclient initramfs
50 |
51 | - name: Build rootfs
52 | run: sudo make guestrootfs
53 |
54 | - name: Print rootfs image size
55 | run: |
56 | echo "============================================================"
57 | echo " ROOTFS IMAGE DETAILS "
58 | echo "============================================================"
59 | ls -lh out/arrakis-guestrootfs-ext4.img
60 | echo "File type: $(file out/arrakis-guestrootfs-ext4.img)"
61 | echo "Disk usage: $(du -h out/arrakis-guestrootfs-ext4.img)"
62 | echo "============================================================"
63 |
64 | - name: Compress rootfs image
65 | run: |
66 | echo "Compressing rootfs image..."
67 | tar -czf out/arrakis-guestrootfs-ext4.img.tar.gz -C out arrakis-guestrootfs-ext4.img
68 | echo "Compressed rootfs image details:"
69 | ls -lh out/arrakis-guestrootfs-ext4.img.tar.gz
70 | echo "Compression ratio: $(($(stat -c %s out/arrakis-guestrootfs-ext4.img.tar.gz) * 100 / $(stat -c %s out/arrakis-guestrootfs-ext4.img)))%"
71 |
72 | - name: Create release artifacts directory
73 | run: mkdir -p release-artifacts
74 |
75 | - name: Copy binaries and config to artifacts directory
76 | run: |
77 | cp out/arrakis-restserver release-artifacts/
78 | cp out/arrakis-client release-artifacts/
79 | cp out/arrakis-guestinit release-artifacts/
80 | cp out/arrakis-rootfsmaker release-artifacts/
81 | cp out/arrakis-cmdserver release-artifacts/
82 | cp out/arrakis-vsockserver release-artifacts/
83 | cp out/arrakis-vsockclient release-artifacts/
84 | cp out/initramfs.cpio.gz release-artifacts/
85 | cp out/arrakis-guestrootfs-ext4.img.tar.gz release-artifacts/
86 | cp config.yaml release-artifacts/
87 |
88 | - name: Create VERSION file
89 | run: |
90 | echo "Creating VERSION file with build metadata..."
91 | echo "VERSION=release-${{ github.run_number }}" > release-artifacts/VERSION
92 | echo "COMMIT=${{ github.sha }}" >> release-artifacts/VERSION
93 | echo "COMMIT_SHORT=$(echo ${{ github.sha }} | cut -c1-8)" >> release-artifacts/VERSION
94 | echo "BUILD_TIME=$(date -u +%Y-%m-%dT%H:%M:%SZ)" >> release-artifacts/VERSION
95 | echo "BRANCH=${{ github.ref_name }}" >> release-artifacts/VERSION
96 | echo "BUILD_ID=${{ github.run_id }}" >> release-artifacts/VERSION
97 | echo "BUILD_NUMBER=${{ github.run_number }}" >> release-artifacts/VERSION
98 | echo "WORKFLOW=${{ github.workflow }}" >> release-artifacts/VERSION
99 | echo "ACTOR=${{ github.actor }}" >> release-artifacts/VERSION
100 | echo ""
101 | echo "VERSION file contents:"
102 | cat release-artifacts/VERSION
103 |
104 | - name: Upload artifacts
105 | uses: actions/upload-artifact@v4
106 | with:
107 | name: arrakis-binaries
108 | path: release-artifacts/
109 | retention-days: 7
110 |
111 | - name: Create Release
112 | if: github.event_name == 'push' && github.ref == 'refs/heads/main'
113 | id: create_release
114 | uses: softprops/action-gh-release@v1
115 | with:
116 | name: Release ${{ github.sha }}
117 | tag_name: release-${{ github.run_number }}
118 | files: |
119 | release-artifacts/arrakis-restserver
120 | release-artifacts/arrakis-client
121 | release-artifacts/arrakis-guestinit
122 | release-artifacts/arrakis-rootfsmaker
123 | release-artifacts/arrakis-cmdserver
124 | release-artifacts/arrakis-vsockserver
125 | release-artifacts/arrakis-vsockclient
126 | release-artifacts/initramfs.cpio.gz
127 | release-artifacts/arrakis-guestrootfs-ext4.img.tar.gz
128 | release-artifacts/config.yaml
129 | release-artifacts/VERSION
130 | generate_release_notes: true
131 | env:
132 | GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
133 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | resources/bin/
2 | out/
3 | *rules
4 | .vscode/
5 | vm-state/
6 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU AFFERO GENERAL PUBLIC LICENSE
2 | Version 3, 19 November 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU Affero General Public License is a free, copyleft license for
11 | software and other kinds of works, specifically designed to ensure
12 | cooperation with the community in the case of network server software.
13 |
14 | The licenses for most software and other practical works are designed
15 | to take away your freedom to share and change the works. By contrast,
16 | our General Public Licenses are intended to guarantee your freedom to
17 | share and change all versions of a program--to make sure it remains free
18 | software for all its users.
19 |
20 | When we speak of free software, we are referring to freedom, not
21 | price. Our General Public Licenses are designed to make sure that you
22 | have the freedom to distribute copies of free software (and charge for
23 | them if you wish), that you receive source code or can get it if you
24 | want it, that you can change the software or use pieces of it in new
25 | free programs, and that you know you can do these things.
26 |
27 | Developers that use our General Public Licenses protect your rights
28 | with two steps: (1) assert copyright on the software, and (2) offer
29 | you this License which gives you legal permission to copy, distribute
30 | and/or modify the software.
31 |
32 | A secondary benefit of defending all users' freedom is that
33 | improvements made in alternate versions of the program, if they
34 | receive widespread use, become available for other developers to
35 | incorporate. Many developers of free software are heartened and
36 | encouraged by the resulting cooperation. However, in the case of
37 | software used on network servers, this result may fail to come about.
38 | The GNU General Public License permits making a modified version and
39 | letting the public access it on a server without ever releasing its
40 | source code to the public.
41 |
42 | The GNU Affero General Public License is designed specifically to
43 | ensure that, in such cases, the modified source code becomes available
44 | to the community. It requires the operator of a network server to
45 | provide the source code of the modified version running there to the
46 | users of that server. Therefore, public use of a modified version, on
47 | a publicly accessible server, gives the public access to the source
48 | code of the modified version.
49 |
50 | An older license, called the Affero General Public License and
51 | published by Affero, was designed to accomplish similar goals. This is
52 | a different license, not a version of the Affero GPL, but Affero has
53 | released a new version of the Affero GPL which permits relicensing under
54 | this license.
55 |
56 | The precise terms and conditions for copying, distribution and
57 | modification follow.
58 |
59 | TERMS AND CONDITIONS
60 |
61 | 0. Definitions.
62 |
63 | "This License" refers to version 3 of the GNU Affero General Public License.
64 |
65 | "Copyright" also means copyright-like laws that apply to other kinds of
66 | works, such as semiconductor masks.
67 |
68 | "The Program" refers to any copyrightable work licensed under this
69 | License. Each licensee is addressed as "you". "Licensees" and
70 | "recipients" may be individuals or organizations.
71 |
72 | To "modify" a work means to copy from or adapt all or part of the work
73 | in a fashion requiring copyright permission, other than the making of an
74 | exact copy. The resulting work is called a "modified version" of the
75 | earlier work or a work "based on" the earlier work.
76 |
77 | A "covered work" means either the unmodified Program or a work based
78 | on the Program.
79 |
80 | To "propagate" a work means to do anything with it that, without
81 | permission, would make you directly or secondarily liable for
82 | infringement under applicable copyright law, except executing it on a
83 | computer or modifying a private copy. Propagation includes copying,
84 | distribution (with or without modification), making available to the
85 | public, and in some countries other activities as well.
86 |
87 | To "convey" a work means any kind of propagation that enables other
88 | parties to make or receive copies. Mere interaction with a user through
89 | a computer network, with no transfer of a copy, is not conveying.
90 |
91 | An interactive user interface displays "Appropriate Legal Notices"
92 | to the extent that it includes a convenient and prominently visible
93 | feature that (1) displays an appropriate copyright notice, and (2)
94 | tells the user that there is no warranty for the work (except to the
95 | extent that warranties are provided), that licensees may convey the
96 | work under this License, and how to view a copy of this License. If
97 | the interface presents a list of user commands or options, such as a
98 | menu, a prominent item in the list meets this criterion.
99 |
100 | 1. Source Code.
101 |
102 | The "source code" for a work means the preferred form of the work
103 | for making modifications to it. "Object code" means any non-source
104 | form of a work.
105 |
106 | A "Standard Interface" means an interface that either is an official
107 | standard defined by a recognized standards body, or, in the case of
108 | interfaces specified for a particular programming language, one that
109 | is widely used among developers working in that language.
110 |
111 | The "System Libraries" of an executable work include anything, other
112 | than the work as a whole, that (a) is included in the normal form of
113 | packaging a Major Component, but which is not part of that Major
114 | Component, and (b) serves only to enable use of the work with that
115 | Major Component, or to implement a Standard Interface for which an
116 | implementation is available to the public in source code form. A
117 | "Major Component", in this context, means a major essential component
118 | (kernel, window system, and so on) of the specific operating system
119 | (if any) on which the executable work runs, or a compiler used to
120 | produce the work, or an object code interpreter used to run it.
121 |
122 | The "Corresponding Source" for a work in object code form means all
123 | the source code needed to generate, install, and (for an executable
124 | work) run the object code and to modify the work, including scripts to
125 | control those activities. However, it does not include the work's
126 | System Libraries, or general-purpose tools or generally available free
127 | programs which are used unmodified in performing those activities but
128 | which are not part of the work. For example, Corresponding Source
129 | includes interface definition files associated with source files for
130 | the work, and the source code for shared libraries and dynamically
131 | linked subprograms that the work is specifically designed to require,
132 | such as by intimate data communication or control flow between those
133 | subprograms and other parts of the work.
134 |
135 | The Corresponding Source need not include anything that users
136 | can regenerate automatically from other parts of the Corresponding
137 | Source.
138 |
139 | The Corresponding Source for a work in source code form is that
140 | same work.
141 |
142 | 2. Basic Permissions.
143 |
144 | All rights granted under this License are granted for the term of
145 | copyright on the Program, and are irrevocable provided the stated
146 | conditions are met. This License explicitly affirms your unlimited
147 | permission to run the unmodified Program. The output from running a
148 | covered work is covered by this License only if the output, given its
149 | content, constitutes a covered work. This License acknowledges your
150 | rights of fair use or other equivalent, as provided by copyright law.
151 |
152 | You may make, run and propagate covered works that you do not
153 | convey, without conditions so long as your license otherwise remains
154 | in force. You may convey covered works to others for the sole purpose
155 | of having them make modifications exclusively for you, or provide you
156 | with facilities for running those works, provided that you comply with
157 | the terms of this License in conveying all material for which you do
158 | not control copyright. Those thus making or running the covered works
159 | for you must do so exclusively on your behalf, under your direction
160 | and control, on terms that prohibit them from making any copies of
161 | your copyrighted material outside their relationship with you.
162 |
163 | Conveying under any other circumstances is permitted solely under
164 | the conditions stated below. Sublicensing is not allowed; section 10
165 | makes it unnecessary.
166 |
167 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
168 |
169 | No covered work shall be deemed part of an effective technological
170 | measure under any applicable law fulfilling obligations under article
171 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
172 | similar laws prohibiting or restricting circumvention of such
173 | measures.
174 |
175 | When you convey a covered work, you waive any legal power to forbid
176 | circumvention of technological measures to the extent such circumvention
177 | is effected by exercising rights under this License with respect to
178 | the covered work, and you disclaim any intention to limit operation or
179 | modification of the work as a means of enforcing, against the work's
180 | users, your or third parties' legal rights to forbid circumvention of
181 | technological measures.
182 |
183 | 4. Conveying Verbatim Copies.
184 |
185 | You may convey verbatim copies of the Program's source code as you
186 | receive it, in any medium, provided that you conspicuously and
187 | appropriately publish on each copy an appropriate copyright notice;
188 | keep intact all notices stating that this License and any
189 | non-permissive terms added in accord with section 7 apply to the code;
190 | keep intact all notices of the absence of any warranty; and give all
191 | recipients a copy of this License along with the Program.
192 |
193 | You may charge any price or no price for each copy that you convey,
194 | and you may offer support or warranty protection for a fee.
195 |
196 | 5. Conveying Modified Source Versions.
197 |
198 | You may convey a work based on the Program, or the modifications to
199 | produce it from the Program, in the form of source code under the
200 | terms of section 4, provided that you also meet all of these conditions:
201 |
202 | a) The work must carry prominent notices stating that you modified
203 | it, and giving a relevant date.
204 |
205 | b) The work must carry prominent notices stating that it is
206 | released under this License and any conditions added under section
207 | 7. This requirement modifies the requirement in section 4 to
208 | "keep intact all notices".
209 |
210 | c) You must license the entire work, as a whole, under this
211 | License to anyone who comes into possession of a copy. This
212 | License will therefore apply, along with any applicable section 7
213 | additional terms, to the whole of the work, and all its parts,
214 | regardless of how they are packaged. This License gives no
215 | permission to license the work in any other way, but it does not
216 | invalidate such permission if you have separately received it.
217 |
218 | d) If the work has interactive user interfaces, each must display
219 | Appropriate Legal Notices; however, if the Program has interactive
220 | interfaces that do not display Appropriate Legal Notices, your
221 | work need not make them do so.
222 |
223 | A compilation of a covered work with other separate and independent
224 | works, which are not by their nature extensions of the covered work,
225 | and which are not combined with it such as to form a larger program,
226 | in or on a volume of a storage or distribution medium, is called an
227 | "aggregate" if the compilation and its resulting copyright are not
228 | used to limit the access or legal rights of the compilation's users
229 | beyond what the individual works permit. Inclusion of a covered work
230 | in an aggregate does not cause this License to apply to the other
231 | parts of the aggregate.
232 |
233 | 6. Conveying Non-Source Forms.
234 |
235 | You may convey a covered work in object code form under the terms
236 | of sections 4 and 5, provided that you also convey the
237 | machine-readable Corresponding Source under the terms of this License,
238 | in one of these ways:
239 |
240 | a) Convey the object code in, or embodied in, a physical product
241 | (including a physical distribution medium), accompanied by the
242 | Corresponding Source fixed on a durable physical medium
243 | customarily used for software interchange.
244 |
245 | b) Convey the object code in, or embodied in, a physical product
246 | (including a physical distribution medium), accompanied by a
247 | written offer, valid for at least three years and valid for as
248 | long as you offer spare parts or customer support for that product
249 | model, to give anyone who possesses the object code either (1) a
250 | copy of the Corresponding Source for all the software in the
251 | product that is covered by this License, on a durable physical
252 | medium customarily used for software interchange, for a price no
253 | more than your reasonable cost of physically performing this
254 | conveying of source, or (2) access to copy the
255 | Corresponding Source from a network server at no charge.
256 |
257 | c) Convey individual copies of the object code with a copy of the
258 | written offer to provide the Corresponding Source. This
259 | alternative is allowed only occasionally and noncommercially, and
260 | only if you received the object code with such an offer, in accord
261 | with subsection 6b.
262 |
263 | d) Convey the object code by offering access from a designated
264 | place (gratis or for a charge), and offer equivalent access to the
265 | Corresponding Source in the same way through the same place at no
266 | further charge. You need not require recipients to copy the
267 | Corresponding Source along with the object code. If the place to
268 | copy the object code is a network server, the Corresponding Source
269 | may be on a different server (operated by you or a third party)
270 | that supports equivalent copying facilities, provided you maintain
271 | clear directions next to the object code saying where to find the
272 | Corresponding Source. Regardless of what server hosts the
273 | Corresponding Source, you remain obligated to ensure that it is
274 | available for as long as needed to satisfy these requirements.
275 |
276 | e) Convey the object code using peer-to-peer transmission, provided
277 | you inform other peers where the object code and Corresponding
278 | Source of the work are being offered to the general public at no
279 | charge under subsection 6d.
280 |
281 | A separable portion of the object code, whose source code is excluded
282 | from the Corresponding Source as a System Library, need not be
283 | included in conveying the object code work.
284 |
285 | A "User Product" is either (1) a "consumer product", which means any
286 | tangible personal property which is normally used for personal, family,
287 | or household purposes, or (2) anything designed or sold for incorporation
288 | into a dwelling. In determining whether a product is a consumer product,
289 | doubtful cases shall be resolved in favor of coverage. For a particular
290 | product received by a particular user, "normally used" refers to a
291 | typical or common use of that class of product, regardless of the status
292 | of the particular user or of the way in which the particular user
293 | actually uses, or expects or is expected to use, the product. A product
294 | is a consumer product regardless of whether the product has substantial
295 | commercial, industrial or non-consumer uses, unless such uses represent
296 | the only significant mode of use of the product.
297 |
298 | "Installation Information" for a User Product means any methods,
299 | procedures, authorization keys, or other information required to install
300 | and execute modified versions of a covered work in that User Product from
301 | a modified version of its Corresponding Source. The information must
302 | suffice to ensure that the continued functioning of the modified object
303 | code is in no case prevented or interfered with solely because
304 | modification has been made.
305 |
306 | If you convey an object code work under this section in, or with, or
307 | specifically for use in, a User Product, and the conveying occurs as
308 | part of a transaction in which the right of possession and use of the
309 | User Product is transferred to the recipient in perpetuity or for a
310 | fixed term (regardless of how the transaction is characterized), the
311 | Corresponding Source conveyed under this section must be accompanied
312 | by the Installation Information. But this requirement does not apply
313 | if neither you nor any third party retains the ability to install
314 | modified object code on the User Product (for example, the work has
315 | been installed in ROM).
316 |
317 | The requirement to provide Installation Information does not include a
318 | requirement to continue to provide support service, warranty, or updates
319 | for a work that has been modified or installed by the recipient, or for
320 | the User Product in which it has been modified or installed. Access to a
321 | network may be denied when the modification itself materially and
322 | adversely affects the operation of the network or violates the rules and
323 | protocols for communication across the network.
324 |
325 | Corresponding Source conveyed, and Installation Information provided,
326 | in accord with this section must be in a format that is publicly
327 | documented (and with an implementation available to the public in
328 | source code form), and must require no special password or key for
329 | unpacking, reading or copying.
330 |
331 | 7. Additional Terms.
332 |
333 | "Additional permissions" are terms that supplement the terms of this
334 | License by making exceptions from one or more of its conditions.
335 | Additional permissions that are applicable to the entire Program shall
336 | be treated as though they were included in this License, to the extent
337 | that they are valid under applicable law. If additional permissions
338 | apply only to part of the Program, that part may be used separately
339 | under those permissions, but the entire Program remains governed by
340 | this License without regard to the additional permissions.
341 |
342 | When you convey a copy of a covered work, you may at your option
343 | remove any additional permissions from that copy, or from any part of
344 | it. (Additional permissions may be written to require their own
345 | removal in certain cases when you modify the work.) You may place
346 | additional permissions on material, added by you to a covered work,
347 | for which you have or can give appropriate copyright permission.
348 |
349 | Notwithstanding any other provision of this License, for material you
350 | add to a covered work, you may (if authorized by the copyright holders of
351 | that material) supplement the terms of this License with terms:
352 |
353 | a) Disclaiming warranty or limiting liability differently from the
354 | terms of sections 15 and 16 of this License; or
355 |
356 | b) Requiring preservation of specified reasonable legal notices or
357 | author attributions in that material or in the Appropriate Legal
358 | Notices displayed by works containing it; or
359 |
360 | c) Prohibiting misrepresentation of the origin of that material, or
361 | requiring that modified versions of such material be marked in
362 | reasonable ways as different from the original version; or
363 |
364 | d) Limiting the use for publicity purposes of names of licensors or
365 | authors of the material; or
366 |
367 | e) Declining to grant rights under trademark law for use of some
368 | trade names, trademarks, or service marks; or
369 |
370 | f) Requiring indemnification of licensors and authors of that
371 | material by anyone who conveys the material (or modified versions of
372 | it) with contractual assumptions of liability to the recipient, for
373 | any liability that these contractual assumptions directly impose on
374 | those licensors and authors.
375 |
376 | All other non-permissive additional terms are considered "further
377 | restrictions" within the meaning of section 10. If the Program as you
378 | received it, or any part of it, contains a notice stating that it is
379 | governed by this License along with a term that is a further
380 | restriction, you may remove that term. If a license document contains
381 | a further restriction but permits relicensing or conveying under this
382 | License, you may add to a covered work material governed by the terms
383 | of that license document, provided that the further restriction does
384 | not survive such relicensing or conveying.
385 |
386 | If you add terms to a covered work in accord with this section, you
387 | must place, in the relevant source files, a statement of the
388 | additional terms that apply to those files, or a notice indicating
389 | where to find the applicable terms.
390 |
391 | Additional terms, permissive or non-permissive, may be stated in the
392 | form of a separately written license, or stated as exceptions;
393 | the above requirements apply either way.
394 |
395 | 8. Termination.
396 |
397 | You may not propagate or modify a covered work except as expressly
398 | provided under this License. Any attempt otherwise to propagate or
399 | modify it is void, and will automatically terminate your rights under
400 | this License (including any patent licenses granted under the third
401 | paragraph of section 11).
402 |
403 | However, if you cease all violation of this License, then your
404 | license from a particular copyright holder is reinstated (a)
405 | provisionally, unless and until the copyright holder explicitly and
406 | finally terminates your license, and (b) permanently, if the copyright
407 | holder fails to notify you of the violation by some reasonable means
408 | prior to 60 days after the cessation.
409 |
410 | Moreover, your license from a particular copyright holder is
411 | reinstated permanently if the copyright holder notifies you of the
412 | violation by some reasonable means, this is the first time you have
413 | received notice of violation of this License (for any work) from that
414 | copyright holder, and you cure the violation prior to 30 days after
415 | your receipt of the notice.
416 |
417 | Termination of your rights under this section does not terminate the
418 | licenses of parties who have received copies or rights from you under
419 | this License. If your rights have been terminated and not permanently
420 | reinstated, you do not qualify to receive new licenses for the same
421 | material under section 10.
422 |
423 | 9. Acceptance Not Required for Having Copies.
424 |
425 | You are not required to accept this License in order to receive or
426 | run a copy of the Program. Ancillary propagation of a covered work
427 | occurring solely as a consequence of using peer-to-peer transmission
428 | to receive a copy likewise does not require acceptance. However,
429 | nothing other than this License grants you permission to propagate or
430 | modify any covered work. These actions infringe copyright if you do
431 | not accept this License. Therefore, by modifying or propagating a
432 | covered work, you indicate your acceptance of this License to do so.
433 |
434 | 10. Automatic Licensing of Downstream Recipients.
435 |
436 | Each time you convey a covered work, the recipient automatically
437 | receives a license from the original licensors, to run, modify and
438 | propagate that work, subject to this License. You are not responsible
439 | for enforcing compliance by third parties with this License.
440 |
441 | An "entity transaction" is a transaction transferring control of an
442 | organization, or substantially all assets of one, or subdividing an
443 | organization, or merging organizations. If propagation of a covered
444 | work results from an entity transaction, each party to that
445 | transaction who receives a copy of the work also receives whatever
446 | licenses to the work the party's predecessor in interest had or could
447 | give under the previous paragraph, plus a right to possession of the
448 | Corresponding Source of the work from the predecessor in interest, if
449 | the predecessor has it or can get it with reasonable efforts.
450 |
451 | You may not impose any further restrictions on the exercise of the
452 | rights granted or affirmed under this License. For example, you may
453 | not impose a license fee, royalty, or other charge for exercise of
454 | rights granted under this License, and you may not initiate litigation
455 | (including a cross-claim or counterclaim in a lawsuit) alleging that
456 | any patent claim is infringed by making, using, selling, offering for
457 | sale, or importing the Program or any portion of it.
458 |
459 | 11. Patents.
460 |
461 | A "contributor" is a copyright holder who authorizes use under this
462 | License of the Program or a work on which the Program is based. The
463 | work thus licensed is called the contributor's "contributor version".
464 |
465 | A contributor's "essential patent claims" are all patent claims
466 | owned or controlled by the contributor, whether already acquired or
467 | hereafter acquired, that would be infringed by some manner, permitted
468 | by this License, of making, using, or selling its contributor version,
469 | but do not include claims that would be infringed only as a
470 | consequence of further modification of the contributor version. For
471 | purposes of this definition, "control" includes the right to grant
472 | patent sublicenses in a manner consistent with the requirements of
473 | this License.
474 |
475 | Each contributor grants you a non-exclusive, worldwide, royalty-free
476 | patent license under the contributor's essential patent claims, to
477 | make, use, sell, offer for sale, import and otherwise run, modify and
478 | propagate the contents of its contributor version.
479 |
480 | In the following three paragraphs, a "patent license" is any express
481 | agreement or commitment, however denominated, not to enforce a patent
482 | (such as an express permission to practice a patent or covenant not to
483 | sue for patent infringement). To "grant" such a patent license to a
484 | party means to make such an agreement or commitment not to enforce a
485 | patent against the party.
486 |
487 | If you convey a covered work, knowingly relying on a patent license,
488 | and the Corresponding Source of the work is not available for anyone
489 | to copy, free of charge and under the terms of this License, through a
490 | publicly available network server or other readily accessible means,
491 | then you must either (1) cause the Corresponding Source to be so
492 | available, or (2) arrange to deprive yourself of the benefit of the
493 | patent license for this particular work, or (3) arrange, in a manner
494 | consistent with the requirements of this License, to extend the patent
495 | license to downstream recipients. "Knowingly relying" means you have
496 | actual knowledge that, but for the patent license, your conveying the
497 | covered work in a country, or your recipient's use of the covered work
498 | in a country, would infringe one or more identifiable patents in that
499 | country that you have reason to believe are valid.
500 |
501 | If, pursuant to or in connection with a single transaction or
502 | arrangement, you convey, or propagate by procuring conveyance of, a
503 | covered work, and grant a patent license to some of the parties
504 | receiving the covered work authorizing them to use, propagate, modify
505 | or convey a specific copy of the covered work, then the patent license
506 | you grant is automatically extended to all recipients of the covered
507 | work and works based on it.
508 |
509 | A patent license is "discriminatory" if it does not include within
510 | the scope of its coverage, prohibits the exercise of, or is
511 | conditioned on the non-exercise of one or more of the rights that are
512 | specifically granted under this License. You may not convey a covered
513 | work if you are a party to an arrangement with a third party that is
514 | in the business of distributing software, under which you make payment
515 | to the third party based on the extent of your activity of conveying
516 | the work, and under which the third party grants, to any of the
517 | parties who would receive the covered work from you, a discriminatory
518 | patent license (a) in connection with copies of the covered work
519 | conveyed by you (or copies made from those copies), or (b) primarily
520 | for and in connection with specific products or compilations that
521 | contain the covered work, unless you entered into that arrangement,
522 | or that patent license was granted, prior to 28 March 2007.
523 |
524 | Nothing in this License shall be construed as excluding or limiting
525 | any implied license or other defenses to infringement that may
526 | otherwise be available to you under applicable patent law.
527 |
528 | 12. No Surrender of Others' Freedom.
529 |
530 | If conditions are imposed on you (whether by court order, agreement or
531 | otherwise) that contradict the conditions of this License, they do not
532 | excuse you from the conditions of this License. If you cannot convey a
533 | covered work so as to satisfy simultaneously your obligations under this
534 | License and any other pertinent obligations, then as a consequence you may
535 | not convey it at all. For example, if you agree to terms that obligate you
536 | to collect a royalty for further conveying from those to whom you convey
537 | the Program, the only way you could satisfy both those terms and this
538 | License would be to refrain entirely from conveying the Program.
539 |
540 | 13. Remote Network Interaction; Use with the GNU General Public License.
541 |
542 | Notwithstanding any other provision of this License, if you modify the
543 | Program, your modified version must prominently offer all users
544 | interacting with it remotely through a computer network (if your version
545 | supports such interaction) an opportunity to receive the Corresponding
546 | Source of your version by providing access to the Corresponding Source
547 | from a network server at no charge, through some standard or customary
548 | means of facilitating copying of software. This Corresponding Source
549 | shall include the Corresponding Source for any work covered by version 3
550 | of the GNU General Public License that is incorporated pursuant to the
551 | following paragraph.
552 |
553 | Notwithstanding any other provision of this License, you have
554 | permission to link or combine any covered work with a work licensed
555 | under version 3 of the GNU General Public License into a single
556 | combined work, and to convey the resulting work. The terms of this
557 | License will continue to apply to the part which is the covered work,
558 | but the work with which it is combined will remain governed by version
559 | 3 of the GNU General Public License.
560 |
561 | 14. Revised Versions of this License.
562 |
563 | The Free Software Foundation may publish revised and/or new versions of
564 | the GNU Affero General Public License from time to time. Such new versions
565 | will be similar in spirit to the present version, but may differ in detail to
566 | address new problems or concerns.
567 |
568 | Each version is given a distinguishing version number. If the
569 | Program specifies that a certain numbered version of the GNU Affero General
570 | Public License "or any later version" applies to it, you have the
571 | option of following the terms and conditions either of that numbered
572 | version or of any later version published by the Free Software
573 | Foundation. If the Program does not specify a version number of the
574 | GNU Affero General Public License, you may choose any version ever published
575 | by the Free Software Foundation.
576 |
577 | If the Program specifies that a proxy can decide which future
578 | versions of the GNU Affero General Public License can be used, that proxy's
579 | public statement of acceptance of a version permanently authorizes you
580 | to choose that version for the Program.
581 |
582 | Later license versions may give you additional or different
583 | permissions. However, no additional obligations are imposed on any
584 | author or copyright holder as a result of your choosing to follow a
585 | later version.
586 |
587 | 15. Disclaimer of Warranty.
588 |
589 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
590 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
591 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
592 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
593 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
594 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
595 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
596 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
597 |
598 | 16. Limitation of Liability.
599 |
600 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
601 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
602 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
603 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
604 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
605 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
606 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
607 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
608 | SUCH DAMAGES.
609 |
610 | 17. Interpretation of Sections 15 and 16.
611 |
612 | If the disclaimer of warranty and limitation of liability provided
613 | above cannot be given local legal effect according to their terms,
614 | reviewing courts shall apply local law that most closely approximates
615 | an absolute waiver of all civil liability in connection with the
616 | Program, unless a warranty or assumption of liability accompanies a
617 | copy of the Program in return for a fee.
618 |
619 | END OF TERMS AND CONDITIONS
620 |
621 | How to Apply These Terms to Your New Programs
622 |
623 | If you develop a new program, and you want it to be of the greatest
624 | possible use to the public, the best way to achieve this is to make it
625 | free software which everyone can redistribute and change under these terms.
626 |
627 | To do so, attach the following notices to the program. It is safest
628 | to attach them to the start of each source file to most effectively
629 | state the exclusion of warranty; and each file should have at least
630 | the "copyright" line and a pointer to where the full notice is found.
631 |
632 |
633 | Copyright (C)
634 |
635 | This program is free software: you can redistribute it and/or modify
636 | it under the terms of the GNU Affero General Public License as published
637 | by the Free Software Foundation, either version 3 of the License, or
638 | (at your option) any later version.
639 |
640 | This program is distributed in the hope that it will be useful,
641 | but WITHOUT ANY WARRANTY; without even the implied warranty of
642 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
643 | GNU Affero General Public License for more details.
644 |
645 | You should have received a copy of the GNU Affero General Public License
646 | along with this program. If not, see .
647 |
648 | Also add information on how to contact you by electronic and paper mail.
649 |
650 | If your software can interact with users remotely through a computer
651 | network, you should also make sure that it provides a way for users to
652 | get its source. For example, if your program is a web application, its
653 | interface could display a "Source" link that leads users to an archive
654 | of the code. There are many ways you could offer source, and different
655 | solutions will be better for different programs; see section 13 for the
656 | specific requirements.
657 |
658 | You should also get your employer (if you work as a programmer) or school,
659 | if any, to sign a "copyright disclaimer" for the program, if necessary.
660 | For more information on this, and how to apply and follow the GNU AGPL, see
661 | .
662 |
--------------------------------------------------------------------------------
/Makefile:
--------------------------------------------------------------------------------
1 | OUT_DIR := out
2 | API_CLIENT_DIR := out/gen/serverapi
3 | API_CLIENT_GO_PACKAGE_NAME := serverapi
4 | CHV_API_DIR := out/gen/chvapi
5 | CHV_API_GO_PACKAGE_NAME := chvapi
6 | RESTSERVER_BIN := ${OUT_DIR}/arrakis-restserver
7 | CLIENT_BIN := ${OUT_DIR}/arrakis-client
8 | GUESTINIT_BIN := ${OUT_DIR}/arrakis-guestinit
9 | ROOTFSMAKER_BIN := ${OUT_DIR}/arrakis-rootfsmaker
10 | CMDSERVER_BIN := ${OUT_DIR}/arrakis-cmdserver
11 | CMDCLIENT_BIN := ${OUT_DIR}/arrakis-cmdclient
12 | GUESTROOTFS_BIN := ${OUT_DIR}/arrakis-guestrootfs-ext4.img
13 | VSOCKSERVER_BIN := ${OUT_DIR}/arrakis-vsockserver
14 | VSOCKCLIENT_BIN := ${OUT_DIR}/arrakis-vsockclient
15 | INITRAMFS_SRC_DIR := initramfs
16 |
17 | .PHONY: all clean serverapi chvapi initramfs restserver client guestinit rootfsmaker cmdserver guestrootfs guest vsockclient vsockserver
18 |
19 | clean:
20 | rm -rf ${OUT_DIR}
21 |
22 | all: serverapi chvapi restserver client guestinit rootfsmaker cmdserver guestrootfs guest vsockclient vsockserver
23 |
24 | serverapi: ${OUT_DIR}/arrakis-serverapi.stamp
25 | ${OUT_DIR}/arrakis-serverapi.stamp: ./api/server-api.yaml
26 | mkdir -p ${API_CLIENT_DIR}
27 | openapi-generator-cli generate -i $< -g go -o ${API_CLIENT_DIR} --package-name ${API_CLIENT_GO_PACKAGE_NAME} \
28 | --git-user-id abshkbh \
29 | --git-repo-id arrakis/${API_CLIENT_DIR} \
30 | --additional-properties=withGoMod=false \
31 | --global-property models,supportingFiles,apis,apiTests=false
32 | rm -rf openapitools.json
33 |
34 | chvapi: ${OUT_DIR}/arrakis-chvapi.stamp
35 | ${OUT_DIR}/arrakis-chvapi.stamp: api/chv-api.yaml
36 | mkdir -p ${API_CLIENT_DIR}
37 | openapi-generator-cli generate -i ./api/chv-api.yaml -g go -o ${CHV_API_DIR} --package-name ${CHV_API_GO_PACKAGE_NAME} \
38 | --git-user-id abshkbh \
39 | --git-repo-id arrakis/${CHV_API_DIR} \
40 | --additional-properties=withGoMod=false \
41 | --global-property models,supportingFiles,apis,apiTests=false
42 | rm -rf openapitools.json
43 |
44 | restserver: serverapi chvapi
45 | mkdir -p ${OUT_DIR}
46 | CGO_ENABLED=0 go build -o ${RESTSERVER_BIN} ./cmd/restserver
47 |
48 | client: serverapi
49 | mkdir -p ${OUT_DIR}
50 | CGO_ENABLED=0 go build -o ${CLIENT_BIN} ./cmd/client
51 |
52 | # Build the guest init binary explicitly statically if "os" or "net" are used by
53 | # using the CGO_ENABLED=0 flag.
54 | guestinit:
55 | mkdir -p ${OUT_DIR}
56 | CGO_ENABLED=0 go build -o ${GUESTINIT_BIN} ./cmd/guestinit
57 |
58 | rootfsmaker:
59 | mkdir -p ${OUT_DIR}
60 | CGO_ENABLED=0 go build -o ${ROOTFSMAKER_BIN} ./cmd/rootfsmaker
61 |
62 | cmdserver:
63 | mkdir -p ${OUT_DIR}
64 | CGO_ENABLED=0 go build -o ${CMDSERVER_BIN} ./cmd/cmdserver
65 |
66 | guestrootfs: rootfsmaker initramfs cmdserver vsockserver guestinit
67 | mkdir -p ${OUT_DIR}
68 | sudo ${OUT_DIR}/arrakis-rootfsmaker create -o ${GUESTROOTFS_BIN} -d ./resources/scripts/rootfs/Dockerfile
69 |
70 | guest: guestinit rootfsmaker cmdserver guestrootfs
71 |
72 | vsockclient:
73 | mkdir -p ${OUT_DIR}
74 | go build -o ${VSOCKCLIENT_BIN} ./cmd/vsockclient
75 |
76 | vsockserver:
77 | mkdir -p ${OUT_DIR}
78 | CGO_ENABLED=0 go build -o ${VSOCKSERVER_BIN} ./cmd/vsockserver
79 |
80 | initramfs: ${OUT_DIR}/initramfs.stamp
81 | ${OUT_DIR}/initramfs.stamp: ${INITRAMFS_SRC_DIR}/create-initramfs.sh
82 | ${INITRAMFS_SRC_DIR}/create-initramfs.sh
83 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # Arrakis
4 |
5 | [](./LICENSE)
6 |
7 | ## Introduction ##
8 |
9 | AI agents can generate malicious or buggy code that can attack the host system its run on.
10 |
11 | Many agents have elaborate multi-step plans to achieve their goals and benefit from the ability to backtrack to intermediate states.
12 |
13 | **Arrakis** provides a **secure**, **fully customizable**, and **self-hosted** solution to spawn and manage Sandboxes for code execution and computer use. It has out-of-the box support for backtracking via **snapshot-and-restore**.
14 |
15 | - Secure by design, each sandbox [runs in a MicroVM](#architecture-and-features).
16 |
17 | - Each sandbox runs Ubuntu inside with a code execution service and a VNC server running at boot.
18 |
19 | - A REST API, Python SDK [py-arrakis](https://pypi.org/project/py-arrakis/), and a [MCP server](https://github.com/abshkbh/arrakis-mcp-server) let clients (both humans and AI Agents) programatically spawn sandboxes, upload files, and execute code inside each sandbox.
20 |
21 | - Automatically sets up and manages port forwarding from the self-hosted public server to the sanboxes running on it i.e. clients can easily access the sandbox GUI (including Chrome for computer use) without extra setup.
22 |
23 | - Supports **snapshot-and-restore** out of the box i.e. AI Agents can do some work, snapshot a sandbox, and later backtrack to the exact previous state by restoring the snapshot. This means any processes spawned, files modified etc. will be restored as is inside the sandbox.Useful for Monte Carlo Tree Search based agents or explainability of elaborate agent execution flows.
24 |
25 | ---
26 |
27 | ## Table of Contents
28 |
29 | - [Introduction](#introduction)
30 | - [Demo](#demo)
31 | - [Setup](#setup)
32 | - [Prerequisites](#prerequisites)
33 | - [GCP Setup](#gcp-setup)
34 | - [Quick setup using prebuilts](#quick-setup-using-prebuilts)
35 | - [Run the arrakis-restserver](#run-the-arrakis-restserver)
36 | - [Use the CLI or py-arrakis](#use-the-cli-or-py-arrakis)
37 | - [Quickstart](#quickstart)
38 | - [SDK](#sdk)
39 | - [MCP](#mcp)
40 | - [GUI For Computer Use](#gui-for-computer-use)
41 | - [CLI Usage](#cli-usage)
42 | - [Architecture And Features](#architecture-and-features)
43 | - [Customization](#customization)
44 | - [Contribution](#contribution)
45 | - [Legal Info](#legal-info)
46 | - [Contributor License Agreement](#contributor-license-agreement)
47 | - [License](#license)
48 | - [License](#license)
49 |
50 | ___
51 |
52 | ## Demo
53 |
54 | Watch Claude code a live Google docs clone using Arrakis via MCP. It even snapshots the sandbox to checkpoint progress.
55 |
56 | [](https://www.youtube.com/watch?v=IZ5cAnhAdPQ)
57 |
58 | ---
59 |
60 | ## Setup
61 |
62 | ### Prerequisites
63 |
64 | - `cloud-hypervisor` only works with `/dev/kvm` for virtualization on Linux machines. Hence, we only support Linux machines.
65 |
66 | - Check if virtualization is enabled on the host by running.
67 | ```bash
68 | stat /dev/kvm
69 | ```
70 |
71 | ### GCP Setup
72 |
73 | - Follow the instructions in [GCP Setup](./setup/gcp-instructions.md) to set up Arrakis on GCE VM.
74 |
75 | ### Quick setup using prebuilts
76 |
77 | - You can leverage our setup.sh script and prebuilt binaries to easily set up Arrakis.
78 | ```bash
79 | curl -sSL https://raw.githubusercontent.com/abshkbh/arrakis/main/setup/setup.sh | bash
80 | ls arrakis-prebuilt
81 | ```
82 |
83 | ### Run the arrakis-restserver
84 |
85 | - Now we have a folder with all binaries and images pulled. We always need to run `arrakis-restserver` first.
86 | ```bash
87 | cd arrakis-prebuilt
88 | sudo ./arrakis-restserver
89 | ```
90 |
91 | ### Use the CLI or py-arrakis
92 |
93 | - You can use the CLI or [py-arrakis](https://pypi.org/project/py-arrakis/) to spawn and manage VMs.
94 | ```bash
95 | cd arrakis-prebuilt
96 | ./arrakis-client start -n agent-sandbox
97 | ```
98 |
99 | ---
100 |
101 | ## Quickstart
102 |
103 | ### SDK
104 |
105 | Arrakis comes with a Python SDK [py-arrakis](https://pypi.org/project/py-arrakis/) that lets you spawn, manage, and interact with VMs seamlessly.
106 |
107 | - Install the SDK
108 | ```bash
109 | pip install py-arrakis
110 | ```
111 |
112 | - Follow the instructions in [Usage](#usage) to run the `arrakis-restserver` on a Linux machine, or download pre-built binaries from the [official releases page](https://github.com/abshkbh/arrakis/releases).
113 |
114 | - Use py-arrakis to interact with `arrakis-restserver`.
115 |
116 | - Run untrusted code
117 | ```python
118 | # Replace this with the ip:port where `arrakis-restserver` is running.
119 | sandbox_manager = SandboxManager('http://127.0.0.1:7000')
120 |
121 | # Start a new sandbox.
122 | with sb as sandbox_manager.start_sandbox('agent-sandbox'):
123 | sb.run_cmd('echo hello world')
124 |
125 | # Sandbox `sb` automatically destroyed when the context is exited.
126 | ```
127 |
128 | - Snapshot and restore a sandbox
129 | ```python
130 | # Start a sandbox and write some data to a file.
131 | sandbox_name = 'agent-sandbox'
132 | sandbox = sandbox_manager.start_sandbox(sandbox_name)
133 | sandbox.run_cmd("echo 'test data before snapshot' > /tmp/testfile")
134 | snapshot_id = sandbox.snapshot("initial-state")
135 | sandbox.run_cmd("echo 'test data after snapshot' > /tmp/testfile")
136 |
137 | # Destroy the sandbox.
138 | sandbox.destroy()
139 |
140 | # Restore the sandbox from the snapshot and verify we have the same data at the time of the
141 | # snapshot.
142 | sandbox = sandbox_manager.restore(sandbox_name, snapshot_id)
143 | result = sandbox.run_cmd("cat /tmp/testfile")
144 | # result["output"] should be "test data before snapshot".
145 | ```
146 |
147 | ___
148 |
149 | ### MCP
150 |
151 | - Arrakis also comes with a [MCP server](https://github.com/abshkbh/arrakis-mcp-server) that lets MCP clients like Claude Desktop App, Windsurf, Cursor etc.. spawn and manage sandboxes.
152 |
153 | - Here is a sample `claude_desktop_config.json`
154 | ```json
155 | {
156 | "mcpServers": {
157 | "arrakis": {
158 | "command": "/Users/username/.local/bin/uv",
159 | "args": [
160 | "--directory",
161 | "/Users/username/Documents/projects/arrakis-mcp-server",
162 | "run",
163 | "arrakis_mcp_server.py"
164 | ]
165 | }
166 | }
167 | }
168 | ```
169 |
170 | ___
171 |
172 | ### GUI For Computer Use
173 |
174 | 
175 |
176 | - Every sandbox comes with a VNC server running at boot. It also comes with Chrome pre-installed.
177 |
178 | - Arrakis also handles port forwarding to expose the VNC server via a port on the dev server running `arrakis-restserver`.
179 |
180 | - Start a sandbox and get metadata about the sandbox including the VNC connection details.
181 |
182 | ```python
183 | # Replace this with the ip:port where `arrakis-restserver` is running.
184 | sandbox_manager = SandboxManager('http://127.0.0.1:7000')
185 | sb = sandbox_manager.start_sandbox('agent-sandbox')
186 | print(sb.info())
187 | ```
188 |
189 | - We can get the VNC connection details from the `port_forwards` field in the response. The VNC server is represented by the description `gui` in a port forward entry. We will use the `host_port` field to connect to the VNC server.
190 | ```bash
191 | {
192 | 'name': 'agent-sandbox',
193 | 'status': 'RUNNING',
194 | 'ip': '10.20.1.2/24',
195 | 'tap_device_name': 'tap0',
196 | 'port_forwards': [{'host_port': '3000', 'guest_port': '5901', 'description': 'gui'}]
197 | }
198 | ```
199 |
200 | - Use any [VNC client](https://github.com/novnc/noVNC) to connect to the VNC server to access the GUI.
201 | ```bash
202 | # We see port 3000 is the host port forwarded to the VNC server running inside the sandbox.
203 | ./utils/novnc_proxy --vnc :3000
204 | ```
205 | ___
206 |
207 | ### CLI Usage
208 |
209 | - Arrakis comes with an out-of-the-box CLI client that you can use to spawn and manage VMs.
210 |
211 | - Start **arrakis-restserver** as detailed in the [Setup](#setup) section.
212 |
213 | - In a separate shell we will use the CLI client to create and manage VMs.
214 |
215 | - Start a VM named `foo`. It returns metadata about the VM which could be used to interacting with the VM.
216 | ```bash
217 | ./out/arrakis-client start -n foo
218 | ```
219 |
220 | ```bash
221 | started VM: {"codeServerPort":"","ip":"10.20.1.2/24","status":"RUNNING","tapDeviceName":"tap-foo","vmName":"foo"}
222 | ```
223 |
224 | - SSH into the VM.
225 | - ssh credentials are configured [here](./resources/scripts/rootfs/Dockerfile#L6).
226 | ```bash
227 | # Use the IP returned. Password is "elara0000"
228 | ssh elara@10.20.1.2
229 | ```
230 |
231 | - Inspecting a VM named `foo`.
232 | ```bash
233 | ./out/arrakis-client list -n foo
234 | ```
235 |
236 | ```bash
237 | VM: {"ip":"10.20.1.2/24","status":"RUNNING","tapDeviceName":"tap-foo","vmName":"foo"}
238 | ```
239 |
240 | - List all the VMs.
241 | ```bash
242 | ./out/arrakis-client list-all
243 | ```
244 |
245 | ```bash
246 | VMs: {"vms":[{"ip":"10.20.1.2/24","status":"RUNNING","tapDeviceName":"tap-foo","vmName":"foo"}]}
247 | ```
248 |
249 | - Stop the VM.
250 | ```bash
251 | ./out/arrakis-client stop -n foo
252 | ```
253 |
254 | - Destroy the VM.
255 | ```bash
256 | ./out/arrakis-client destroy -n foo
257 | ```
258 |
259 | - Snapshotting and Restoring the VM.
260 | - We support snapshotting the VM and then using the snapshot to restore the VM. Currently, we restore the VM to use the same IP as the original VM. If you plan to restore the VM on the same host then either stop or destroy the original VM before restoring. In the future this won't be a constraint.
261 | ```bash
262 | ./out/arrakis-client snapshot -n foo-original -o foo-snapshot
263 | ```
264 |
265 | ```bash
266 | ./out/arrakis-client destroy -n foo-original -o foo-snapshot
267 | ```
268 |
269 | ```bash
270 | ./out/arrakis-client restore -n foo-original --snapshot foo-snapshot
271 | ```
272 |
273 | ---
274 |
275 | ## Architecture And Features
276 |
277 | 
278 |
279 | `arrakis` includes the following services and features
280 |
281 | - **REST API**
282 | - **arrakis-restserver**
283 | - A daemon that exposes a REST API to *start*, *stop*, *destroy*, *list-all* VMs. Every VM started is managed by this server i.e. the lifetime of each VM is tied to the lifetime of this daemon.
284 | - The api is present at [api/server-api.yaml](./api/server-api.yaml).
285 | - [Code](./cmd/restserver)
286 | - **arrakis-client**
287 | - A Golang CLI that you can use to interact with **arrakis-restserver** to spawn and manage VMs.
288 | - [Code](./cmd/client)
289 |
290 | - **Python SDK**
291 | - Checkout out the official Python SDK - [py-arrakis](https://pypi.org/project/py-arrakis/)
292 |
293 | - **Security**
294 | - Each sandbox runs in a MicroVM.
295 | - MicroVMs are lightweight Virtual Machines (compared to traditional VMs) powered by Rust based Virtual Machine Managers such as [firecracker](https://github.com/firecracker-microvm/firecracker) and [cloud-hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor).
296 | - **Arrakis** uses [cloud-hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor) as the VMM.
297 | - Any untrusted code executed within the sandbox is isolated from the host machine as well as other agents.
298 | - We use overlayfs to also protect the root filesystem of each sandbox.
299 |
300 | - **Customization**
301 | - Dockerfile based rootfs customization.
302 | - Easily add packages and binaries to your VM's rootfs by manipulating a [Dockerfile](./resources/scripts/rootfs/Dockerfile).
303 | - Out of the box networking setup for the guest.
304 | - Each sandbox gets a tap device that gets added to a Linux bridge on the host.
305 | - ssh access to the sandbox.
306 | - Prebuilt Linux kernel for the sandbox
307 | - Or pass your own kernel to **arrakis-client** while starting VMs.
308 |
309 | ---
310 |
311 | ## Customization
312 |
313 | - [Detailed README](./docs/detailed-README.md) goes over how to customize the default packages and binaries running in a sandbox.
314 |
315 | ---
316 |
317 | ## Contribution
318 |
319 | Thank you for considering contributing to **arrakis**! 🎉
320 |
321 | Feel free to open a PR. A detailed contribution guide is going to be available soon.
322 |
323 | ## Legal Info
324 |
325 | ### Contributor License Agreement
326 |
327 | In order for us to accept patches and other contributions from you, you need to adopt our Arrakis Contributor License Agreement (the "**CLA**"). Please drop a line at abshkbh@gmail.com to start this process.
328 |
329 | Arrakis uses a tool called CLA Assistant to help us keep track of the CLA status of contributors. CLA Assistant will post a comment to your pull request indicating whether you have signed the CLA or not. If you have not signed the CLA, you will need to do so before we can accept your contribution. Signing the CLA would be one-time process, is valid for all future contributions to Arrakis, and can be done in under a minute by signing in with your GitHub account.
330 |
331 |
332 | ### License
333 |
334 | By contributing to Arrakis, you agree that your contributions will be licensed under the [GNU Affero General Public License v3.0](LICENSE) and as commercial software.
335 |
336 | ---
337 |
338 | ## License
339 |
340 | This project is licensed under the [GNU Affero General Public License v3.0](./LICENSE). For commercial licensing, please drop a line at abshkbh@gmail.com.
341 |
342 | ---
343 |
--------------------------------------------------------------------------------
/api/server-api.yaml:
--------------------------------------------------------------------------------
1 | openapi: 3.0.0
2 | info:
3 | title: VM Management API
4 | description: API for managing VMs via REST endpoints.
5 | version: 2.0.0
6 | servers:
7 | - url: http://{host}:{port}
8 | description: Development server
9 | variables:
10 | host:
11 | default: localhost
12 | port:
13 | default: "8080"
14 | paths:
15 | /v1/health:
16 | get:
17 | summary: Health check endpoint
18 | responses:
19 | '200':
20 | description: Service is healthy
21 | content:
22 | application/json:
23 | schema:
24 | type: object
25 | properties:
26 | status:
27 | type: string
28 | example: "healthy"
29 | timestamp:
30 | type: string
31 | format: date-time
32 | example: "2023-05-26T07:17:03Z"
33 | '503':
34 | description: Service is unhealthy
35 | content:
36 | application/json:
37 | schema:
38 | $ref: '#/components/schemas/ErrorResponse'
39 | /v1/vms:
40 | get:
41 | summary: List all VMs
42 | responses:
43 | '200':
44 | description: List of all VMs
45 | content:
46 | application/json:
47 | schema:
48 | $ref: '#/components/schemas/ListAllVMsResponse'
49 | '500':
50 | description: Internal server error
51 | content:
52 | application/json:
53 | schema:
54 | $ref: '#/components/schemas/ErrorResponse'
55 | post:
56 | summary: Start a VM
57 | requestBody:
58 | required: true
59 | content:
60 | application/json:
61 | schema:
62 | $ref: '#/components/schemas/StartVMRequest'
63 | responses:
64 | '200':
65 | description: Successfully started VM
66 | content:
67 | application/json:
68 | schema:
69 | $ref: '#/components/schemas/StartVMResponse'
70 | '400':
71 | description: Invalid request body
72 | content:
73 | application/json:
74 | schema:
75 | $ref: '#/components/schemas/ErrorResponse'
76 | '500':
77 | description: Internal server error
78 | content:
79 | application/json:
80 | schema:
81 | $ref: '#/components/schemas/ErrorResponse'
82 | delete:
83 | summary: Destroy all VMs
84 | responses:
85 | '200':
86 | description: Successfully destroyed all VMs
87 | content:
88 | application/json:
89 | schema:
90 | $ref: '#/components/schemas/DestroyAllVMsResponse'
91 | '500':
92 | description: Internal server error
93 | content:
94 | application/json:
95 | schema:
96 | $ref: '#/components/schemas/ErrorResponse'
97 | /v1/vms/{name}:
98 | get:
99 | summary: Get details of a specific VM
100 | parameters:
101 | - name: name
102 | in: path
103 | required: true
104 | description: Name of the VM
105 | schema:
106 | type: string
107 | responses:
108 | '200':
109 | description: VM details
110 | content:
111 | application/json:
112 | schema:
113 | $ref: '#/components/schemas/ListVMResponse'
114 | '500':
115 | description: Internal server error
116 | content:
117 | application/json:
118 | schema:
119 | $ref: '#/components/schemas/ErrorResponse'
120 | patch:
121 | summary: Update the state of a specific VM
122 | parameters:
123 | - name: name
124 | in: path
125 | required: true
126 | description: Name of the VM
127 | schema:
128 | type: string
129 | requestBody:
130 | required: true
131 | content:
132 | application/json:
133 | schema:
134 | type: object
135 | properties:
136 | status:
137 | type: string
138 | enum: [stopped, paused]
139 | description: Action to perform on the VM
140 | responses:
141 | '200':
142 | description: Successfully updated VM state
143 | content:
144 | application/json:
145 | schema:
146 | $ref: '#/components/schemas/VMResponse'
147 | '400':
148 | description: Invalid request body
149 | content:
150 | application/json:
151 | schema:
152 | $ref: '#/components/schemas/ErrorResponse'
153 | '404':
154 | description: VM not found
155 | content:
156 | application/json:
157 | schema:
158 | $ref: '#/components/schemas/ErrorResponse'
159 | '500':
160 | description: Internal server error
161 | content:
162 | application/json:
163 | schema:
164 | $ref: '#/components/schemas/ErrorResponse'
165 | delete:
166 | summary: Destroy a specific VM
167 | parameters:
168 | - name: name
169 | in: path
170 | required: true
171 | description: Name of the VM to destroy
172 | schema:
173 | type: string
174 | responses:
175 | '200':
176 | description: Successfully destroyed VM
177 | content:
178 | application/json:
179 | schema:
180 | $ref: '#/components/schemas/VMResponse'
181 | '404':
182 | description: VM not found
183 | content:
184 | application/json:
185 | schema:
186 | $ref: '#/components/schemas/ErrorResponse'
187 | '500':
188 | description: Internal server error
189 | content:
190 | application/json:
191 | schema:
192 | $ref: '#/components/schemas/ErrorResponse'
193 | /v1/vms/{name}/snapshots:
194 | post:
195 | summary: Create a snapshot of a VM
196 | parameters:
197 | - name: name
198 | in: path
199 | required: true
200 | description: Name of the VM to snapshot
201 | schema:
202 | type: string
203 | requestBody:
204 | required: true
205 | content:
206 | application/json:
207 | schema:
208 | type: object
209 | properties:
210 | snapshotId:
211 | type: string
212 | description: Unique identifier for the snapshot
213 | responses:
214 | '200':
215 | description: Successfully created snapshot
216 | content:
217 | application/json:
218 | schema:
219 | $ref: '#/components/schemas/VMSnapshotResponse'
220 | '400':
221 | description: Invalid request body
222 | content:
223 | application/json:
224 | schema:
225 | $ref: '#/components/schemas/ErrorResponse'
226 | '404':
227 | description: VM not found
228 | content:
229 | application/json:
230 | schema:
231 | $ref: '#/components/schemas/ErrorResponse'
232 | '500':
233 | description: Internal server error
234 | content:
235 | application/json:
236 | schema:
237 | $ref: '#/components/schemas/ErrorResponse'
238 | /v1/vms/{name}/cmd:
239 | post:
240 | summary: Execute command in VM
241 | parameters:
242 | - name: name
243 | in: path
244 | required: true
245 | description: Name of the VM
246 | schema:
247 | type: string
248 | requestBody:
249 | required: true
250 | content:
251 | application/json:
252 | schema:
253 | $ref: '#/components/schemas/VmCommandRequest'
254 | responses:
255 | '200':
256 | description: Command executed successfully
257 | content:
258 | application/json:
259 | schema:
260 | $ref: '#/components/schemas/VmCommandResponse'
261 | '400':
262 | description: Invalid request body
263 | content:
264 | application/json:
265 | schema:
266 | $ref: '#/components/schemas/ErrorResponse'
267 | '404':
268 | description: VM not found
269 | content:
270 | application/json:
271 | schema:
272 | $ref: '#/components/schemas/ErrorResponse'
273 | '500':
274 | description: Internal server error
275 | content:
276 | application/json:
277 | schema:
278 | $ref: '#/components/schemas/ErrorResponse'
279 | /v1/vms/{name}/files:
280 | post:
281 | summary: Upload files to VM
282 | parameters:
283 | - name: name
284 | in: path
285 | required: true
286 | description: Name of the VM
287 | schema:
288 | type: string
289 | requestBody:
290 | required: true
291 | content:
292 | application/json:
293 | schema:
294 | $ref: '#/components/schemas/VmFileUploadRequest'
295 | responses:
296 | '200':
297 | description: Files uploaded successfully
298 | content:
299 | application/json:
300 | schema:
301 | $ref: '#/components/schemas/VmFileUploadResponse'
302 | '400':
303 | description: Invalid request body
304 | content:
305 | application/json:
306 | schema:
307 | $ref: '#/components/schemas/ErrorResponse'
308 | '404':
309 | description: VM not found
310 | content:
311 | application/json:
312 | schema:
313 | $ref: '#/components/schemas/ErrorResponse'
314 | '500':
315 | description: Internal server error
316 | content:
317 | application/json:
318 | schema:
319 | $ref: '#/components/schemas/ErrorResponse'
320 | get:
321 | summary: Download files from VM
322 | parameters:
323 | - name: name
324 | in: path
325 | required: true
326 | description: Name of the VM
327 | schema:
328 | type: string
329 | - name: paths
330 | in: query
331 | required: true
332 | description: Comma-separated list of file paths to download
333 | schema:
334 | type: string
335 | responses:
336 | '200':
337 | description: Files downloaded successfully
338 | content:
339 | application/json:
340 | schema:
341 | $ref: '#/components/schemas/VmFileDownloadResponse'
342 | '400':
343 | description: Missing paths parameter
344 | content:
345 | application/json:
346 | schema:
347 | $ref: '#/components/schemas/ErrorResponse'
348 | '404':
349 | description: VM not found
350 | content:
351 | application/json:
352 | schema:
353 | $ref: '#/components/schemas/ErrorResponse'
354 | '500':
355 | description: Internal server error
356 | content:
357 | application/json:
358 | schema:
359 | $ref: '#/components/schemas/ErrorResponse'
360 | components:
361 | schemas:
362 | ErrorResponse:
363 | type: object
364 | properties:
365 | error:
366 | type: object
367 | properties:
368 | message:
369 | type: string
370 | description: Error message describing what went wrong
371 | StartVMRequest:
372 | type: object
373 | properties:
374 | vmName:
375 | type: string
376 | description: Name of the VM to start
377 | kernel:
378 | type: string
379 | description: Path of the kernel image to be used
380 | initramfs:
381 | type: string
382 | description: Path of the initramfs image to be used
383 | rootfs:
384 | type: string
385 | description: Path of the rootfs image to be used
386 | entryPoint:
387 | type: string
388 | description: Optional entry point to start in the VM upon boot
389 | snapshotId:
390 | type: string
391 | description: Optional ID of the snapshot to restore from. If provided, kernel and rootfs are ignored
392 | StartVMResponse:
393 | type: object
394 | properties:
395 | vmName:
396 | type: string
397 | status:
398 | type: string
399 | ip:
400 | type: string
401 | tapDeviceName:
402 | type: string
403 | portForwards:
404 | type: array
405 | items:
406 | $ref: '#/components/schemas/PortForward'
407 | VMRequest:
408 | type: object
409 | properties:
410 | vmName:
411 | type: string
412 | description: Name of the VM
413 | VMResponse:
414 | type: object
415 | properties:
416 | success:
417 | type: boolean
418 | message:
419 | type: string
420 | DestroyAllVMsResponse:
421 | type: object
422 | properties:
423 | success:
424 | type: boolean
425 | ListAllVMsResponse:
426 | type: object
427 | properties:
428 | vms:
429 | type: array
430 | items:
431 | type: object
432 | properties:
433 | vmName:
434 | type: string
435 | status:
436 | type: string
437 | ip:
438 | type: string
439 | tapDeviceName:
440 | type: string
441 | portForwards:
442 | type: array
443 | items:
444 | $ref: '#/components/schemas/PortForward'
445 | ListVMResponse:
446 | type: object
447 | properties:
448 | vmName:
449 | type: string
450 | status:
451 | type: string
452 | ip:
453 | type: string
454 | tapDeviceName:
455 | type: string
456 | portForwards:
457 | type: array
458 | items:
459 | $ref: '#/components/schemas/PortForward'
460 | VmCommandRequest:
461 | type: object
462 | required:
463 | - cmd
464 | properties:
465 | cmd:
466 | type: string
467 | description: Command to execute in the VM
468 | blocking:
469 | type: boolean
470 | description: Whether to wait for the command to complete before returning (default true)
471 | VmCommandResponse:
472 | type: object
473 | properties:
474 | output:
475 | type: string
476 | description: Command output
477 | error:
478 | type: string
479 | description: Error message if command failed
480 | VmFileUploadRequest:
481 | type: object
482 | required:
483 | - files
484 | properties:
485 | files:
486 | type: array
487 | description: Files to upload to the VM
488 | items:
489 | type: object
490 | required:
491 | - path
492 | - content
493 | properties:
494 | path:
495 | type: string
496 | description: Path where to save the file in the VM
497 | content:
498 | type: string
499 | description: Content of the file
500 | VmFileUploadResponse:
501 | type: object
502 | properties:
503 | error:
504 | type: string
505 | description: Error message if file upload failed
506 | VmFileDownloadResponse:
507 | type: object
508 | properties:
509 | files:
510 | type: array
511 | items:
512 | type: object
513 | properties:
514 | path:
515 | type: string
516 | description: Path of the file
517 | content:
518 | type: string
519 | description: Content of the file
520 | error:
521 | type: string
522 | description: Error message if file download failed
523 | PortForward:
524 | type: object
525 | properties:
526 | hostPort:
527 | type: string
528 | guestPort:
529 | type: string
530 | description:
531 | type: string
532 | description: Description of what's running on this port
533 | VMSnapshotResponse:
534 | type: object
535 | properties:
536 | snapshotId:
537 | type: string
538 |
--------------------------------------------------------------------------------
/cmd/client/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "fmt"
7 | "io"
8 | "net"
9 | "net/http"
10 | "os"
11 | "strings"
12 |
13 | log "github.com/sirupsen/logrus"
14 | "github.com/urfave/cli/v2"
15 |
16 | "github.com/abshkbh/arrakis/out/gen/serverapi"
17 | "github.com/abshkbh/arrakis/pkg/config"
18 | )
19 |
20 | var (
21 | apiClient *serverapi.APIClient
22 | )
23 |
24 | // parseErrorResponse attempts to parse the HTTP response body as an ErrorResponse.
25 | // It returns a formatted error with the error message from the response if successful,
26 | // or falls back to a generic error if parsing fails.
27 | func parseErrorResponse(operation string, httpResp *http.Response, err error) error {
28 | if httpResp == nil {
29 | return fmt.Errorf("failed to %s: %v", operation, err)
30 | }
31 |
32 | defer httpResp.Body.Close()
33 | body, readErr := io.ReadAll(httpResp.Body)
34 | if readErr != nil {
35 | return fmt.Errorf("failed to %s: %v (error reading response body: %v)", operation, err, readErr)
36 | }
37 |
38 | var errorResp serverapi.ErrorResponse
39 | if jsonErr := json.Unmarshal(body, &errorResp); jsonErr == nil && errorResp.Error != nil {
40 | // Successfully parsed ErrorResponse
41 | return fmt.Errorf("failed to %s: %s (HTTP %d)", operation, errorResp.Error.GetMessage(), httpResp.StatusCode)
42 | }
43 |
44 | // Couldn't parse as ErrorResponse, use raw body
45 | return fmt.Errorf("failed to %s: %s (HTTP %d)", operation, string(body), httpResp.StatusCode)
46 | }
47 |
48 | func stopVM(vmName string) error {
49 | req := apiClient.DefaultAPI.V1VmsNamePatch(context.Background(), vmName)
50 |
51 | req = req.V1VmsNamePatchRequest(serverapi.V1VmsNamePatchRequest{
52 | Status: serverapi.PtrString("stopped"),
53 | })
54 |
55 | _, httpResp, err := req.Execute()
56 | if err != nil {
57 | return parseErrorResponse("stop VM", httpResp, err)
58 | }
59 |
60 | log.Infof("successfully stopped VM: %s", vmName)
61 | return nil
62 | }
63 |
64 | func destroyVM(vmName string) error {
65 | _, httpResp, err := apiClient.DefaultAPI.V1VmsNameDelete(context.Background(), vmName).Execute()
66 | if err != nil {
67 | return parseErrorResponse("destroy VM", httpResp, err)
68 | }
69 |
70 | log.Infof("successfully destroyed VM: %s", vmName)
71 | return nil
72 | }
73 |
74 | func destroyAllVMs() error {
75 | _, httpResp, err := apiClient.DefaultAPI.V1VmsDelete(context.Background()).Execute()
76 | if err != nil {
77 | return parseErrorResponse("destroy all VMs", httpResp, err)
78 | }
79 |
80 | log.Infof("destroyed all VMs")
81 | return nil
82 | }
83 |
84 | func startVM(vmName string, kernel string, rootfs string, entryPoint string, snapshotId string) error {
85 | var startVMRequest *serverapi.StartVMRequest
86 | if snapshotId != "" {
87 | // If snapshot ID is provided, restore the VM from the snapshot
88 | startVMRequest = &serverapi.StartVMRequest{
89 | VmName: serverapi.PtrString(vmName),
90 | SnapshotId: serverapi.PtrString(snapshotId),
91 | }
92 | } else {
93 | startVMRequest = &serverapi.StartVMRequest{
94 | VmName: serverapi.PtrString(vmName),
95 | Kernel: serverapi.PtrString(kernel),
96 | Rootfs: serverapi.PtrString(rootfs),
97 | EntryPoint: serverapi.PtrString(entryPoint),
98 | }
99 | }
100 |
101 | resp, httpResp, err := apiClient.DefaultAPI.V1VmsPost(context.Background()).StartVMRequest(*startVMRequest).Execute()
102 | if err != nil {
103 | return parseErrorResponse("start VM", httpResp, err)
104 | }
105 |
106 | resp_bytes, err := resp.MarshalJSON()
107 | if err != nil {
108 | return fmt.Errorf("failed to marshal response: %w", err)
109 | }
110 | log.Infof("started VM: %v", string(resp_bytes))
111 | return nil
112 | }
113 |
114 | func listAllVMs() error {
115 | resp, httpResp, err := apiClient.DefaultAPI.V1VmsGet(context.Background()).Execute()
116 | if err != nil {
117 | return parseErrorResponse("list all VMs", httpResp, err)
118 | }
119 |
120 | // Format output to better show port forwards with descriptions
121 | fmt.Println("Available VMs:")
122 | fmt.Println("-------------")
123 |
124 | for _, vm := range resp.GetVms() {
125 | fmt.Printf("VM Name: %s\n", vm.GetVmName())
126 | fmt.Printf("Status: %s\n", vm.GetStatus())
127 | fmt.Printf("IP Address: %s\n", vm.GetIp())
128 | fmt.Printf("Tap Device: %s\n", vm.GetTapDeviceName())
129 |
130 | // Print port forwards with descriptions
131 | if len(vm.GetPortForwards()) > 0 {
132 | fmt.Println("Port Forwards:")
133 | for _, pf := range vm.GetPortForwards() {
134 | fmt.Printf(" %s -> %s: %s\n",
135 | pf.GetHostPort(),
136 | pf.GetGuestPort(),
137 | pf.GetDescription())
138 | }
139 | }
140 | fmt.Println("-------------")
141 | }
142 |
143 | return nil
144 | }
145 |
146 | func createApiClient(serverAddr string) (*serverapi.APIClient, error) {
147 | host, port, err := net.SplitHostPort(serverAddr)
148 | if err != nil {
149 | return nil, fmt.Errorf("failed to parse server address: %v", err)
150 | }
151 |
152 | serverConfiguration := &serverapi.ServerConfiguration{
153 | URL: "http://{host}:{port}",
154 | Description: "Development server",
155 | Variables: map[string]serverapi.ServerVariable{
156 | "host": {
157 | Description: "host",
158 | DefaultValue: host,
159 | },
160 | "port": {
161 | Description: "port",
162 | DefaultValue: port,
163 | },
164 | },
165 | }
166 |
167 | configuration := serverapi.NewConfiguration()
168 | configuration.Servers = serverapi.ServerConfigurations{
169 | *serverConfiguration,
170 | }
171 | apiClient = serverapi.NewAPIClient(configuration)
172 |
173 | return apiClient, nil
174 | }
175 |
176 | func snapshotVM(vmName string, snapshotId string) error {
177 | req := serverapi.V1VmsNameSnapshotsPostRequest{}
178 | if snapshotId != "" {
179 | req.SetSnapshotId(snapshotId)
180 | }
181 |
182 | resp, httpResp, err := apiClient.DefaultAPI.V1VmsNameSnapshotsPost(context.Background(), vmName).V1VmsNameSnapshotsPostRequest(req).Execute()
183 | if err != nil {
184 | return parseErrorResponse("create snapshot", httpResp, err)
185 | }
186 | log.Infof("successfully created snapshot for VM %s with ID %s", vmName, resp.GetSnapshotId())
187 | return nil
188 | }
189 |
190 | func restoreVM(vmName string, snapshotId string) error {
191 | return startVM(vmName, "", "", "", snapshotId)
192 | }
193 |
194 | func pauseVM(vmName string) error {
195 | req := apiClient.DefaultAPI.V1VmsNamePatch(context.Background(), vmName)
196 | req = req.V1VmsNamePatchRequest(serverapi.V1VmsNamePatchRequest{
197 | Status: serverapi.PtrString("paused"),
198 | })
199 | _, httpResp, err := req.Execute()
200 | if err != nil {
201 | return parseErrorResponse("pause VM", httpResp, err)
202 | }
203 | log.Infof("successfully paused VM: %s", vmName)
204 | return nil
205 | }
206 |
207 | func resumeVM(vmName string) error {
208 | req := apiClient.DefaultAPI.V1VmsNamePatch(context.Background(), vmName)
209 | req = req.V1VmsNamePatchRequest(serverapi.V1VmsNamePatchRequest{
210 | Status: serverapi.PtrString("stopped"),
211 | })
212 | _, httpResp, err := req.Execute()
213 | if err != nil {
214 | return parseErrorResponse("resume VM", httpResp, err)
215 | }
216 | log.Infof("successfully resumed VM: %s", vmName)
217 | return nil
218 | }
219 |
220 | func uploadFiles(vmName string, fileSpecs []string) error {
221 | if len(fileSpecs) == 0 || len(fileSpecs)%2 != 0 {
222 | return fmt.Errorf("invalid number of file specifications: must be even")
223 | }
224 |
225 | apiFiles := make([]serverapi.VmFileUploadRequestFilesInner, len(fileSpecs)/2)
226 | for i := 0; i < len(fileSpecs); i += 2 {
227 | sourcePath := fileSpecs[i]
228 | destPath := fileSpecs[i+1]
229 |
230 | log.Infof("uploading file from %s to %s", sourcePath, destPath)
231 |
232 | content, err := os.ReadFile(sourcePath)
233 | if err != nil {
234 | return fmt.Errorf("failed to read file %s: %v", sourcePath, err)
235 | }
236 |
237 | apiFiles[i/2] = serverapi.VmFileUploadRequestFilesInner{
238 | Path: destPath,
239 | Content: string(content),
240 | }
241 | }
242 |
243 | req := apiClient.DefaultAPI.V1VmsNameFilesPost(context.Background(), vmName)
244 | req = req.VmFileUploadRequest(serverapi.VmFileUploadRequest{
245 | Files: apiFiles,
246 | })
247 |
248 | _, httpResp, err := req.Execute()
249 | if err != nil {
250 | return parseErrorResponse("upload files", httpResp, err)
251 | }
252 |
253 | log.Infof("successfully uploaded %d files to VM: %s", len(fileSpecs)/2, vmName)
254 | return nil
255 | }
256 |
257 | func runCommand(vmName string, cmd string) error {
258 | req := serverapi.VmCommandRequest{
259 | Cmd: cmd,
260 | Blocking: serverapi.PtrBool(true),
261 | }
262 |
263 | resp, httpResp, err := apiClient.DefaultAPI.V1VmsNameCmdPost(context.Background(), vmName).VmCommandRequest(req).Execute()
264 | if err != nil {
265 | return parseErrorResponse("run command", httpResp, err)
266 | }
267 |
268 | if resp.GetError() != "" {
269 | return fmt.Errorf("command failed: %s\nOutput: %s", resp.GetError(), resp.GetOutput())
270 | }
271 | fmt.Println(resp.GetOutput())
272 | return nil
273 | }
274 |
275 | func downloadFiles(vmName string, paths []string) error {
276 | pathsStr := strings.Join(paths, ",")
277 | resp, httpResp, err := apiClient.DefaultAPI.V1VmsNameFilesGet(context.Background(), vmName).Paths(pathsStr).Execute()
278 | if err != nil {
279 | return parseErrorResponse("download files", httpResp, err)
280 | }
281 |
282 | for _, file := range resp.GetFiles() {
283 | log.Infof("Downloaded file: %s", file.GetPath())
284 | fmt.Printf("Content: %s\n", file.GetContent())
285 | }
286 | return nil
287 | }
288 |
289 | func listVM(vmName string) error {
290 | resp, httpResp, err := apiClient.DefaultAPI.V1VmsNameGet(context.Background(), vmName).Execute()
291 | if err != nil {
292 | return parseErrorResponse("get VM info", httpResp, err)
293 | }
294 |
295 | fmt.Printf("VM Name: %s\n", resp.GetVmName())
296 | fmt.Printf("Status: %s\n", resp.GetStatus())
297 | fmt.Printf("IP Address: %s\n", resp.GetIp())
298 | fmt.Printf("Tap Device: %s\n", resp.GetTapDeviceName())
299 |
300 | // Print port forwards with descriptions
301 | if len(resp.GetPortForwards()) > 0 {
302 | fmt.Println("Port Forwards:")
303 | for _, pf := range resp.GetPortForwards() {
304 | fmt.Printf(" %s -> %s: %s\n",
305 | pf.GetHostPort(),
306 | pf.GetGuestPort(),
307 | pf.GetDescription())
308 | }
309 | }
310 |
311 | return nil
312 | }
313 |
314 | func main() {
315 | app := &cli.App{
316 | Name: "arrakis-client",
317 | Usage: "A CLI for managing VMs",
318 | Flags: []cli.Flag{
319 | &cli.StringFlag{
320 | Name: "config",
321 | Aliases: []string{"c"},
322 | Usage: "Path to config file",
323 | Value: "./config.yaml",
324 | },
325 | },
326 | Before: func(ctx *cli.Context) error {
327 | configPath := ctx.String("config")
328 | clientConfig, err := config.GetClientConfig(configPath)
329 | if err != nil {
330 | return fmt.Errorf("failed to get client config: %v", err)
331 | }
332 | log.Infof("client config: %v", clientConfig)
333 |
334 | apiClient, err = createApiClient(
335 | fmt.Sprintf("%s:%s", clientConfig.ServerHost, clientConfig.ServerPort),
336 | )
337 | if err != nil {
338 | return fmt.Errorf("failed to initialize api client: %v", err)
339 | }
340 | return nil
341 | },
342 | Commands: []*cli.Command{
343 | {
344 | Name: "start",
345 | Usage: "Start a VM",
346 | Flags: []cli.Flag{
347 | &cli.StringFlag{
348 | Name: "name",
349 | Aliases: []string{"n"},
350 | Usage: "Name of the VM to create",
351 | Required: true,
352 | },
353 | &cli.StringFlag{
354 | Name: "kernel",
355 | Aliases: []string{"k"},
356 | Usage: "Path of the kernel image to be used",
357 | },
358 | &cli.StringFlag{
359 | Name: "rootfs",
360 | Aliases: []string{"r"},
361 | Usage: "Path of the rootfs image to be used",
362 | },
363 | &cli.StringFlag{
364 | Name: "entry-point",
365 | Aliases: []string{"e"},
366 | Usage: "Entry point of the VM",
367 | Required: false,
368 | },
369 | &cli.StringFlag{
370 | Name: "snapshot",
371 | Aliases: []string{"s"},
372 | Usage: "Path to snapshot directory to restore from",
373 | },
374 | },
375 | Action: func(ctx *cli.Context) error {
376 | return startVM(
377 | ctx.String("name"),
378 | ctx.String("kernel"),
379 | ctx.String("rootfs"),
380 | ctx.String("entry-point"),
381 | ctx.String("snapshot"),
382 | )
383 | },
384 | },
385 | {
386 | Name: "stop",
387 | Usage: "Stop a VM",
388 | Flags: []cli.Flag{
389 | &cli.StringFlag{
390 | Name: "name",
391 | Aliases: []string{"n"},
392 | Usage: "Name of the VM to stop",
393 | Required: true,
394 | },
395 | },
396 | Action: func(ctx *cli.Context) error {
397 | return stopVM(ctx.String("name"))
398 | },
399 | },
400 | {
401 | Name: "destroy",
402 | Usage: "Destroy a VM",
403 | Flags: []cli.Flag{
404 | &cli.StringFlag{
405 | Name: "name",
406 | Aliases: []string{"n"},
407 | Usage: "Name of the VM to destroy",
408 | Required: true,
409 | },
410 | },
411 | Action: func(ctx *cli.Context) error {
412 | return destroyVM(ctx.String("name"))
413 | },
414 | },
415 | {
416 | Name: "destroy-all",
417 | Usage: "Destroy all VMs",
418 | Action: func(ctx *cli.Context) error {
419 | return destroyAllVMs()
420 | },
421 | },
422 | {
423 | Name: "list-all",
424 | Usage: "List all VMs",
425 | Action: func(ctx *cli.Context) error {
426 | return listAllVMs()
427 | },
428 | },
429 | {
430 | Name: "list",
431 | Usage: "List VM info",
432 | Flags: []cli.Flag{
433 | &cli.StringFlag{
434 | Name: "name",
435 | Aliases: []string{"n"},
436 | Usage: "Name of the VM to destroy",
437 | Required: true,
438 | },
439 | },
440 | Action: func(ctx *cli.Context) error {
441 | return listVM(ctx.String("name"))
442 | },
443 | },
444 | {
445 | Name: "snapshot",
446 | Usage: "Create a snapshot of a VM",
447 | Flags: []cli.Flag{
448 | &cli.StringFlag{
449 | Name: "name",
450 | Aliases: []string{"n"},
451 | Usage: "Name of the VM",
452 | Required: true,
453 | },
454 | &cli.StringFlag{
455 | Name: "id",
456 | Aliases: []string{"i"},
457 | Usage: "Unique identifier for the snapshot",
458 | Required: false,
459 | },
460 | },
461 | Action: func(ctx *cli.Context) error {
462 | return snapshotVM(ctx.String("name"), ctx.String("id"))
463 | },
464 | },
465 | {
466 | Name: "restore",
467 | Usage: "Restore a VM from a snapshot",
468 | Flags: []cli.Flag{
469 | &cli.StringFlag{
470 | Name: "name",
471 | Aliases: []string{"n"},
472 | Usage: "Name to give to the restored VM",
473 | Required: true,
474 | },
475 | &cli.StringFlag{
476 | Name: "id",
477 | Aliases: []string{"i"},
478 | Usage: "ID of the snapshot to restore from",
479 | Required: true,
480 | },
481 | },
482 | Action: func(ctx *cli.Context) error {
483 | return restoreVM(ctx.String("name"), ctx.String("id"))
484 | },
485 | },
486 | {
487 | Name: "pause",
488 | Usage: "Pause a running VM",
489 | Flags: []cli.Flag{
490 | &cli.StringFlag{
491 | Name: "name",
492 | Aliases: []string{"n"},
493 | Usage: "Name of the VM to pause",
494 | Required: true,
495 | },
496 | },
497 | Action: func(ctx *cli.Context) error {
498 | return pauseVM(ctx.String("name"))
499 | },
500 | },
501 | {
502 | Name: "resume",
503 | Usage: "Resume a paused VM",
504 | Flags: []cli.Flag{
505 | &cli.StringFlag{
506 | Name: "name",
507 | Aliases: []string{"n"},
508 | Usage: "Name of the VM to resume",
509 | Required: true,
510 | },
511 | },
512 | Action: func(ctx *cli.Context) error {
513 | return resumeVM(ctx.String("name"))
514 | },
515 | },
516 | {
517 | Name: "upload",
518 | Usage: "Upload files to a VM",
519 | Flags: []cli.Flag{
520 | &cli.StringFlag{
521 | Name: "name",
522 | Aliases: []string{"n"},
523 | Usage: "Name of the VM",
524 | Required: true,
525 | },
526 | &cli.StringSliceFlag{
527 | Name: "file",
528 | Aliases: []string{"f"},
529 | Usage: "File(s) to upload in format 'source,destination' (can be specified multiple times)",
530 | Required: true,
531 | },
532 | },
533 | Action: func(ctx *cli.Context) error {
534 | return uploadFiles(ctx.String("name"), ctx.StringSlice("file"))
535 | },
536 | },
537 | {
538 | Name: "run",
539 | Usage: "Run a command in a VM",
540 | Flags: []cli.Flag{
541 | &cli.StringFlag{
542 | Name: "name",
543 | Aliases: []string{"n"},
544 | Usage: "Name of the VM",
545 | Required: true,
546 | },
547 | &cli.StringFlag{
548 | Name: "cmd",
549 | Aliases: []string{"c"},
550 | Usage: "Command to run",
551 | Required: true,
552 | },
553 | },
554 | Action: func(ctx *cli.Context) error {
555 | return runCommand(ctx.String("name"), ctx.String("cmd"))
556 | },
557 | },
558 | {
559 | Name: "download",
560 | Usage: "Download files from a VM",
561 | Flags: []cli.Flag{
562 | &cli.StringFlag{
563 | Name: "name",
564 | Aliases: []string{"n"},
565 | Usage: "Name of the VM",
566 | Required: true,
567 | },
568 | &cli.StringSliceFlag{
569 | Name: "path",
570 | Aliases: []string{"p"},
571 | Usage: "Path(s) to download (can be specified multiple times)",
572 | Required: true,
573 | },
574 | },
575 | Action: func(ctx *cli.Context) error {
576 | return downloadFiles(ctx.String("name"), ctx.StringSlice("path"))
577 | },
578 | },
579 | },
580 | }
581 |
582 | err := app.Run(os.Args)
583 | if err != nil {
584 | log.Fatal(err)
585 | }
586 | }
587 |
--------------------------------------------------------------------------------
/cmd/cmdserver/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "encoding/json"
6 | "fmt"
7 | "net/http"
8 | "os"
9 | "os/exec"
10 | "path/filepath"
11 | "strings"
12 |
13 | log "github.com/sirupsen/logrus"
14 |
15 | "github.com/abshkbh/arrakis/pkg/cmdserver"
16 | "github.com/gorilla/mux"
17 | "github.com/mattn/go-shellwords"
18 | )
19 |
20 | const (
21 | // Define a base directory to prevent path traversal
22 | baseDir = "/tmp/server_files"
23 | )
24 |
25 | // uploadFileHandler handles "/files" POST requests.
26 | func uploadFileHandler(w http.ResponseWriter, r *http.Request) {
27 | logger := log.WithField("api", "upload")
28 | if r.Method != http.MethodPost {
29 | logger.Error("method not allowed")
30 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
31 | return
32 | }
33 |
34 | var req cmdserver.FilesPostRequest
35 | err := json.NewDecoder(r.Body).Decode(&req)
36 | if err != nil {
37 | logger.Error("invalid json body")
38 | http.Error(w, "Invalid JSON body", http.StatusBadRequest)
39 | return
40 | }
41 |
42 | for _, file_data := range req.Files {
43 | if file_data.Path == "" {
44 | logger.Warn("skipping empty file path")
45 | continue
46 | }
47 |
48 | logger.Infof("uploading file: %s", file_data.Path)
49 | var absoluteFilePath string
50 | if filepath.IsAbs(file_data.Path) {
51 | absoluteFilePath = file_data.Path
52 | } else {
53 | absoluteFilePath = filepath.Join(baseDir, file_data.Path)
54 | }
55 |
56 | file, err := os.Create(absoluteFilePath)
57 | if err != nil {
58 | logger.Errorf("failed to create file: %s err: %v", absoluteFilePath, err)
59 | http.Error(w, fmt.Sprintf("failed to create file: %s err: %v", absoluteFilePath, err), http.StatusInternalServerError)
60 | return
61 | }
62 | defer file.Close()
63 | logger.Infof("uploading file: %s", absoluteFilePath)
64 |
65 | _, err = file.WriteString(file_data.Content)
66 | if err != nil {
67 | logger.Errorf("failed to write file: %s err: %v", absoluteFilePath, err)
68 | http.Error(w, fmt.Sprintf("failed to write file: %s err: %v", absoluteFilePath, err), http.StatusInternalServerError)
69 | return
70 | }
71 | }
72 | }
73 |
74 | // downloadFileHandler handles "/files" GET requests.
75 | func downloadFileHandler(w http.ResponseWriter, r *http.Request) {
76 | if r.Method != http.MethodGet {
77 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
78 | return
79 | }
80 |
81 | // Get files from query parameter, expects comma-separated paths
82 | filesParam := r.URL.Query().Get("paths")
83 | if filesParam == "" {
84 | http.Error(w, "Missing 'paths' query parameter", http.StatusBadRequest)
85 | return
86 | }
87 |
88 | filePaths := strings.Split(filesParam, ",")
89 | response := cmdserver.FilesGetResponse{
90 | Files: make([]cmdserver.FileData, 0, len(filePaths)),
91 | }
92 |
93 | for _, filePath := range filePaths {
94 | fileResp := cmdserver.FileData{Path: filePath}
95 | // Resolve path to prevent path traversal.
96 | absolutePath := filepath.Join(baseDir, filepath.Clean(filePath))
97 | content, err := os.ReadFile(absolutePath)
98 | if err != nil {
99 | fileResp.Error = fmt.Sprintf("Failed to read file: %v", err)
100 | } else {
101 | fileResp.Content = string(content)
102 | }
103 | log.WithField("api", "download").Infof("downloading file: %s", absolutePath)
104 | response.Files = append(response.Files, fileResp)
105 | }
106 |
107 | w.Header().Set("Content-Type", "application/json")
108 | json.NewEncoder(w).Encode(response)
109 | }
110 |
111 | // runCommandHandler handles "/cmd" POST requests.
112 | func runCommandHandler(w http.ResponseWriter, r *http.Request) {
113 | if r.Method != http.MethodPost {
114 | log.WithField("api", "run_cmd").Error("method not allowed")
115 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
116 | return
117 | }
118 |
119 | var req struct {
120 | Cmd string `json:"cmd"`
121 | Blocking bool `json:"blocking,omitempty"`
122 | }
123 | // Block by default if not specified in the payload.
124 | req.Blocking = true
125 |
126 | err := json.NewDecoder(r.Body).Decode(&req)
127 | if err != nil {
128 | log.WithField("api", "run_cmd").Error("invalid json body")
129 | http.Error(w, "Invalid JSON body", http.StatusBadRequest)
130 | return
131 | }
132 |
133 | if strings.TrimSpace(req.Cmd) == "" {
134 | log.WithField("api", "run_cmd").Error("empty command")
135 | http.Error(w, "Empty Command", http.StatusBadRequest)
136 | return
137 | }
138 |
139 | // Parse the command string using shellwords to handle quotes and escaped spaces
140 | parser := shellwords.NewParser()
141 | parts, err := parser.Parse(req.Cmd)
142 | if err != nil {
143 | log.WithFields(log.Fields{
144 | "api": "run_cmd",
145 | }).Errorf("failed to parse command string: %v", err)
146 | http.Error(w, fmt.Sprintf("failed to parse command string: %v", err), http.StatusBadRequest)
147 | return
148 | }
149 |
150 | if len(parts) == 0 {
151 | log.WithFields(log.Fields{
152 | "api": "run_cmd",
153 | }).Error("empty command string")
154 | http.Error(w, "empty command string", http.StatusBadRequest)
155 | return
156 | }
157 |
158 | cmdName := parts[0]
159 | cmdArgs := parts[1:]
160 |
161 | // Set up environment variables
162 | env := os.Environ()
163 | customPath := "/usr/local/bin:/usr/bin:/bin" // Modify as needed
164 | env = append(env, "PATH="+customPath)
165 |
166 | // Create the command
167 | cmd := exec.Command("bash", "-c", req.Cmd)
168 | cmd.Env = env
169 | cmd.Dir = baseDir
170 |
171 | // Log the command execution details
172 | log.WithFields(log.Fields{
173 | "api": "run_cmd",
174 | "cmd": cmdName,
175 | "args": cmdArgs,
176 | "workingDir": cmd.Dir,
177 | }).Info("Executing command")
178 |
179 | // Handle command execution based on blocking mode
180 | if req.Blocking {
181 | // Execute the command and capture the combined output in blocking mode
182 | output, err := cmd.CombinedOutput()
183 | if err != nil {
184 | log.WithFields(log.Fields{
185 | "api": "run_cmd",
186 | "cmd": cmdName,
187 | "args": cmdArgs,
188 | }).Errorf("command execution failed output: %s err: %v", string(output), err)
189 | resp := cmdserver.RunCmdResponse{
190 | Error: err.Error(),
191 | Output: string(output),
192 | }
193 | writeJSON(w, resp)
194 | return
195 | }
196 |
197 | // Log successful execution
198 | log.WithFields(log.Fields{
199 | "api": "run_cmd",
200 | "cmd": cmdName,
201 | "args": cmdArgs,
202 | "output": string(output),
203 | "workingDir": cmd.Dir,
204 | }).Info("command executed successfully")
205 |
206 | // Respond with the command output
207 | resp := cmdserver.RunCmdResponse{
208 | Output: string(output),
209 | }
210 | writeJSON(w, resp)
211 | } else {
212 | // Non-blocking mode: start the command but don't wait for it to complete
213 | // Set up pipes for stdout and stderr
214 | stdoutPipe, err := cmd.StdoutPipe()
215 | if err != nil {
216 | log.WithFields(log.Fields{
217 | "api": "run_cmd",
218 | "cmd": cmdName,
219 | "args": cmdArgs,
220 | }).Errorf("failed to create stdout pipe: %v", err)
221 | resp := cmdserver.RunCmdResponse{
222 | Error: fmt.Sprintf("failed to create stdout pipe: %v", err),
223 | }
224 | writeJSON(w, resp)
225 | return
226 | }
227 |
228 | stderrPipe, err := cmd.StderrPipe()
229 | if err != nil {
230 | log.WithFields(log.Fields{
231 | "api": "run_cmd",
232 | "cmd": cmdName,
233 | "args": cmdArgs,
234 | }).Errorf("failed to create stderr pipe: %v", err)
235 | resp := cmdserver.RunCmdResponse{
236 | Error: fmt.Sprintf("failed to create stderr pipe: %v", err),
237 | }
238 | writeJSON(w, resp)
239 | return
240 | }
241 |
242 | // Start the command
243 | if err := cmd.Start(); err != nil {
244 | log.WithFields(log.Fields{
245 | "api": "run_cmd",
246 | "cmd": cmdName,
247 | "args": cmdArgs,
248 | }).Errorf("failed to start command: %v", err)
249 | resp := cmdserver.RunCmdResponse{
250 | Error: fmt.Sprintf("failed to start command: %v", err),
251 | }
252 | writeJSON(w, resp)
253 | return
254 | }
255 |
256 | // Start goroutines to handle stdout and stderr in the background
257 | go func() {
258 | scanner := bufio.NewScanner(stdoutPipe)
259 | for scanner.Scan() {
260 | log.WithFields(log.Fields{
261 | "api": "run_cmd",
262 | "cmd": cmdName,
263 | "stdout": scanner.Text(),
264 | }).Debug("command stdout")
265 | }
266 | }()
267 |
268 | go func() {
269 | scanner := bufio.NewScanner(stderrPipe)
270 | for scanner.Scan() {
271 | log.WithFields(log.Fields{
272 | "api": "run_cmd",
273 | "cmd": cmdName,
274 | "stderr": scanner.Text(),
275 | }).Debug("command stderr")
276 | }
277 | }()
278 |
279 | // Start a goroutine to wait for the command to complete
280 | go func() {
281 | err := cmd.Wait()
282 | if err != nil {
283 | log.WithFields(log.Fields{
284 | "api": "run_cmd",
285 | "cmd": cmdName,
286 | "args": cmdArgs,
287 | }).Errorf("command execution failed: %v", err)
288 | } else {
289 | log.WithFields(log.Fields{
290 | "api": "run_cmd",
291 | "cmd": cmdName,
292 | "args": cmdArgs,
293 | }).Info("command completed successfully")
294 | }
295 | }()
296 |
297 | // Respond immediately with a success message
298 | resp := cmdserver.RunCmdResponse{
299 | Output: fmt.Sprintf("Command '%s' started in background", cmd.String()),
300 | }
301 | writeJSON(w, resp)
302 | }
303 | }
304 |
305 | // indexHandler handles "/" GET requests.
306 | func indexHandler(w http.ResponseWriter, r *http.Request) {
307 | if r.Method != http.MethodGet {
308 | http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
309 | return
310 | }
311 |
312 | response := map[string]string{
313 | "msg": "Hello from cmdserver",
314 | }
315 |
316 | w.Header().Set("Content-Type", "application/json")
317 | json.NewEncoder(w).Encode(response)
318 | }
319 |
320 | // Utility function to write JSON response
321 | func writeJSON(w http.ResponseWriter, resp cmdserver.RunCmdResponse) {
322 | w.Header().Set("Content-Type", "application/json")
323 | json.NewEncoder(w).Encode(resp)
324 | }
325 |
326 | func main() {
327 | // Ensure base directory exists.
328 | err := os.MkdirAll(baseDir, os.ModePerm)
329 | if err != nil {
330 | log.Fatalf("Failed to create base directory: %v", err)
331 | }
332 |
333 | // Initialize Gorilla Mux router.
334 | router := mux.NewRouter()
335 |
336 | // Register routes with their respective handlers.
337 | router.HandleFunc("/", indexHandler).Methods(http.MethodGet)
338 | router.HandleFunc("/files", uploadFileHandler).Methods(http.MethodPost)
339 | router.HandleFunc("/files", downloadFileHandler).Methods(http.MethodGet)
340 | router.HandleFunc("/cmd", runCommandHandler).Methods(http.MethodPost)
341 |
342 | // Optionally, add logging middleware.
343 | router.Use(loggingMiddleware)
344 |
345 | port := "4031"
346 | log.Printf("Server is running on port %s...", port)
347 | log.Fatal(http.ListenAndServe(":"+port, router))
348 | }
349 |
350 | // Optional: Middleware for logging requests.
351 | func loggingMiddleware(next http.Handler) http.Handler {
352 | return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
353 | log.Printf("[%s] %s %s", r.RemoteAddr, r.Method, r.URL.Path)
354 | next.ServeHTTP(w, r)
355 | })
356 | }
357 |
--------------------------------------------------------------------------------
/cmd/guestinit/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "os"
7 | "os/exec"
8 | "strings"
9 |
10 | log "github.com/sirupsen/logrus"
11 | )
12 |
13 | const (
14 | ifname = "eth0"
15 | ipBin = "/usr/bin/ip"
16 | )
17 |
18 | // parseKeyFromCmdLine parses a key from the kernel command line. Assumes each
19 | // key:val is present like key="val" in /proc/cmdline.
20 | func parseKeyFromCmdLine(prefix string) (string, error) {
21 | cmdline, err := os.ReadFile("/proc/cmdline")
22 | if err != nil {
23 | return "", fmt.Errorf("failed to read /proc/cmdline: %w", err)
24 | }
25 |
26 | key := prefix + "="
27 | cmdlineStr := string(cmdline)
28 |
29 | start := strings.Index(cmdlineStr, key)
30 | if start == -1 {
31 | return "", fmt.Errorf("key %q not found in kernel command line", key)
32 | }
33 |
34 | start += len(key)
35 | value := strings.TrimPrefix(cmdlineStr[start:], "\"")
36 | end := strings.IndexByte(value, '"')
37 | if end == -1 {
38 | return "", fmt.Errorf("unclosed quote for key %q in kernel command line", key)
39 | }
40 | return value[:end], nil
41 | }
42 |
43 | // parseNetworkingMetadata parses the networking metadata from the kernel command line.
44 | func parseNetworkingMetadata() (string, string, error) {
45 | guestCIDR, err := parseKeyFromCmdLine("guest_ip")
46 | if err != nil {
47 | return "", "", fmt.Errorf("failed to parse guest_ip: %w", err)
48 | }
49 |
50 | gatewayCIDR, err := parseKeyFromCmdLine("gateway_ip")
51 | if err != nil {
52 | return "", "", fmt.Errorf("failed to parse gateway_ip: %w", err)
53 | }
54 |
55 | if guestCIDR == "" || gatewayCIDR == "" {
56 | return "", "", fmt.Errorf("guest_ip or gateway_ip not found in kernel command line")
57 | }
58 |
59 | // gateway's IP needs to be returned without the subnet mask.
60 | gatewayIP, _, err := net.ParseCIDR(gatewayCIDR)
61 | if err != nil {
62 | return "", "", fmt.Errorf("failed to parse gatewayCIDR: %w", err)
63 | }
64 |
65 | return guestCIDR, gatewayIP.String(), nil
66 | }
67 |
68 | // setupNetworking sets up networking inside the guest.
69 | func setupNetworking(guestCIDR string, gatewayIP string) error {
70 | cmd := exec.Command(ipBin, "l", "set", "lo", "up")
71 | output, err := cmd.CombinedOutput()
72 | if err != nil {
73 | return fmt.Errorf(
74 | "failed to set the lo interface up. output: %s, error: %w",
75 | string(output),
76 | err,
77 | )
78 | }
79 | log.Info("lo interface up")
80 |
81 | cmd = exec.Command(ipBin, "a", "add", guestCIDR, "dev", ifname)
82 | output, err = cmd.CombinedOutput()
83 | if err != nil {
84 | return fmt.Errorf(
85 | "failed to add IP address to interface. output: %s, error: %w",
86 | string(output),
87 | err,
88 | )
89 | }
90 |
91 | cmd = exec.Command(ipBin, "l", "set", ifname, "up")
92 | output, err = cmd.CombinedOutput()
93 | if err != nil {
94 | return fmt.Errorf(
95 | "failed to set interface up. output: %s, error: %w",
96 | string(output),
97 | err,
98 | )
99 | }
100 |
101 | cmd = exec.Command(ipBin, "r", "add", "default", "via", gatewayIP, "dev", ifname)
102 | output, err = cmd.CombinedOutput()
103 | if err != nil {
104 | return fmt.Errorf(
105 | "failed to add default route. output: %s, error: %w",
106 | string(output),
107 | err,
108 | )
109 | }
110 |
111 | f, err := os.OpenFile("/etc/resolv.conf", os.O_APPEND|os.O_WRONLY, 0644)
112 | if err != nil {
113 | return fmt.Errorf(
114 | "failed to open /etc/resolv.conf. error: %w",
115 | err,
116 | )
117 | }
118 | defer f.Close()
119 |
120 | _, err = f.WriteString("nameserver 8.8.8.8\n")
121 | if err != nil {
122 | return fmt.Errorf(
123 | "failed to write nameserver to /etc/resolv.conf. error: %w",
124 | err,
125 | )
126 | }
127 | return nil
128 | }
129 |
130 | func main() {
131 | log.Infof("starting guestinit")
132 | guestCIDR, gatewayIP, err := parseNetworkingMetadata()
133 | if err != nil {
134 | log.WithError(err).Error("failed to parse guest networking metadata")
135 | }
136 |
137 | if err := setupNetworking(guestCIDR, gatewayIP); err != nil {
138 | log.WithError(err).Error("failed to setup networking")
139 | }
140 | log.Info("guestinit exiting...")
141 | }
142 |
--------------------------------------------------------------------------------
/cmd/restserver/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "context"
5 | "encoding/json"
6 | "fmt"
7 | "net/http"
8 | "os"
9 | "os/signal"
10 | "syscall"
11 | "time"
12 |
13 | "github.com/gorilla/mux"
14 | log "github.com/sirupsen/logrus"
15 | "github.com/urfave/cli/v2"
16 |
17 | "github.com/abshkbh/arrakis/out/gen/serverapi"
18 | "github.com/abshkbh/arrakis/pkg/config"
19 | "github.com/abshkbh/arrakis/pkg/server"
20 | )
21 |
22 | const (
23 | API_VERSION = "v1"
24 | )
25 |
26 | // sendErrorResponse sends a standardized error response to the client.
27 | func sendErrorResponse(w http.ResponseWriter, statusCode int, message string) {
28 | resp := serverapi.ErrorResponse{
29 | Error: &serverapi.ErrorResponseError{
30 | Message: &message,
31 | },
32 | }
33 | w.Header().Set("Content-Type", "application/json")
34 | w.WriteHeader(statusCode)
35 | json.NewEncoder(w).Encode(resp)
36 | }
37 |
38 | type restServer struct {
39 | vmServer *server.Server
40 | }
41 |
42 | // Health check endpoint for load balancer monitoring
43 | func (s *restServer) healthCheck(w http.ResponseWriter, r *http.Request) {
44 | response := map[string]interface{}{
45 | "status": "healthy",
46 | "timestamp": time.Now().UTC().Format(time.RFC3339),
47 | }
48 |
49 | w.Header().Set("Content-Type", "application/json")
50 | w.WriteHeader(http.StatusOK)
51 | json.NewEncoder(w).Encode(response)
52 | }
53 |
54 | // Implement handler functions
55 | func (s *restServer) startVM(w http.ResponseWriter, r *http.Request) {
56 | logger := log.WithField("api", "startVM")
57 | startTime := time.Now()
58 |
59 | var req serverapi.StartVMRequest
60 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
61 | logger.WithError(err).Error("Invalid request body")
62 | sendErrorResponse(
63 | w,
64 | http.StatusBadRequest,
65 | fmt.Sprintf("Invalid request format: %v", err))
66 | return
67 | }
68 |
69 | if req.GetVmName() == "" {
70 | logger.Error("Empty vm name")
71 | sendErrorResponse(
72 | w,
73 | http.StatusBadRequest,
74 | "Empty vm name")
75 | return
76 | }
77 |
78 | vmName := req.GetVmName()
79 | resp, err := s.vmServer.StartVM(r.Context(), &req)
80 | if err != nil {
81 | logger.WithField("vmName", vmName).WithError(err).Error("Failed to start VM")
82 | sendErrorResponse(
83 | w,
84 | http.StatusInternalServerError,
85 | fmt.Sprintf("Failed to start VM: %v", err))
86 | return
87 | }
88 |
89 | elapsedTime := time.Since(startTime)
90 | logger.WithFields(log.Fields{
91 | "vmName": vmName,
92 | "startupTime": elapsedTime.String(),
93 | }).Info("VM started successfully")
94 | w.Header().Set("Content-Type", "application/json")
95 | json.NewEncoder(w).Encode(resp)
96 | }
97 |
98 | func (s *restServer) destroyVM(w http.ResponseWriter, r *http.Request) {
99 | logger := log.WithField("api", "destroyVM")
100 | vars := mux.Vars(r)
101 | vmName := vars["name"]
102 |
103 | // Create request object with the VM name
104 | req := serverapi.VMRequest{
105 | VmName: &vmName,
106 | }
107 |
108 | resp, err := s.vmServer.DestroyVM(r.Context(), &req)
109 | if err != nil {
110 | logger.WithField("vmName", vmName).WithError(err).Error("Failed to destroy VM")
111 | sendErrorResponse(
112 | w,
113 | http.StatusInternalServerError,
114 | fmt.Sprintf("Failed to destroy VM: %v", err))
115 | return
116 | }
117 |
118 | w.Header().Set("Content-Type", "application/json")
119 | json.NewEncoder(w).Encode(resp)
120 | }
121 |
122 | func (s *restServer) destroyAllVMs(w http.ResponseWriter, r *http.Request) {
123 | logger := log.WithField("api", "destroyAllVMs")
124 | resp, err := s.vmServer.DestroyAllVMs(r.Context())
125 | if err != nil {
126 | logger.WithError(err).Error("Failed to destroy all VMs")
127 | sendErrorResponse(
128 | w,
129 | http.StatusInternalServerError,
130 | fmt.Sprintf("Failed to destroy all VMs: %v", err))
131 | return
132 | }
133 |
134 | w.Header().Set("Content-Type", "application/json")
135 | json.NewEncoder(w).Encode(resp)
136 | }
137 |
138 | func (s *restServer) listAllVMs(w http.ResponseWriter, r *http.Request) {
139 | logger := log.WithField("api", "listAllVMs")
140 | resp, err := s.vmServer.ListAllVMs(r.Context())
141 | if err != nil {
142 | logger.WithError(err).Error("Failed to list all VMs")
143 | sendErrorResponse(
144 | w,
145 | http.StatusInternalServerError,
146 | fmt.Sprintf("Failed to list all VMs: %v", err))
147 | return
148 | }
149 |
150 | w.Header().Set("Content-Type", "application/json")
151 | json.NewEncoder(w).Encode(resp)
152 | }
153 |
154 | func (s *restServer) listVM(w http.ResponseWriter, r *http.Request) {
155 | logger := log.WithField("api", "listVM")
156 | vars := mux.Vars(r)
157 | vmName := vars["name"]
158 | resp, err := s.vmServer.ListVM(r.Context(), vmName)
159 | if err != nil {
160 | logger.WithField("vmName", vmName).WithError(err).Error("Failed to list VM")
161 | sendErrorResponse(
162 | w,
163 | http.StatusInternalServerError,
164 | fmt.Sprintf("Failed to list VM: %v", err))
165 | return
166 | }
167 |
168 | w.Header().Set("Content-Type", "application/json")
169 | json.NewEncoder(w).Encode(resp)
170 | }
171 |
172 | func (s *restServer) snapshotVM(w http.ResponseWriter, r *http.Request) {
173 | logger := log.WithField("api", "snapshotVM")
174 | vars := mux.Vars(r)
175 | vmName := vars["name"]
176 |
177 | var req struct {
178 | SnapshotId string `json:"snapshotId,omitempty"`
179 | }
180 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
181 | logger.WithField("vmName", vmName).WithError(err).Error("Invalid request body")
182 | sendErrorResponse(
183 | w,
184 | http.StatusBadRequest,
185 | fmt.Sprintf("Invalid request format: %v", err))
186 | return
187 | }
188 |
189 | resp, err := s.vmServer.SnapshotVM(r.Context(), vmName, req.SnapshotId)
190 | if err != nil {
191 | logger.WithFields(log.Fields{
192 | "vmName": vmName,
193 | "snapshotId": req.SnapshotId,
194 | }).WithError(err).Error("Failed to create snapshot")
195 | sendErrorResponse(
196 | w,
197 | http.StatusInternalServerError,
198 | fmt.Sprintf("Failed to create snapshot: %v", err))
199 | return
200 | }
201 |
202 | w.Header().Set("Content-Type", "application/json")
203 | json.NewEncoder(w).Encode(resp)
204 | }
205 |
206 | func (s *restServer) updateVMState(w http.ResponseWriter, r *http.Request) {
207 | logger := log.WithField("api", "updateVMState")
208 | vars := mux.Vars(r)
209 | vmName := vars["name"]
210 |
211 | var req serverapi.V1VmsNamePatchRequest
212 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
213 | logger.WithField("vmName", vmName).WithError(err).Error("Invalid request body")
214 | sendErrorResponse(
215 | w,
216 | http.StatusBadRequest,
217 | fmt.Sprintf("Invalid request format: %v", err))
218 | return
219 | }
220 |
221 | status := req.GetStatus()
222 | if status != "stopped" && status != "paused" && status != "resume" {
223 | logger.WithFields(log.Fields{
224 | "vmName": vmName,
225 | "status": status,
226 | }).Error("Invalid status value")
227 | sendErrorResponse(
228 | w,
229 | http.StatusBadRequest,
230 | fmt.Sprintf("Invalid status value: %s", status))
231 | return
232 | }
233 |
234 | vmReq := serverapi.VMRequest{
235 | VmName: &vmName,
236 | }
237 |
238 | var resp *serverapi.VMResponse
239 | var err error
240 | if status == "stopped" {
241 | resp, err = s.vmServer.StopVM(r.Context(), &vmReq)
242 | } else if status == "paused" {
243 | resp, err = s.vmServer.PauseVM(r.Context(), &vmReq)
244 | } else { // status == "resume"
245 | resp, err = s.vmServer.ResumeVM(r.Context(), &vmReq)
246 | }
247 |
248 | if err != nil {
249 | logger.WithFields(log.Fields{
250 | "vmName": vmName,
251 | "status": status,
252 | }).WithError(err).Error("Failed to update VM state")
253 | sendErrorResponse(
254 | w,
255 | http.StatusInternalServerError,
256 | fmt.Sprintf("Failed to change VM state to '%s': %v", status, err))
257 | return
258 | }
259 |
260 | w.Header().Set("Content-Type", "application/json")
261 | json.NewEncoder(w).Encode(resp)
262 | }
263 |
264 | func (s *restServer) vmCommand(w http.ResponseWriter, r *http.Request) {
265 | logger := log.WithField("api", "vmCommand")
266 | vars := mux.Vars(r)
267 | vmName := vars["name"]
268 |
269 | var req serverapi.VmCommandRequest
270 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
271 | logger.WithField("vmName", vmName).WithError(err).Error("Invalid request body")
272 | sendErrorResponse(
273 | w,
274 | http.StatusBadRequest,
275 | fmt.Sprintf("Invalid request format: %v", err))
276 | return
277 | }
278 |
279 | if req.GetCmd() == "" {
280 | logger.WithField("vmName", vmName).Error("Command cannot be empty")
281 | sendErrorResponse(
282 | w,
283 | http.StatusBadRequest,
284 | "Command cannot be empty")
285 | return
286 | }
287 |
288 | cmd := req.GetCmd()
289 | // Default to blocking if not specified
290 | blocking := true
291 | if req.Blocking != nil {
292 | blocking = *req.Blocking
293 | }
294 |
295 | resp, err := s.vmServer.VMCommand(r.Context(), vmName, cmd, blocking)
296 | if err != nil {
297 | logger.WithFields(log.Fields{
298 | "vmName": vmName,
299 | "cmd": cmd,
300 | "blocking": blocking,
301 | "success": false,
302 | }).Error("Failed to execute command")
303 | sendErrorResponse(
304 | w,
305 | http.StatusInternalServerError,
306 | fmt.Sprintf("Failed to execute command: %v", err))
307 | return
308 | }
309 |
310 | logger.WithFields(log.Fields{
311 | "vmName": vmName,
312 | "cmd": cmd,
313 | "blocking": blocking,
314 | "success": true,
315 | }).Info("Successfully executed command")
316 | w.Header().Set("Content-Type", "application/json")
317 | json.NewEncoder(w).Encode(resp)
318 | }
319 |
320 | func (s *restServer) vmFileUpload(w http.ResponseWriter, r *http.Request) {
321 | logger := log.WithField("api", "vmFileUpload")
322 | vars := mux.Vars(r)
323 | vmName := vars["name"]
324 |
325 | var req serverapi.VmFileUploadRequest
326 | if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
327 | logger.WithField("vmName", vmName).WithError(err).Error("Invalid request body")
328 | sendErrorResponse(
329 | w,
330 | http.StatusBadRequest,
331 | fmt.Sprintf("Invalid request format: %v", err))
332 | return
333 | }
334 |
335 | if len(req.GetFiles()) == 0 {
336 | logger.WithField("vmName", vmName).Error("No files provided")
337 | sendErrorResponse(
338 | w,
339 | http.StatusBadRequest,
340 | "No files provided for upload")
341 | return
342 | }
343 |
344 | files := req.GetFiles()
345 | resp, err := s.vmServer.VMFileUpload(r.Context(), vmName, files)
346 | if err != nil {
347 | logger.WithFields(log.Fields{
348 | "vmName": vmName,
349 | "fileCount": len(files),
350 | }).WithError(err).Error("Failed to upload files")
351 | sendErrorResponse(
352 | w,
353 | http.StatusInternalServerError,
354 | fmt.Sprintf("Failed to upload files: %v", err))
355 | return
356 | }
357 |
358 | w.Header().Set("Content-Type", "application/json")
359 | json.NewEncoder(w).Encode(resp)
360 | }
361 |
362 | func (s *restServer) vmFileDownload(w http.ResponseWriter, r *http.Request) {
363 | logger := log.WithField("api", "vmFileDownload")
364 | vars := mux.Vars(r)
365 | vmName := vars["name"]
366 |
367 | paths := r.URL.Query().Get("paths")
368 | if paths == "" {
369 | logger.WithField("vmName", vmName).Error("Missing 'paths' query parameter")
370 | sendErrorResponse(
371 | w,
372 | http.StatusBadRequest,
373 | "Missing 'paths' query parameter")
374 | return
375 | }
376 |
377 | resp, err := s.vmServer.VMFileDownload(r.Context(), vmName, paths)
378 | if err != nil {
379 | logger.WithFields(log.Fields{
380 | "vmName": vmName,
381 | "paths": paths,
382 | }).WithError(err).Error("Failed to download files")
383 | sendErrorResponse(
384 | w,
385 | http.StatusInternalServerError,
386 | fmt.Sprintf("Failed to download files: %v", err))
387 | return
388 | }
389 |
390 | w.Header().Set("Content-Type", "application/json")
391 | json.NewEncoder(w).Encode(resp)
392 | }
393 |
394 | func main() {
395 | var serverConfig *config.ServerConfig
396 | var configFile string
397 |
398 | app := &cli.App{
399 | Name: "arrakis-restserver",
400 | Usage: "A daemon for spawning and managing cloud-hypervisor based microVMs.",
401 | Flags: []cli.Flag{
402 | &cli.StringFlag{
403 | Name: "config",
404 | Aliases: []string{"c"},
405 | Usage: "Path to config file",
406 | Destination: &configFile,
407 | Value: "./config.yaml",
408 | },
409 | },
410 | Action: func(ctx *cli.Context) error {
411 | var err error
412 | serverConfig, err = config.GetServerConfig(configFile)
413 | if err != nil {
414 | return fmt.Errorf("server config not found: %v", err)
415 | }
416 | log.Infof("server config: %v", serverConfig)
417 | return nil
418 | },
419 | }
420 |
421 | err := app.Run(os.Args)
422 | if err != nil {
423 | log.WithError(err).Fatal("server exited with error")
424 | }
425 |
426 | // At this point `serverConfig` is populated.
427 | // Create the VM server
428 | vmServer, err := server.NewServer(*serverConfig)
429 | if err != nil {
430 | log.Fatalf("failed to create VM server: %v", err)
431 | }
432 |
433 | // Create REST server
434 | s := &restServer{vmServer: vmServer}
435 | r := mux.NewRouter()
436 |
437 | // Register routes
438 | r.HandleFunc("/"+API_VERSION+"/vms", s.startVM).Methods("POST")
439 | r.HandleFunc("/"+API_VERSION+"/vms/{name}", s.updateVMState).Methods("PATCH")
440 | r.HandleFunc("/"+API_VERSION+"/vms/{name}", s.destroyVM).Methods("DELETE")
441 | r.HandleFunc("/"+API_VERSION+"/vms", s.destroyAllVMs).Methods("DELETE")
442 | r.HandleFunc("/"+API_VERSION+"/vms", s.listAllVMs).Methods("GET")
443 | r.HandleFunc("/"+API_VERSION+"/vms/{name}", s.listVM).Methods("GET")
444 | r.HandleFunc("/"+API_VERSION+"/vms/{name}/snapshots", s.snapshotVM).Methods("POST")
445 | r.HandleFunc("/"+API_VERSION+"/vms/{name}/cmd", s.vmCommand).Methods("POST")
446 | r.HandleFunc("/"+API_VERSION+"/vms/{name}/files", s.vmFileUpload).Methods("POST")
447 | r.HandleFunc("/"+API_VERSION+"/vms/{name}/files", s.vmFileDownload).Methods("GET")
448 | r.HandleFunc("/"+API_VERSION+"/health", s.healthCheck).Methods("GET")
449 |
450 | // Start HTTP server
451 | srv := &http.Server{
452 | Addr: serverConfig.Host + ":" + serverConfig.Port,
453 | Handler: r,
454 | }
455 |
456 | go func() {
457 | log.Printf("REST server listening on: %s:%s", serverConfig.Host, serverConfig.Port)
458 | if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
459 | log.Fatalf("Failed to start server: %v", err)
460 | }
461 | }()
462 |
463 | // Set up signal handling for graceful shutdown
464 | sigChan := make(chan os.Signal, 1)
465 | signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
466 | <-sigChan
467 |
468 | log.Println("Shutting down server...")
469 | if err := srv.Shutdown(context.Background()); err != nil {
470 | log.Fatalf("Server shutdown failed: %v", err)
471 | }
472 | vmServer.DestroyAllVMs(context.Background())
473 | log.Println("Server stopped")
474 | }
475 |
--------------------------------------------------------------------------------
/cmd/rootfsmaker/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "fmt"
5 | "os"
6 | "os/exec"
7 |
8 | log "github.com/sirupsen/logrus"
9 |
10 | "github.com/urfave/cli/v2"
11 | "gvisor.dev/gvisor/pkg/cleanup"
12 | )
13 |
14 | const (
15 | outputDir = "out"
16 | workingDir = outputDir + "/rootfsmaker-working-dir"
17 | dockerFile = "./resources/scripts/rootfs/Dockerfile"
18 | dockerImageName = "arrakis-lambda-img"
19 | dockerContainerName = "arrakis-lambda"
20 | rootfsTar = outputDir + "/rootfs.tar"
21 | rootfsDir = outputDir + "/rootfs"
22 | mountDir = outputDir + "/mnt"
23 | // We will be using `truncate` to create the image file, this won't really consume all the disk
24 | // space.
25 | diskSizeInMB = 4096
26 | )
27 |
28 | // runCmd runs `cmdName` with `args`.
29 | func runCmd(cmdName string, args ...string) error {
30 | cmd := exec.Command(cmdName, args...)
31 | cmd.Stdout = os.Stdout
32 | cmd.Stderr = os.Stderr
33 | return cmd.Run()
34 | }
35 |
36 | func createRootfsFromDockerfile(dockerFile string, outputFile string) (retErr error) {
37 | cleanup := cleanup.Make(func() {
38 | if retErr == nil {
39 | log.Info("create rootfs from docker file finished")
40 | }
41 | })
42 |
43 | defer func() {
44 | cleanup.Clean()
45 | }()
46 |
47 | log.Info("creating working dir")
48 | err := runCmd("mkdir", "-p", workingDir)
49 | if err != nil {
50 | return fmt.Errorf("failed to create working dir: %s: %w", workingDir, err)
51 | }
52 | cleanup.Add(func() {
53 | if err := runCmd("rm", "-rf", workingDir); err != nil {
54 | log.WithError(err).Errorf("failed to cleanup working dir: %s", workingDir)
55 | }
56 | })
57 |
58 | log.Info("copying dockerfile")
59 | srcDockerfile := dockerFile
60 | dstDockerfile := workingDir + "/Dockerfile"
61 | err = runCmd("cp", srcDockerfile, dstDockerfile)
62 | if err != nil {
63 | return fmt.Errorf(
64 | "failed to copy docker file: %s to: %s: %w",
65 | srcDockerfile,
66 | dstDockerfile,
67 | err,
68 | )
69 | }
70 | cleanup.Add(func() {
71 | if err := runCmd("rm", "-rf", dstDockerfile); err != nil {
72 | log.WithError(err).Errorf(
73 | "failed to cleanup docker file: %s",
74 | dstDockerfile,
75 | )
76 | }
77 | })
78 |
79 | log.Info("creating output folder")
80 | err = runCmd("mkdir", "-p", outputDir)
81 | if err != nil {
82 | return fmt.Errorf("failed to create output folder: %w", err)
83 | }
84 |
85 | log.Info("building docker image")
86 | err = runCmd("docker", "build", "-f", dstDockerfile, "-t", dockerImageName, ".")
87 | if err != nil {
88 | return fmt.Errorf("failed to build docker container image: %w", err)
89 | }
90 | cleanup.Add(func() {
91 | if err := runCmd("docker", "rmi", dockerImageName); err != nil {
92 | log.WithError(err).Errorf("failed to cleanup docker image: %s", dockerImageName)
93 | }
94 | })
95 |
96 | // Needed in case the container wasn't cleaned up from previous runs.
97 | log.Info("removing stale container")
98 | err = runCmd("docker", "rm", "-f", dockerContainerName)
99 | if err != nil {
100 | log.WithError(err).Errorf("failed to remove stale container: %s", dockerContainerName)
101 | }
102 |
103 | log.Info("creating container")
104 | err = runCmd("docker", "create", "--name", dockerContainerName, dockerImageName)
105 | if err != nil {
106 | return fmt.Errorf("failed to build docker container: %w", err)
107 | }
108 | cleanup.Add(func() {
109 | if err := runCmd("docker", "rm", dockerContainerName); err != nil {
110 | log.WithError(err).Errorf(
111 | "failed to cleanup docker container: %s",
112 | dockerContainerName,
113 | )
114 | }
115 | })
116 |
117 | log.Info("exporting rootfs to tar file")
118 | err = runCmd("docker", "export", "--output", rootfsTar, dockerContainerName)
119 | if err != nil {
120 | return fmt.Errorf("failed to export docker container: %w", err)
121 | }
122 |
123 | log.Info("creating img file")
124 | err = runCmd(
125 | "dd",
126 | "if=/dev/zero",
127 | "of="+outputFile,
128 | "bs=1M",
129 | "count="+fmt.Sprintf("%d", diskSizeInMB),
130 | )
131 | if err != nil {
132 | return fmt.Errorf("failed to create img file: %w", err)
133 | }
134 |
135 | log.Info("formatting img file to ext4")
136 | err = runCmd("mkfs.ext4", outputFile)
137 | if err != nil {
138 | return fmt.Errorf("failed to format ext4 image: %w", err)
139 | }
140 |
141 | log.Info("creating loopback mount directory")
142 | err = runCmd("mkdir", "-p", mountDir)
143 | if err != nil {
144 | return fmt.Errorf("failed to create loopback mount dir: %w", err)
145 | }
146 | cleanup.Add(func() {
147 | if err := runCmd("rm", "-rf", mountDir); err != nil {
148 | log.WithError(err).Errorf("failed to cleanup mount dir: %s", mountDir)
149 | }
150 | })
151 |
152 | log.Info("mounting loopback mount")
153 | err = runCmd("mount", "-o", "loop", outputFile, mountDir)
154 | if err != nil {
155 | return fmt.Errorf("failed to mount ext4 image: %w", err)
156 | }
157 | cleanup.Add(func() {
158 | if err := runCmd("umount", mountDir); err != nil {
159 | log.WithError(err).Errorf("failed to umount dir: %s", mountDir)
160 | // Only process to `resize2fs` if umount succeeded.
161 | return
162 | }
163 | })
164 |
165 | log.Info("extracting rootfs tar to mount dir")
166 | err = runCmd("tar", "-xvf", rootfsTar, "-C", mountDir)
167 | if err != nil {
168 | return fmt.Errorf("failed to extract rootfs tar to mount dir: %w", err)
169 | }
170 | cleanup.Add(func() {
171 | if err := runCmd("rm", "-rf", rootfsTar); err != nil {
172 | log.WithError(err).Errorf("failed to delete rootfs tar: %s", rootfsTar)
173 | }
174 | })
175 |
176 | return nil
177 | }
178 |
179 | func main() {
180 | log.Info("making guest rootfs")
181 |
182 | app := &cli.App{
183 | Name: "rootfsmaker",
184 | Usage: "A script to make a guest rootfs for a VM",
185 | Commands: []*cli.Command{
186 | {
187 | Name: "create",
188 | Usage: "Create guest rootfs from docker file",
189 | Flags: []cli.Flag{
190 | &cli.StringFlag{
191 | Name: "dockerfile",
192 | Aliases: []string{"d"},
193 | Usage: "Path to the docker file",
194 | Required: true,
195 | },
196 | &cli.StringFlag{
197 | Name: "output",
198 | Aliases: []string{"o"},
199 | Usage: "Path to the output rootfs file",
200 | Required: true,
201 | },
202 | },
203 | Action: func(ctx *cli.Context) error {
204 | return createRootfsFromDockerfile(ctx.String("dockerfile"), ctx.String("output"))
205 | },
206 | },
207 | },
208 | }
209 |
210 | err := app.Run(os.Args)
211 | if err != nil {
212 | log.WithError(err).Fatal("failed to create rootfs")
213 | }
214 | }
215 |
--------------------------------------------------------------------------------
/cmd/vsockclient/cmdclient/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bytes"
5 | "context"
6 | "encoding/json"
7 | "fmt"
8 | "io"
9 | "net"
10 | "net/http"
11 | "os"
12 | "strings"
13 |
14 | log "github.com/sirupsen/logrus"
15 | "github.com/urfave/cli/v2"
16 | )
17 |
18 | type runCmdRequest struct {
19 | Cmd string `json:"cmd"`
20 | }
21 |
22 | type runCmdResponse struct {
23 | Output string `json:"output,omitempty"`
24 | Error string `json:"error,omitempty"`
25 | }
26 |
27 | func unixSocketHTTPClient(socketPath string) *http.Client {
28 | return &http.Client{
29 | Transport: &http.Transport{
30 | DialContext: func(ctx context.Context, network, addr string) (net.Conn, error) {
31 | log.Infof("Attempting to dial unix socket at %s", socketPath)
32 | return net.Dial("unix", socketPath)
33 | },
34 | },
35 | }
36 | }
37 |
38 | func runCommand(client *http.Client, cmd string) error {
39 | // Prepare the request
40 | reqBody := runCmdRequest{
41 | Cmd: cmd,
42 | }
43 | jsonBody, err := json.Marshal(reqBody)
44 | if err != nil {
45 | return fmt.Errorf("failed to marshal request: %v", err)
46 | }
47 |
48 | // Create HTTP request
49 | req, err := http.NewRequest(http.MethodPost, "http://localhost/cmd", bytes.NewBuffer(jsonBody))
50 | if err != nil {
51 | return fmt.Errorf("failed to create request: %v", err)
52 | }
53 | req.Header.Set("Content-Type", "application/json")
54 |
55 | // Send request
56 | resp, err := client.Do(req)
57 | if err != nil {
58 | return fmt.Errorf("failed to send request: %v", err)
59 | }
60 | defer resp.Body.Close()
61 |
62 | // Read response
63 | body, err := io.ReadAll(resp.Body)
64 | if err != nil {
65 | return fmt.Errorf("failed to read response: %v", err)
66 | }
67 |
68 | if resp.StatusCode != http.StatusOK {
69 | return fmt.Errorf("server returned error: %s", string(body))
70 | }
71 |
72 | // Parse response
73 | var cmdResp runCmdResponse
74 | if err := json.Unmarshal(body, &cmdResp); err != nil {
75 | return fmt.Errorf("failed to parse response: %v", err)
76 | }
77 |
78 | // Handle response
79 | if cmdResp.Error != "" {
80 | return fmt.Errorf("command failed: %s\nOutput: %s", cmdResp.Error, cmdResp.Output)
81 | }
82 |
83 | fmt.Print(cmdResp.Output)
84 | return nil
85 | }
86 |
87 | func main() {
88 | app := &cli.App{
89 | Name: "cmdclient",
90 | Usage: "Send commands to a VM's cmdserver via Unix domain socket",
91 | Flags: []cli.Flag{
92 | &cli.StringFlag{
93 | Name: "uds",
94 | Usage: "Path to the Unix domain socket (AF_UNIX) to connect to",
95 | Required: true,
96 | },
97 | },
98 | Action: func(c *cli.Context) error {
99 | udsPath := c.String("uds")
100 | if c.NArg() == 0 {
101 | return fmt.Errorf("command argument required")
102 | }
103 |
104 | client := unixSocketHTTPClient(udsPath)
105 |
106 | cmd := strings.Join(c.Args().Slice(), " ")
107 | if err := runCommand(client, cmd); err != nil {
108 | log.Fatal(err)
109 | }
110 |
111 | return nil
112 | },
113 | }
114 |
115 | if err := app.Run(os.Args); err != nil {
116 | log.Fatal(err)
117 | }
118 | }
119 |
--------------------------------------------------------------------------------
/cmd/vsockclient/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "io"
7 | "net"
8 | "os"
9 | "path"
10 | "strings"
11 |
12 | log "github.com/sirupsen/logrus"
13 | "github.com/urfave/cli/v2"
14 | )
15 |
16 | const (
17 | defaultPort = 4032
18 | stateDir = "./vm-state"
19 | vsockFileName = "vsock.sock"
20 | )
21 |
22 | func getVsockPath(vmName string) string {
23 | return path.Join(stateDir, vmName, vsockFileName)
24 | }
25 |
26 | func startInteractiveSession(socketPath string, port int) error {
27 | // Connect to Unix domain socket
28 | conn, err := net.Dial("unix", socketPath)
29 | if err != nil {
30 | return fmt.Errorf("failed to connect to socket %s: %v", socketPath, err)
31 | }
32 | defer conn.Close()
33 |
34 | // Send CONNECT command
35 | connectCmd := fmt.Sprintf("CONNECT %d\n", port)
36 | _, err = conn.Write([]byte(connectCmd))
37 | if err != nil {
38 | return fmt.Errorf("failed to send CONNECT command: %v", err)
39 | }
40 |
41 | // Read response to CONNECT
42 | reader := bufio.NewReader(conn)
43 | response, err := reader.ReadString('\n')
44 | if err != nil {
45 | return fmt.Errorf("failed to read CONNECT response: %v", err)
46 | }
47 |
48 | response = strings.TrimSpace(response)
49 | if !strings.HasPrefix(response, "OK") {
50 | return fmt.Errorf("unexpected response to CONNECT: %s", response)
51 | }
52 |
53 | // Start interactive session
54 | fmt.Println("Connected to vsock server. Enter commands (Ctrl+C to exit):")
55 |
56 | // Create a channel to handle server responses
57 | done := make(chan struct{})
58 | go func() {
59 | defer close(done)
60 | for {
61 | line, err := reader.ReadString('\n')
62 | if err != nil {
63 | if err != io.EOF {
64 | log.Errorf("Error reading from server: %v", err)
65 | }
66 | return
67 | }
68 | fmt.Print(line)
69 | }
70 | }()
71 |
72 | // Read commands from stdin and send to server
73 | stdinReader := bufio.NewReader(os.Stdin)
74 | for {
75 | cmd, err := stdinReader.ReadString('\n')
76 | if err != nil {
77 | if err == io.EOF {
78 | break
79 | }
80 | return fmt.Errorf("error reading from stdin: %v", err)
81 | }
82 |
83 | _, err = conn.Write([]byte(cmd))
84 | if err != nil {
85 | return fmt.Errorf("error sending command: %v", err)
86 | }
87 | }
88 |
89 | return nil
90 | }
91 |
92 | func main() {
93 | app := &cli.App{
94 | Name: "vsockclient",
95 | Usage: "Interactive client for VM's vsockserver via Unix domain socket",
96 | Flags: []cli.Flag{
97 | &cli.StringFlag{
98 | Name: "vm",
99 | Aliases: []string{"v"},
100 | Usage: "Name of the VM to connect to",
101 | Required: true,
102 | },
103 | &cli.IntFlag{
104 | Name: "port",
105 | Aliases: []string{"p"},
106 | Usage: "Port number to connect to",
107 | Value: defaultPort,
108 | },
109 | },
110 | Action: func(c *cli.Context) error {
111 | vmName := c.String("vm")
112 | port := c.Int("port")
113 |
114 | socketPath := getVsockPath(vmName)
115 | if _, err := os.Stat(socketPath); os.IsNotExist(err) {
116 | return fmt.Errorf("vsock socket not found for VM %s at %s", vmName, socketPath)
117 | }
118 |
119 | log.WithFields(log.Fields{
120 | "vm": vmName,
121 | "port": port,
122 | "socket": socketPath,
123 | }).Info("Starting interactive session")
124 |
125 | return startInteractiveSession(socketPath, port)
126 | },
127 | }
128 |
129 | if err := app.Run(os.Args); err != nil {
130 | log.Fatal(err)
131 | }
132 | }
133 |
--------------------------------------------------------------------------------
/cmd/vsockserver/main.go:
--------------------------------------------------------------------------------
1 | package main
2 |
3 | import (
4 | "bufio"
5 | "fmt"
6 | "io"
7 | "os"
8 | "os/exec"
9 | "strings"
10 |
11 | "github.com/coreos/go-systemd/daemon"
12 | "github.com/mdlayher/vsock"
13 | log "github.com/sirupsen/logrus"
14 | )
15 |
16 | const (
17 | // Define a base directory to prevent path traversal.
18 | baseDir = "/tmp/vsockserver"
19 | port = 4032
20 | )
21 |
22 | func handleConnection(conn *vsock.Conn) {
23 | defer conn.Close()
24 |
25 | reader := bufio.NewReader(conn)
26 |
27 | for {
28 | // Read command from the connection
29 | cmd, err := reader.ReadString('\n')
30 | if err != nil {
31 | if err != io.EOF {
32 | log.Errorf("Error reading from connection: %v", err)
33 | }
34 | return
35 | }
36 |
37 | // Trim whitespace and newline
38 | cmd = strings.TrimSpace(cmd)
39 |
40 | if cmd == "" {
41 | continue
42 | }
43 |
44 | // Set up environment variables with a restricted PATH for security
45 | // This limits command execution to only system binaries in standard locations:
46 | // - /usr/local/bin: For locally compiled/installed programs
47 | // - /usr/bin: For distribution-packaged programs
48 | // - /bin: For essential system binaries
49 | // Prevents execution of programs from unsafe locations like current directory,
50 | // home directories, or other non-standard paths that could contain malicious code
51 | env := os.Environ()
52 | customPath := "/usr/local/bin:/usr/bin:/bin"
53 | env = append(env, "PATH="+customPath)
54 |
55 | // Create and configure the command
56 | command := exec.Command("/bin/bash", "-c", cmd)
57 | command.Env = env
58 | command.Dir = baseDir
59 |
60 | // Log the command execution
61 | log.WithFields(log.Fields{
62 | "cmd": cmd,
63 | "workingDir": command.Dir,
64 | }).Info("Executing command")
65 |
66 | // Execute the command and capture output
67 | output, err := command.CombinedOutput()
68 | if err != nil {
69 | errMsg := fmt.Sprintf("Error: %v\nOutput: %s\n", err, string(output))
70 | log.WithFields(log.Fields{
71 | "cmd": cmd,
72 | "error": err,
73 | "output": string(output),
74 | }).Error("Command execution failed")
75 | conn.Write([]byte(errMsg))
76 | continue
77 | }
78 |
79 | // Log successful execution
80 | log.WithFields(log.Fields{
81 | "cmd": cmd,
82 | "output": string(output),
83 | }).Info("Command executed successfully")
84 |
85 | // Write the output back to the connection
86 | _, err = conn.Write(append(output, '\n'))
87 | if err != nil {
88 | log.Errorf("Error writing response: %v", err)
89 | return
90 | }
91 | }
92 | }
93 |
94 | func main() {
95 | if err := os.MkdirAll(baseDir, 0755); err != nil {
96 | log.Fatalf("Failed to create base directory: %v", err)
97 | }
98 |
99 | listener, err := vsock.Listen(uint32(port), &vsock.Config{})
100 | if err != nil {
101 | log.Fatalf("Failed to create vsock listener: %v", err)
102 | }
103 | defer listener.Close()
104 |
105 | log.Printf("VSock server listening on port %d...", port)
106 | // Make other services start via systemd since we're ready to debug.
107 | if _, err := daemon.SdNotify(false, daemon.SdNotifyReady); err != nil {
108 | log.Warnf("Failed to notify systemd of readiness: %v", err)
109 | }
110 |
111 | for {
112 | conn, err := listener.Accept()
113 | if err != nil {
114 | log.Errorf("Failed to accept connection: %v", err)
115 | continue
116 | }
117 |
118 | // Handle each connection in a goroutine
119 | go handleConnection(conn.(*vsock.Conn))
120 | }
121 | }
122 |
--------------------------------------------------------------------------------
/config.yaml:
--------------------------------------------------------------------------------
1 | hostservices:
2 | restserver:
3 | host: "0.0.0.0"
4 | port: "7000"
5 | state_dir: "./vm-state"
6 | bridge_name: "br0"
7 | bridge_ip: "10.20.1.1/24"
8 | bridge_subnet: "10.20.1.0/24"
9 | chv_bin: "./resources/bin/cloud-hypervisor"
10 | kernel: "./resources/bin/vmlinux.bin"
11 | rootfs: "./out/arrakis-guestrootfs-ext4.img"
12 | initramfs: "./out/initramfs.cpio.gz"
13 | port_forwards:
14 | - port: "5901"
15 | description: "gui"
16 | - port: "5736-5740"
17 | description: "code"
18 | stateful_size_in_mb: "2048"
19 | guest_mem_percentage: "30"
20 | client:
21 | server_host: "127.0.0.1"
22 | server_port: "7000"
23 | guestservices:
24 | codeserver:
25 | port: "4030"
26 | cmdserver:
27 | port: "4031"
28 |
--------------------------------------------------------------------------------
/docs/detailed-README.md:
--------------------------------------------------------------------------------
1 | ## Table of Contents
2 |
3 | - [Build from source](#build-from-source)
4 | - [Build](#build)
5 | - [Build a custom rootfs for the guest](#build-a-custom-rootfs-for-the-guest)
6 | - [Configuration](#configuration)
7 | - [Usage](#usage)
8 |
9 | ---
10 |
11 | ## Build from source
12 |
13 | - Clone the repository
14 | ```bash
15 | git clone https://github.com/abshkbh/arrakis.git
16 | cd arrakis
17 | ```
18 |
19 | - Install Golang dependencies
20 | ```bash
21 | go mod tidy
22 | ```
23 |
24 | - Install deps to build the project
25 | ```bash
26 |
27 |
28 | - The easiest way to install prerequisite images is to use the `install-images.py` script.
29 | ```bash
30 | ./setup/install-images.py
31 | ```
32 |
33 | - The following images are installed by the script above and can also be installed manually -
34 |
35 | - Install the [cloud-hypervisor](https://github.com/cloud-hypervisor/cloud-hypervisor) binary and note down the path of the binary. This will be used in the [Configuration](#configuration) section. By default we look for this binary at `resources/bin/cloud-hypervisor`, you may place it there.
36 |
37 | - Download the prebuilt guest kernel for the VM from [arrakis-images](https://github.com/abshkbh/arrakis-images/blob/main/guest/kernel/vmlinux.bin), note down the path. This will be used in the [Configuration](#configuration) section. By default we look for this binary at `resources/bin/vmlinux.bin`, you may place it there.
38 |
39 | ---
40 |
41 | ## Build
42 |
43 | - Make everything. You"ll be prompted by `sudo` once while making the guest rootfs.
44 | ```bash
45 | make all
46 | ```
47 | All binaries will be placed in `./out`.
48 |
49 | - The following binaries are built -
50 | - **arrakis-restserver** - A daemon exposing a REST API to create, manage and interact with cloud-hypervisor based MicroVMs.
51 | - **arrakis-client** - A CLI client to communicate with **arrakis-restserver**.
52 | - **arrakis-cmdserver** - A daemon to execute shell commands that can be put inside the guest using the [Dockerfile](./resources/scripts/rootfs/Dockerfile) and **arrakis-rootfsmaker**.
53 | - **arrakis-codeserver** - A daemon to run **python** or **typescript** node that can be put inside the guest using the `Dockerfile` and **arrakis-rootfsmaker**.
54 | - **arrakis-guestinit** - The init running inside the MicroVM guest.
55 | - **arrakis-guestrootfs-ext4.img** - The rootfs used for the MicroVM guest.
56 | - **arrakis-rootfsmaker** - The program used to convert the [Dockerfile](./resources/scripts/rootfs/Dockerfile) into the guest rootfs (**arrakis-guestrootfs-ext4.img**).
57 | - `gen` - Contains the generated code for both the [cloud-hypervisor API](./api/arrakis-api.yaml) (used by **arrakis-restserver**) and [REST server API](./api/server-api.yaml) (used by **arrakis-client**).
58 |
59 | - Clean all binaries.
60 | ```bash
61 | make clean
62 | ```
63 |
64 | ---
65 |
66 | ## Build a custom rootfs for the guest
67 |
68 | - The rootfs for guests can be configured using the provided [Dockerfile](./resources/scripts/rootfs/Dockerfile).
69 |
70 | - An example of how custom binaries can be added to the rootfs can be found [here](./resources/scripts/rootfs/Dockerfile#L66).
71 | - By default we keep custom binaries at `/opt/custom_scripts/` within the guest.
72 |
73 | - Command to make the guest rootfs -
74 | ```bash
75 | make guestrootfs
76 | ```
77 |
78 | ---
79 |
80 | ## Configuration
81 |
82 | - A [config.yaml](./config.yaml) file is used to configure all the services provided by this project. It has defaults but could be modified.
83 |
84 | - Configuring services on the host -
85 | - Host services are configured under the `hostservices` section.
86 |
87 | - Configuring **arrakis-restserver** -
88 | - The `hostservices` -> `restserver` sub-section is used.
89 | - **state_dir** - Where each MicroVM's runtime state is stored.
90 | - **chv_bin** - The path to the **cloud-hypervisor** binary on the host.
91 | - **kernel** - The path to the kernel to be used for all MicroVMs.
92 | - **rootfs** - The path to the rootfs to be used for all MicroVMs. Set to **./out/arrakis-guestrootfs-ext4.img** by default.
93 |
94 | - Configuring **arrakis-client** -
95 | - The `hostservices` -> `client` sub-section is used.
96 | - **server_host** - The IP at which the **arrakis-restserver** running.
97 | - **server_port** - The port at which the **arrakis-restserver** is running.
98 |
99 | - Configuring services inside the guest -
100 | - Guest services are configured under the `guestservices` section.
101 | - The sample config file has an example for an optional **codeserver** inside the guest.
102 |
103 | ---
104 |
105 | ## Usage
106 |
107 | - Before anything we need our `arrakis-restserver` to start. Start it with -
108 | ```bash
109 | sudo ./out/arrakis-restserver
110 | ```
111 | - Root access is only needed to configure **iptables** for guest networking. Removing the root dependency is being currently worked on.
112 |
113 | - In a separate shell we will use the CLI client to create and manage VMs.
114 |
115 | - Start a VM named `foo`. It returns metadata about the VM which could be used to interacting with the VM.
116 | ```bash
117 | ./out/arrakis-client start -n foo
118 | ```
119 |
120 | ```bash
121 | started VM: {"codeServerPort":"","ip":"10.20.1.2/24","status":"RUNNING","tapDeviceName":"tap-foo","vmName":"foo"}
122 | ```
123 |
124 | - SSH into the VM.
125 | - ssh credentials are configured [here](./resources/scripts/rootfs/Dockerfile#L6).
126 | ```bash
127 | # Use the IP returned. Password is "elara0000"
128 | ssh elara@10.20.1.2
129 | ```
130 |
131 | - Inspecting a VM named `foo`.
132 | ```bash
133 | ./out/arrakis-client list -n foo
134 | ```
135 |
136 | ```bash
137 | VM: {"ip":"10.20.1.2/24","status":"RUNNING","tapDeviceName":"tap-foo","vmName":"foo"}
138 | ```
139 |
140 | - List all the VMs.
141 | ```bash
142 | ./out/arrakis-client list-all
143 | ```
144 |
145 | ```bash
146 | VMs: {"vms":[{"ip":"10.20.1.2/24","status":"RUNNING","tapDeviceName":"tap-foo","vmName":"foo"}]}
147 | ```
148 |
149 | - Stop the VM.
150 | ```bash
151 | ./out/arrakis-client stop -n foo
152 | ```
153 |
154 | - Destroy the VM.
155 | ```bash
156 | ./out/arrakis-client destroy -n foo
157 | ```
158 |
159 | - Snapshotting and Restoring the VM.
160 | - We support snapshotting the VM and then using the snapshot to restore the VM. Currently, we restore the VM to use the same IP as the original VM. If you plan to restore the VM on the same host then either stop or destroy the original VM before restoring. In the future this won't be a constraint.
161 | ```bash
162 | ./out/arrakis-client snapshot -n foo-original -o foo-snapshot
163 | ```
164 |
165 | ```bash
166 | ./out/arrakis-client destroy -n foo-original -o foo-snapshot
167 | ```
168 |
169 | ```bash
170 | ./out/arrakis-client restore -n foo-original --snapshot foo-snapshot
171 | ```
172 |
173 | ---
174 |
175 | ## Ongoing Work
176 |
177 | - Reduce sandbox startup time to less than 500 ms.
178 |
179 | - Making existing coding agents work with Arrakis.
180 |
181 | ---
182 |
183 | ## Contribution
184 |
185 | Thank you for considering contributing to **arrakis**! 🎉
186 |
187 | Feel free to open a PR. A detailed contribution guide is going to be available soon.
188 |
189 | ## Legal Info
190 |
191 | ### Contributor License Agreement
192 |
193 | In order for us to accept patches and other contributions from you, you need to adopt our Arrakis Contributor License Agreement (the "**CLA**"). Please drop a line at abshkbh@gmail.com to start this process.
194 |
195 | Arrakis uses a tool called CLA Assistant to help us keep track of the CLA status of contributors. CLA Assistant will post a comment to your pull request indicating whether you have signed the CLA or not. If you have not signed the CLA, you will need to do so before we can accept your contribution. Signing the CLA would be one-time process, is valid for all future contributions to Arrakis, and can be done in under a minute by signing in with your GitHub account.
196 |
197 |
198 | ### License
199 |
200 | By contributing to Arrakis, you agree that your contributions will be licensed under the [GNU Affero General Public License v3.0](LICENSE) and as commercial software.
201 |
202 | ---
203 |
204 | ## License
205 |
206 | This project is licensed under the [GNU Affero General Public License v3.0](./LICENSE). For commercial licensing, please drop a line at abshkbh@gmail.com.
207 |
208 | ---
209 |
--------------------------------------------------------------------------------
/docs/images/arrakis-gui.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abshkbh/arrakis/877231496acbf3b3091ab33340d2d126a251c4d5/docs/images/arrakis-gui.png
--------------------------------------------------------------------------------
/docs/images/arrakis-logo.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abshkbh/arrakis/877231496acbf3b3091ab33340d2d126a251c4d5/docs/images/arrakis-logo.png
--------------------------------------------------------------------------------
/docs/images/high-level-architecture-arrakis.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/abshkbh/arrakis/877231496acbf3b3091ab33340d2d126a251c4d5/docs/images/high-level-architecture-arrakis.png
--------------------------------------------------------------------------------
/go.mod:
--------------------------------------------------------------------------------
1 | module github.com/abshkbh/arrakis
2 |
3 | go 1.23.1
4 |
5 | toolchain go1.23.2
6 |
7 | require (
8 | github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf
9 | github.com/mattn/go-shellwords v1.0.12
10 | github.com/mdlayher/vsock v1.2.1
11 | github.com/sirupsen/logrus v1.9.3
12 | github.com/spf13/viper v1.19.0
13 | github.com/urfave/cli/v2 v2.27.3
14 | google.golang.org/grpc v1.65.0
15 | )
16 |
17 | require (
18 | github.com/fsnotify/fsnotify v1.7.0 // indirect
19 | github.com/hashicorp/hcl v1.0.0 // indirect
20 | github.com/magiconair/properties v1.8.7 // indirect
21 | github.com/mdlayher/socket v0.4.1 // indirect
22 | github.com/mitchellh/mapstructure v1.5.0 // indirect
23 | github.com/pelletier/go-toml/v2 v2.2.2 // indirect
24 | github.com/sagikazarmark/locafero v0.4.0 // indirect
25 | github.com/sagikazarmark/slog-shim v0.1.0 // indirect
26 | github.com/sourcegraph/conc v0.3.0 // indirect
27 | github.com/spf13/afero v1.11.0 // indirect
28 | github.com/spf13/cast v1.6.0 // indirect
29 | github.com/spf13/pflag v1.0.5 // indirect
30 | github.com/stretchr/testify v1.10.0 // indirect
31 | github.com/subosito/gotenv v1.6.0 // indirect
32 | go.uber.org/atomic v1.9.0 // indirect
33 | go.uber.org/multierr v1.9.0 // indirect
34 | golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
35 | golang.org/x/sync v0.10.0 // indirect
36 | golang.org/x/text v0.21.0 // indirect
37 | google.golang.org/protobuf v1.34.1 // indirect
38 | gopkg.in/ini.v1 v1.67.0 // indirect
39 | gopkg.in/yaml.v3 v3.0.1 // indirect
40 | )
41 |
42 | require (
43 | github.com/cpuguy83/go-md2man/v2 v2.0.4 // indirect
44 | github.com/gorilla/mux v1.8.1
45 | github.com/russross/blackfriday/v2 v2.1.0 // indirect
46 | github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 // indirect
47 | golang.org/x/net v0.32.0 // indirect
48 | golang.org/x/sys v0.28.0 // indirect
49 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 // indirect
50 | gvisor.dev/gvisor v0.0.0-20241025194355-0b2cae1b4ea8
51 | )
52 |
--------------------------------------------------------------------------------
/go.sum:
--------------------------------------------------------------------------------
1 | github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf h1:iW4rZ826su+pqaw19uhpSCzhj44qo35pNgKFGqzDKkU=
2 | github.com/coreos/go-systemd v0.0.0-20191104093116-d3cd4ed1dbcf/go.mod h1:F5haX7vjVVG0kc13fIWeqUViNPyEJxv/OmvnBo0Yme4=
3 | github.com/cpuguy83/go-md2man/v2 v2.0.4 h1:wfIWP927BUkWJb2NmU/kNDYIBTh/ziUX91+lVfRxZq4=
4 | github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
5 | github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
6 | github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
7 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
8 | github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
9 | github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
10 | github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
11 | github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
12 | github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
13 | github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
14 | github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
15 | github.com/gorilla/mux v1.8.1 h1:TuBL49tXwgrFYWhqrNgrUNEY92u81SPhu7sTdzQEiWY=
16 | github.com/gorilla/mux v1.8.1/go.mod h1:AKf9I4AEqPTmMytcMc0KkNouC66V3BtZ4qD5fmWSiMQ=
17 | github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
18 | github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
19 | github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
20 | github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
21 | github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
22 | github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
23 | github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
24 | github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
25 | github.com/mattn/go-shellwords v1.0.12 h1:M2zGm7EW6UQJvDeQxo4T51eKPurbeFbe8WtebGE2xrk=
26 | github.com/mattn/go-shellwords v1.0.12/go.mod h1:EZzvwXDESEeg03EKmM+RmDnNOPKG4lLtQsUlTZDWQ8Y=
27 | github.com/mdlayher/socket v0.4.1 h1:eM9y2/jlbs1M615oshPQOHZzj6R6wMT7bX5NPiQvn2U=
28 | github.com/mdlayher/socket v0.4.1/go.mod h1:cAqeGjoufqdxWkD7DkpyS+wcefOtmu5OQ8KuoJGIReA=
29 | github.com/mdlayher/vsock v1.2.1 h1:pC1mTJTvjo1r9n9fbm7S1j04rCgCzhCOS5DY0zqHlnQ=
30 | github.com/mdlayher/vsock v1.2.1/go.mod h1:NRfCibel++DgeMD8z/hP+PPTjlNJsdPOmxcnENvE+SE=
31 | github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
32 | github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
33 | github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
34 | github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
35 | github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
36 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
37 | github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
38 | github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
39 | github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
40 | github.com/russross/blackfriday/v2 v2.1.0 h1:JIOH55/0cWyOuilr9/qlrm0BSXldqnqwMsf35Ld67mk=
41 | github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
42 | github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
43 | github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
44 | github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
45 | github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
46 | github.com/sirupsen/logrus v1.9.3 h1:dueUQJ1C2q9oE3F7wvmSGAaVtTmUizReu6fjN8uqzbQ=
47 | github.com/sirupsen/logrus v1.9.3/go.mod h1:naHLuLoDiP4jHNo9R0sCBMtWGeIprob74mVsIT4qYEQ=
48 | github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
49 | github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
50 | github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
51 | github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
52 | github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
53 | github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
54 | github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
55 | github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
56 | github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
57 | github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
58 | github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
59 | github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
60 | github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
61 | github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
62 | github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
63 | github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
64 | github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
65 | github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
66 | github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
67 | github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
68 | github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA=
69 | github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
70 | github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
71 | github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
72 | github.com/urfave/cli/v2 v2.27.3 h1:/POWahRmdh7uztQ3CYnaDddk0Rm90PyOgIxgW2rr41M=
73 | github.com/urfave/cli/v2 v2.27.3/go.mod h1:m4QzxcD2qpra4z7WhzEGn74WZLViBnMpb1ToCAKdGRQ=
74 | github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1 h1:gEOO8jv9F4OT7lGCjxCBTO/36wtF6j2nSip77qHd4x4=
75 | github.com/xrash/smetrics v0.0.0-20240521201337-686a1a2994c1/go.mod h1:Ohn+xnUBiLI6FVj/9LpzZWtj1/D6lUovWYBkxHVV3aM=
76 | go.uber.org/atomic v1.9.0 h1:ECmE8Bn/WFTYwEW/bpKD3M8VtR/zQVbavAoalC1PYyE=
77 | go.uber.org/atomic v1.9.0/go.mod h1:fEN4uk6kAWBTFdckzkM89CLk9XfWZrxpCo0nPH17wJc=
78 | go.uber.org/multierr v1.9.0 h1:7fIwc/ZtS0q++VgcfqFDxSBZVv/Xo49/SYnDFupUwlI=
79 | go.uber.org/multierr v1.9.0/go.mod h1:X2jQV1h+kxSjClGpnseKVIxpmcjrj7MNnI0bnlfKTVQ=
80 | golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
81 | golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
82 | golang.org/x/net v0.32.0 h1:ZqPmj8Kzc+Y6e0+skZsuACbx+wzMgo5MQsJh9Qd6aYI=
83 | golang.org/x/net v0.32.0/go.mod h1:CwU0IoeOlnQQWJ6ioyFrfRuomB8GKF6KbYXZVyeXNfs=
84 | golang.org/x/sync v0.10.0 h1:3NQrjDixjgGwUOCaF8w2+VYHv0Ve/vGYSbdkTa98gmQ=
85 | golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
86 | golang.org/x/sys v0.0.0-20220715151400-c0bba94af5f8/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
87 | golang.org/x/sys v0.28.0 h1:Fksou7UEQUWlKvIdsqzJmUmCX3cZuD2+P3XyyzwMhlA=
88 | golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
89 | golang.org/x/text v0.21.0 h1:zyQAAkrwaneQ066sspRyJaG9VNi/YJ1NfzcGB3hZ/qo=
90 | golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
91 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157 h1:Zy9XzmMEflZ/MAaA7vNcoebnRAld7FsPW1EeBB7V0m8=
92 | google.golang.org/genproto/googleapis/rpc v0.0.0-20240528184218-531527333157/go.mod h1:EfXuqaE1J41VCDicxHzUDm+8rk+7ZdXzHV0IhO/I6s0=
93 | google.golang.org/grpc v1.65.0 h1:bs/cUb4lp1G5iImFFd3u5ixQzweKizoZJAwBNLR42lc=
94 | google.golang.org/grpc v1.65.0/go.mod h1:WgYC2ypjlB0EiQi6wdKixMqukr6lBc0Vo+oOgjrM5ZQ=
95 | google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
96 | google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
97 | gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
98 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
99 | gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
100 | gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
101 | gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
102 | gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
103 | gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
104 | gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
105 | gvisor.dev/gvisor v0.0.0-20241025194355-0b2cae1b4ea8 h1:B9P+8uZALygqYM6va7uUlA4/dvn1bQoe94poPSR1kEs=
106 | gvisor.dev/gvisor v0.0.0-20241025194355-0b2cae1b4ea8/go.mod h1:5DMfjtclAbTIjbXqO1qCe2K5GKKxWz2JHvCChuTcJEM=
107 |
--------------------------------------------------------------------------------
/initramfs/create-initramfs.sh:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 | INITRAMFS_SRC_DIR="initramfs"
3 | INITRAMFS_WORK_DIR="/tmp/initramfs"
4 | OUT_FILE="out/initramfs.cpio.gz"
5 |
6 | # Create directories
7 | for dir in bin dev etc home mnt proc sys usr; do
8 | mkdir -p ${INITRAMFS_WORK_DIR}/$dir
9 | done
10 |
11 | cp resources/bin/busybox ${INITRAMFS_WORK_DIR}/bin/busybox
12 | cp ${INITRAMFS_SRC_DIR}/init.sh ${INITRAMFS_WORK_DIR}/init
13 | chmod +x ${INITRAMFS_WORK_DIR}/init
14 |
15 | # Create initramfs image
16 | pushd ${INITRAMFS_WORK_DIR} > /dev/null
17 | find . -print0 | cpio --null -o --format=newc > /tmp/initramfs.cpio
18 | gzip -f /tmp/initramfs.cpio > /tmp/initramfs.cpio.gz
19 | rm -rf /tmp/initramfs.cpio
20 | popd > /dev/null
21 |
22 | mv /tmp/initramfs.cpio.gz ${OUT_FILE}
23 | rm -rf /tmp/initramfs.cpio.gz
24 | rm -rf ${INITRAMFS_WORK_DIR}
25 |
--------------------------------------------------------------------------------
/initramfs/init.sh:
--------------------------------------------------------------------------------
1 | #!/bin/busybox sh
2 | echo "In initramfs"
3 |
4 | LOWER_RO_DEVICE=/dev/vda
5 | WRITABLE_RW_DEVICE=/dev/vdb
6 |
7 | LOWER_RO=/mnt/ro
8 | WRITABLE_RW=/mnt/rw
9 | UPPER=${WRITABLE_RW}/upper
10 | WORK=${WRITABLE_RW}/work
11 |
12 | NEWROOT=${WRITABLE_RW}/newroot
13 | NEWROOT_LOWER_RO=${NEWROOT}/ro
14 | NEWROOT_WRITABLE_RW=${NEWROOT}/rw
15 |
16 |
17 | echo "Setup essential mounts"
18 | /bin/busybox mount -t devtmpfs none /dev
19 | /bin/busybox mount -t proc proc /proc
20 | /bin/busybox mount -t sysfs sysfs /sys
21 | /bin/busybox mount -t tmpfs inittemp /mnt
22 |
23 | echo "Setting up overlayroot..."
24 |
25 | # 3. Mount read-only rootfs
26 | echo "Mounting read-only rootfs from $LOWER_RO_DEVICE to $LOWER_RO"
27 | /bin/busybox mkdir -p ${LOWER_RO}
28 | /bin/busybox mount -t ext4 ${LOWER_RO_DEVICE} ${LOWER_RO}
29 | if [ $? -ne 0 ]; then
30 | echo "Error mounting read-only rootfs!"
31 | exec /bin/busybox sh # Drop to shell for debugging
32 | return 1
33 | else
34 | echo "Read-only rootfs mounted successfully."
35 | fi
36 |
37 | # 2. Mount writable device
38 | echo "Mounting writable device $WRITABLE_RW_DEVICE to $WRITABLE_RW"
39 | /bin/busybox mkdir -p ${WRITABLE_RW}
40 | # TODO: Add ro for good measure.
41 | /bin/busybox mount -t ext4 ${WRITABLE_RW_DEVICE} ${WRITABLE_RW}
42 | if [ $? -ne 0 ]; then
43 | echo "Error mounting writable device!"
44 | exec /bin/busybox sh # Drop to shell for debugging
45 | return 1
46 | else
47 | echo "Writable device mounted successfully."
48 | fi
49 |
50 | # 3. Create upper and work directories
51 | echo "Creating upper and work directories in $WRITABLE_RW"
52 | /bin/busybox mkdir -p ${UPPER}
53 | /bin/busybox mkdir -p ${WORK}
54 | /bin/busybox mkdir -p ${NEWROOT}
55 | /bin/busybox mkdir -p ${NEWROOT_LOWER_RO}
56 | /bin/busybox mkdir -p ${NEWROOT_WRITABLE_RW}
57 |
58 | # 4. Mount overlayfs
59 | echo "Mounting overlayfs to $NEWROOT"
60 | /bin/busybox mount -t overlay overlay -o lowerdir=${LOWER_RO},upperdir=${UPPER},workdir=${WORK} ${NEWROOT}
61 | if [ $? -ne 0 ]; then
62 | echo "Error mounting overlayfs!"
63 | exec /bin/busybox sh # Drop to shell for debugging
64 | return 1
65 | else
66 | echo "Overlayfs mounted successfully."
67 | fi
68 |
69 | echo "Verifying /mnt/overlay is a mount point..."
70 | echo $(/bin/busybox mount)
71 |
72 | echo "Switching root to ${NEWROOT}"
73 | exec switch_root ${NEWROOT} /sbin/init
74 |
--------------------------------------------------------------------------------
/pkg/cmdserver/cmdserver.go:
--------------------------------------------------------------------------------
1 | package cmdserver
2 |
3 | // fileData represents a single file's content and metadata.
4 | type FileData struct {
5 | Content string `json:"content"`
6 | Path string `json:"path"`
7 | Error string `json:"error,omitempty"`
8 | }
9 |
10 | // FilesGetResponse represents multiple files.
11 | type FilesGetResponse struct {
12 | Files []FileData `json:"files"`
13 | }
14 |
15 | // FilePostData represents a single file to be uploaded.
16 | type FilePostData struct {
17 | Path string `json:"path"`
18 | Content string `json:"content"`
19 | }
20 |
21 | // FilesPostRequest represents multiple files to be uploaded.
22 | type FilesPostRequest struct {
23 | Files []FilePostData `json:"files"`
24 | }
25 |
26 | // RunCmdResponse structure for JSON responses from command execution
27 | type RunCmdResponse struct {
28 | Output string `json:"output,omitempty"`
29 | Error string `json:"error,omitempty"`
30 | }
--------------------------------------------------------------------------------
/pkg/config/config.go:
--------------------------------------------------------------------------------
1 | package config
2 |
3 | import (
4 | "fmt"
5 |
6 | "github.com/spf13/viper"
7 | )
8 |
9 | const (
10 | serverConfigKey = "hostservices.restserver"
11 | clientConfigKey = "hostservices.client"
12 | codeServerConfigKey = "guestservices.codeserver"
13 | )
14 |
15 | type PortForwardConfig struct {
16 | Port string `mapstructure:"port"`
17 | Description string `mapstructure:"description"`
18 | }
19 |
20 | type ServerConfig struct {
21 | Host string `mapstructure:"host"`
22 | Port string `mapstructure:"port"`
23 | StateDir string `mapstructure:"state_dir"`
24 | BridgeName string `mapstructure:"bridge_name"`
25 | BridgeIP string `mapstructure:"bridge_ip"`
26 | BridgeSubnet string `mapstructure:"bridge_subnet"`
27 | ChvBinPath string `mapstructure:"chv_bin"`
28 | KernelPath string `mapstructure:"kernel"`
29 | RootfsPath string `mapstructure:"rootfs"`
30 | PortForwards []PortForwardConfig `mapstructure:"port_forwards"`
31 | InitramfsPath string `mapstructure:"initramfs"`
32 | StatefulSizeInMB int32 `mapstructure:"stateful_size_in_mb"`
33 | GuestMemPercentage int32 `mapstructure:"guest_mem_percentage"`
34 | }
35 |
36 | func (c ServerConfig) String() string {
37 | return fmt.Sprintf(`{
38 | Host: %s
39 | Port: %s
40 | StateDir: %s
41 | BridgeName: %s
42 | BridgeIP: %s
43 | BridgeSubnet: %s
44 | KernelPath: %s
45 | ChvBinPath: %s
46 | PortForwards: %+v
47 | InitramfsPath: %s
48 | StatefulSizeInMB: %d
49 | GuestMemPercentage: %d
50 | }`,
51 | c.Host,
52 | c.Port,
53 | c.StateDir,
54 | c.BridgeName,
55 | c.BridgeIP,
56 | c.BridgeSubnet,
57 | c.KernelPath,
58 | c.ChvBinPath,
59 | c.PortForwards,
60 | c.InitramfsPath,
61 | c.StatefulSizeInMB,
62 | c.GuestMemPercentage,
63 | )
64 | }
65 |
66 | type ClientConfig struct {
67 | ServerHost string `mapstructure:"server_host"`
68 | ServerPort string `mapstructure:"server_port"`
69 | }
70 |
71 | func (c ClientConfig) String() string {
72 | return fmt.Sprintf(`{
73 | ServerHost: %s
74 | ServerPort: %s
75 | }`, c.ServerHost, c.ServerPort)
76 | }
77 |
78 | type CodeServerConfig struct {
79 | Port string `mapstructure:"port"`
80 | }
81 |
82 | func (c CodeServerConfig) String() string {
83 | return fmt.Sprintf(`{
84 | Port: %s
85 | }`, c.Port)
86 | }
87 |
88 | func GetServerConfig(configFile string) (*ServerConfig, error) {
89 | viper.SetConfigFile(configFile)
90 | err := viper.ReadInConfig()
91 | if err != nil {
92 | return nil, fmt.Errorf("failed to read config: %v", err)
93 | }
94 |
95 | restServerConfig := viper.Sub(serverConfigKey)
96 | if restServerConfig == nil {
97 | return nil, fmt.Errorf("restserver configuration not found")
98 | }
99 |
100 | var result ServerConfig
101 | if err := restServerConfig.Unmarshal(&result); err != nil {
102 | return nil, fmt.Errorf("error unmarshalling config: %v", err)
103 | }
104 |
105 | return &result, nil
106 | }
107 |
108 | func GetClientConfig(configFile string) (*ClientConfig, error) {
109 | viper.SetConfigFile(configFile)
110 | err := viper.ReadInConfig()
111 | if err != nil {
112 | return nil, fmt.Errorf("failed to read config: %v", err)
113 | }
114 |
115 | clientConfig := viper.Sub(clientConfigKey)
116 | if clientConfig == nil {
117 | return nil, fmt.Errorf("client configuration not found")
118 | }
119 |
120 | var result ClientConfig
121 | if err := clientConfig.Unmarshal(&result); err != nil {
122 | return nil, fmt.Errorf("error unmarshalling config: %v", err)
123 | }
124 | return &result, nil
125 | }
126 |
127 | func GetCodeServerConfig(configFile string) (*CodeServerConfig, error) {
128 | viper.SetConfigFile(configFile)
129 | err := viper.ReadInConfig()
130 | if err != nil {
131 | return nil, fmt.Errorf("failed to read config: %v", err)
132 | }
133 |
134 | clientConfig := viper.Sub(clientConfigKey)
135 | if clientConfig == nil {
136 | return nil, fmt.Errorf("client configuration not found")
137 | }
138 |
139 | var result CodeServerConfig
140 | if err := clientConfig.Unmarshal(&result); err != nil {
141 | return nil, fmt.Errorf("error unmarshalling config: %v", err)
142 | }
143 | return &result, nil
144 | }
145 |
--------------------------------------------------------------------------------
/pkg/server/cidallocator/cidallocator.go:
--------------------------------------------------------------------------------
1 | package cidallocator
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | // CIDAllocator manages allocation of Context IDs (CIDs) for VMs
9 | type CIDAllocator struct {
10 | lowCID uint32
11 | highCID uint32
12 | available []uint32
13 | mutex sync.Mutex
14 | }
15 |
16 | // NewCIDAllocator creates a new CID allocator for the given CID range
17 | func NewCIDAllocator(lowCID, highCID uint32) (*CIDAllocator, error) {
18 | if lowCID < 3 || highCID > 0xFFFFFFFF || lowCID > highCID {
19 | return nil, fmt.Errorf("invalid CID range: %d-%d", lowCID, highCID)
20 | }
21 |
22 | allocator := &CIDAllocator{
23 | lowCID: lowCID,
24 | highCID: highCID,
25 | available: make([]uint32, 0, highCID-lowCID+1),
26 | }
27 |
28 | // Initialize available CIDs
29 | for cid := lowCID; cid <= highCID; cid++ {
30 | allocator.available = append(allocator.available, cid)
31 | }
32 |
33 | return allocator, nil
34 | }
35 |
36 | // AllocateCID allocates and returns the next available CID
37 | func (a *CIDAllocator) AllocateCID() (uint32, error) {
38 | a.mutex.Lock()
39 | defer a.mutex.Unlock()
40 |
41 | if len(a.available) == 0 {
42 | return 0, fmt.Errorf("no available CIDs in range %d-%d", a.lowCID, a.highCID)
43 | }
44 |
45 | // Take the first available CID
46 | cid := a.available[0]
47 | a.available = a.available[1:]
48 |
49 | return cid, nil
50 | }
51 |
52 | // FreeCID returns a CID to the pool of available CIDs
53 | func (a *CIDAllocator) FreeCID(cid uint32) error {
54 | a.mutex.Lock()
55 | defer a.mutex.Unlock()
56 |
57 | if cid < a.lowCID || cid > a.highCID {
58 | return fmt.Errorf("CID %d is outside allocator range %d-%d", cid, a.lowCID, a.highCID)
59 | }
60 |
61 | // Check if CID is already in available pool
62 | for _, c := range a.available {
63 | if c == cid {
64 | return fmt.Errorf("CID %d is already free", cid)
65 | }
66 | }
67 |
68 | a.available = append(a.available, cid)
69 | return nil
70 | }
71 |
72 | // ClaimCID claims a specific CID from the pool of available CIDs
73 | func (a *CIDAllocator) ClaimCID(cid uint32) error {
74 | a.mutex.Lock()
75 | defer a.mutex.Unlock()
76 |
77 | for i, c := range a.available {
78 | if c == cid {
79 | a.available = append(a.available[:i], a.available[i+1:]...)
80 | return nil
81 | }
82 | }
83 | return fmt.Errorf("CID %d is not available", cid)
84 | }
--------------------------------------------------------------------------------
/pkg/server/fountain/fountain.go:
--------------------------------------------------------------------------------
1 | package fountain
2 |
3 | import (
4 | "fmt"
5 | "os/exec"
6 | "sync"
7 |
8 | log "github.com/sirupsen/logrus"
9 | "gvisor.dev/gvisor/pkg/cleanup"
10 | )
11 |
12 | const (
13 | LowID int32 = 0
14 | HighID int32 = 65535
15 | )
16 |
17 | // TapDevice represents a tap network device
18 | type TapDevice struct {
19 | Name string
20 | ID int32
21 | }
22 |
23 | // String implements the fmt.Stringer interface.
24 | func (t *TapDevice) String() string {
25 | return fmt.Sprintf("TapDevice{Name: %s, ID: %d}", t.Name, t.ID)
26 | }
27 |
28 | type Fountain struct {
29 | bridgeDevice string
30 | mutex sync.Mutex
31 | available []int32 // Available tap IDs
32 | lowID int32 // Lowest ID to allocate
33 | highID int32 // Highest ID to allocate
34 | }
35 |
36 | func NewFountain(bridgeDevice string) *Fountain {
37 | f := &Fountain{
38 | bridgeDevice: bridgeDevice,
39 | lowID: LowID,
40 | highID: HighID,
41 | available: make([]int32, 0, HighID-LowID+1),
42 | }
43 |
44 | for id := LowID; id <= HighID; id++ {
45 | f.available = append(f.available, id)
46 | }
47 | return f
48 | }
49 |
50 | // allocateTapID allocates a new tap device ID (internal use).
51 | func (f *Fountain) allocateTapID() (int32, error) {
52 | f.mutex.Lock()
53 | defer f.mutex.Unlock()
54 |
55 | if len(f.available) == 0 {
56 | return -1, fmt.Errorf("no available tap device IDs in range %d-%d", f.lowID, f.highID)
57 | }
58 |
59 | id := f.available[0]
60 | f.available = f.available[1:]
61 | return id, nil
62 | }
63 |
64 | // freeTapID returns a tap ID to the pool of available IDs (internal use).
65 | func (f *Fountain) freeTapID(id int32) error {
66 | f.mutex.Lock()
67 | defer f.mutex.Unlock()
68 |
69 | if id < f.lowID || id > f.highID {
70 | return fmt.Errorf("tap ID %d is outside allocator range %d-%d", id, f.lowID, f.highID)
71 | }
72 |
73 | for _, i := range f.available {
74 | if i == id {
75 | return fmt.Errorf("tap ID %d is already free", id)
76 | }
77 | }
78 | f.available = append(f.available, id)
79 | return nil
80 | }
81 |
82 | // claimID attempts to claim a specific tap ID from the pool
83 | // It returns an error if the ID is not available or outside the valid range
84 | func (f *Fountain) claimID(id int32) error {
85 | f.mutex.Lock()
86 | defer f.mutex.Unlock()
87 |
88 | // Check if ID is in valid range
89 | if id < f.lowID || id > f.highID {
90 | return fmt.Errorf("tap ID %d is outside allocator range %d-%d", id, f.lowID, f.highID)
91 | }
92 |
93 | // Check if ID is available
94 | isAvailable := false
95 | for i, availableID := range f.available {
96 | if availableID == id {
97 | // Remove this ID from the available pool
98 | f.available = append(f.available[:i], f.available[i+1:]...)
99 | isAvailable = true
100 | break
101 | }
102 | }
103 |
104 | if !isAvailable {
105 | return fmt.Errorf("tap ID %d is not available", id)
106 | }
107 |
108 | return nil
109 | }
110 |
111 | // CreateTapDevice creates a new tap device with an auto-allocated ID and returns a TapDevice
112 | // If id is provided, it will attempt to claim that specific ID instead of auto-allocating
113 | func (f *Fountain) CreateTapDevice(id *int32) (*TapDevice, error) {
114 | logger := log.WithField("action", "CreateTapDevice")
115 | cleanup := cleanup.Make(func() {
116 | logger.Debug("createTapDevice cleanup")
117 | })
118 | defer cleanup.Clean()
119 |
120 | var allocatedID int32
121 | var err error
122 | if id != nil {
123 | if err := f.claimID(*id); err != nil {
124 | return nil, err
125 | }
126 | allocatedID = *id
127 | } else {
128 | // Use existing auto-allocation logic
129 | allocatedID, err = f.allocateTapID()
130 | if err != nil {
131 | return nil, fmt.Errorf("failed to allocate tap ID: %w", err)
132 | }
133 | }
134 | cleanup.Add(func() {
135 | if err := f.freeTapID(allocatedID); err != nil {
136 | logger.WithError(err).Errorf("failed to free tap ID %d during cleanup", allocatedID)
137 | }
138 | })
139 |
140 | deviceName := fmt.Sprintf("tap%d", allocatedID)
141 | if output, err := exec.Command(
142 | "ip", "tuntap", "add", "dev", deviceName, "mode", "tap",
143 | ).CombinedOutput(); err != nil {
144 | return nil, fmt.Errorf("failed to create: %v: %s %w", deviceName, output, err)
145 | }
146 |
147 | if output, err := exec.Command(
148 | "ip", "l", "set", "dev", deviceName, "master", f.bridgeDevice,
149 | ).CombinedOutput(); err != nil {
150 | return nil, fmt.Errorf("failed to add: %v to: %v: %s %w", deviceName, f.bridgeDevice, output, err)
151 | }
152 |
153 | if output, err := exec.Command(
154 | "ip", "l", "set", deviceName, "up",
155 | ).CombinedOutput(); err != nil {
156 | return nil, fmt.Errorf("failed to up: %v: %s %w", deviceName, output, err)
157 | }
158 |
159 | cleanup.Release()
160 | return &TapDevice{
161 | Name: deviceName,
162 | ID: allocatedID,
163 | }, nil
164 | }
165 |
166 | // DestroyTapDevice destroys a tap device and frees its ID.
167 | func (f *Fountain) DestroyTapDevice(device *TapDevice) error {
168 | log.WithFields(log.Fields{
169 | "deviceName": device.Name,
170 | "deviceID": device.ID,
171 | }).Info("destroy tap device")
172 |
173 | // Remove the tap device from the bridge
174 | if err := exec.Command("ip", "link", "set", device.Name, "nomaster").Run(); err != nil {
175 | return fmt.Errorf("failed to remove %v from bridge: %w", device.Name, err)
176 | }
177 |
178 | // Bring the tap device down
179 | if err := exec.Command("ip", "link", "set", device.Name, "down").Run(); err != nil {
180 | return fmt.Errorf("failed to bring down %v: %w", device.Name, err)
181 | }
182 |
183 | // Delete the tap device
184 | if err := exec.Command("ip", "tuntap", "del", "dev", device.Name, "mode", "tap").Run(); err != nil {
185 | return fmt.Errorf("failed to delete %v: %w", device.Name, err)
186 | }
187 |
188 | // Free the ID if it's valid
189 | if device.ID >= f.lowID && device.ID <= f.highID {
190 | // Ignore error from freeTapID as the device is already deleted
191 | _ = f.freeTapID(device.ID)
192 | }
193 |
194 | return nil
195 | }
196 |
--------------------------------------------------------------------------------
/pkg/server/ipallocator/ipallocator.go:
--------------------------------------------------------------------------------
1 | package ipallocator
2 |
3 | import (
4 | "fmt"
5 | "net"
6 | "sync"
7 | )
8 |
9 | type IPAllocator struct {
10 | subnet *net.IPNet
11 | available []net.IP
12 | mutex sync.Mutex
13 | }
14 |
15 | func incrementIP(ip net.IP) net.IP {
16 | newIP := copyIP(ip)
17 | for j := len(newIP) - 1; j >= 0; j-- {
18 | newIP[j]++
19 | if newIP[j] > 0 {
20 | break
21 | }
22 | }
23 | return newIP
24 | }
25 |
26 | func copyIP(ip net.IP) net.IP {
27 | dup := make(net.IP, len(ip))
28 | copy(dup, ip)
29 | return dup
30 | }
31 |
32 | func NewIPAllocator(subnetCIDR string) (*IPAllocator, error) {
33 | _, subnet, err := net.ParseCIDR(subnetCIDR)
34 | if err != nil {
35 | return nil, fmt.Errorf("invalid subnet CIDR: %v", err)
36 | }
37 |
38 | allocator := &IPAllocator{
39 | subnet: subnet,
40 | available: []net.IP{},
41 | }
42 |
43 | // The first one will be reserved as the gateway. Start from x.x.x.2.
44 | ip := incrementIP(subnet.IP)
45 |
46 | // Generate all available IPs in the subnet
47 | for ip := incrementIP(ip); subnet.Contains(ip); ip = incrementIP(ip) {
48 | allocator.available = append(allocator.available, copyIP(ip))
49 | }
50 |
51 | return allocator, nil
52 | }
53 |
54 | func (a *IPAllocator) AllocateIP() (*net.IPNet, error) {
55 | a.mutex.Lock()
56 | defer a.mutex.Unlock()
57 |
58 | if len(a.available) == 0 {
59 | return nil, fmt.Errorf("no available IPs")
60 | }
61 |
62 | ip := a.available[0]
63 | a.available = a.available[1:]
64 |
65 | return &net.IPNet{
66 | IP: ip,
67 | Mask: a.subnet.Mask,
68 | }, nil
69 | }
70 |
71 | func (a *IPAllocator) FreeIP(ip net.IP) error {
72 | a.mutex.Lock()
73 | defer a.mutex.Unlock()
74 |
75 | if !a.subnet.Contains(ip) {
76 | return fmt.Errorf("IP %v is not in the subnet", ip)
77 | }
78 |
79 | a.available = append(a.available, copyIP(ip))
80 | return nil
81 | }
82 |
83 | // ClaimIP attempts to claim a specific IP address from the pool.
84 | // Returns error if the IP is already allocated or not in the subnet.
85 | func (a *IPAllocator) ClaimIP(ip net.IP) error {
86 | a.mutex.Lock()
87 | defer a.mutex.Unlock()
88 |
89 | if !a.subnet.Contains(ip) {
90 | return fmt.Errorf("IP %v is not in the subnet", ip)
91 | }
92 |
93 | for i, availIP := range a.available {
94 | if availIP.Equal(ip) {
95 | // Remove this IP from available pool
96 | a.available = append(a.available[:i], a.available[i+1:]...)
97 | break
98 | }
99 | }
100 | return nil
101 | }
102 |
--------------------------------------------------------------------------------
/pkg/server/portallocator/portallocator.go:
--------------------------------------------------------------------------------
1 | package portallocator
2 |
3 | import (
4 | "fmt"
5 | "sync"
6 | )
7 |
8 | // PortAllocator manages allocation of ports within a specified range
9 | type PortAllocator struct {
10 | lowPort int32
11 | highPort int32
12 | available []int32
13 | mutex sync.Mutex
14 | }
15 |
16 | // NewPortAllocator creates a new port allocator for the given port range
17 | func NewPortAllocator(lowPort, highPort int32) (*PortAllocator, error) {
18 | if lowPort < 1 || highPort > 65535 || lowPort > highPort {
19 | return nil, fmt.Errorf("invalid port range: %d-%d", lowPort, highPort)
20 | }
21 |
22 | allocator := &PortAllocator{
23 | lowPort: lowPort,
24 | highPort: highPort,
25 | available: make([]int32, 0, highPort-lowPort+1),
26 | }
27 |
28 | // Initialize available ports
29 | for port := lowPort; port <= highPort; port++ {
30 | allocator.available = append(allocator.available, port)
31 | }
32 |
33 | return allocator, nil
34 | }
35 |
36 | // AllocatePort allocates and returns the next available port
37 | func (a *PortAllocator) AllocatePort() (int32, error) {
38 | a.mutex.Lock()
39 | defer a.mutex.Unlock()
40 |
41 | if len(a.available) == 0 {
42 | return 0, fmt.Errorf("no available ports in range %d-%d", a.lowPort, a.highPort)
43 | }
44 |
45 | // Take the first available port
46 | port := a.available[0]
47 | a.available = a.available[1:]
48 |
49 | return port, nil
50 | }
51 |
52 | // FreePort returns a port to the pool of available ports
53 | func (a *PortAllocator) FreePort(port int32) error {
54 | a.mutex.Lock()
55 | defer a.mutex.Unlock()
56 |
57 | if port < a.lowPort || port > a.highPort {
58 | return fmt.Errorf("port %d is outside allocator range %d-%d", port, a.lowPort, a.highPort)
59 | }
60 |
61 | // Check if port is already in available pool
62 | for _, p := range a.available {
63 | if p == port {
64 | return fmt.Errorf("port %d is already free", port)
65 | }
66 | }
67 |
68 | a.available = append(a.available, port)
69 | return nil
70 | }
71 |
--------------------------------------------------------------------------------
/resources/arrakis-cmdserver.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=CHV Command Server
3 | After=arrakis-guestinit.service
4 |
5 | [Service]
6 | Type=simple
7 | ExecStart=/usr/local/bin/arrakis-cmdserver
8 | Restart=on-failure
9 | RestartSec=5
10 | StandardOutput=journal
11 | StandardError=journal
12 |
13 | [Install]
14 | WantedBy=multi-user.target
15 |
--------------------------------------------------------------------------------
/resources/arrakis-guestinit.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=Arrakis sandbox Guest Initialization Service
3 | # This service configures the guest's network and thus requires the interface to be UP.
4 | After=network-online.target
5 |
6 | [Service]
7 | # Using `oneshot` ensures that After= clauses in other services referring to this service mean that
8 | # the service is finished running.
9 | Type=oneshot
10 | ExecStart=/usr/local/bin/arrakis-guestinit
11 | ExecStartPost=hostnamectl hostname arrakis-vm
12 | # Directly using `echo` didn't work.
13 | ExecStartPost=/bin/sh -c 'echo "127.0.0.1 arrakis-vm" >> /etc/hosts'
14 | ExecStartPost=/bin/sh -c 'echo "127.0.0.1 localhost" >> /etc/hosts'
15 | Restart=no
16 | StandardOutput=journal
17 | StandardError=journal
18 |
19 | [Install]
20 | WantedBy=multi-user.target
21 |
--------------------------------------------------------------------------------
/resources/arrakis-vncserver.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=CHV VNC Server
3 | After=arrakis-guestinit.service
4 |
5 | [Service]
6 | Type=forking
7 | User=elara
8 | # Set VNC password before starting tigervncserver, so we don't have to enter it manually.
9 | ExecStartPre=/bin/sh -c 'printf "elara0000\nelara0000\nn\n" | /usr/bin/vncpasswd'
10 | # Kill any stale data from previous runs. But don't fail if it doesn't exist.
11 | ExecStartPre=-/usr/bin/vncserver -kill :*
12 | ExecStart=/usr/bin/vncserver -localhost no -xstartup /usr/bin/startxfce4
13 | ExecStop=/usr/bin/vncserver -kill :*
14 | Restart=on-failure
15 | RestartSec=5
16 | StandardOutput=journal
17 | StandardError=journal
18 |
19 | [Install]
20 | WantedBy=multi-user.target
21 |
--------------------------------------------------------------------------------
/resources/arrakis-vsockserver.service:
--------------------------------------------------------------------------------
1 | [Unit]
2 | Description=CHV Vsock Server
3 | # We need to listen on the vsock port.
4 | After=network-online.target
5 |
6 | [Service]
7 | Type=notify
8 | ExecStart=/usr/local/bin/arrakis-vsockserver
9 | Restart=no
10 | StandardOutput=journal
11 | StandardError=journal
12 |
13 | [Install]
14 | WantedBy=multi-user.target
15 |
--------------------------------------------------------------------------------
/resources/scripts/rootfs/Dockerfile:
--------------------------------------------------------------------------------
1 | FROM ubuntu:22.04
2 |
3 | # Avoid prompts from apt.
4 | ENV DEBIAN_FRONTEND=noninteractive
5 |
6 | ARG USERNAME=elara
7 | ARG PASSWORD=elara0000
8 | RUN useradd -m $USERNAME && \
9 | echo "$USERNAME:$PASSWORD" | chpasswd && \
10 | adduser $USERNAME sudo
11 |
12 | # Needed to see journal logs.
13 | RUN usermod -aG adm elara
14 |
15 | # Set timezone.
16 | ENV TZ=Etc/UTC
17 | RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone
18 |
19 | # Packages required for Agent-S https://github.com/simular-ai/Agent-S.
20 | ARG AGENT_S_PACKAGES="python3-tk gnome-screenshot cmake libcairo2-dev python3-gi python3-gi-cairo gir1.2-gtk-4.0 libgirepository1.0-dev gir1.2-atspi-2.0"
21 |
22 | # Update and install common utilities.
23 | RUN apt-get update && \
24 | apt-get install -y ${AGENT_S_PACKAGES} \
25 | init \
26 | systemd \
27 | ncat \
28 | bash \
29 | curl \
30 | wget \
31 | vim \
32 | nano \
33 | git \
34 | htop \
35 | net-tools \
36 | iputils-ping \
37 | iproute2 \
38 | traceroute \
39 | dnsutils \
40 | tcpdump \
41 | netcat-openbsd \
42 | ssh \
43 | sudo \
44 | man-db \
45 | less \
46 | procps \
47 | psmisc \
48 | lsof \
49 | rsync \
50 | tar \
51 | gzip \
52 | zip \
53 | unzip \
54 | ca-certificates \
55 | tzdata \
56 | tini \
57 | python3 \
58 | python3-venv \
59 | python3-pip \
60 | xvfb \
61 | xfce4 \
62 | xfce4-goodies \
63 | zsh \
64 | tigervnc-standalone-server \
65 | socat \
66 | strace \
67 | && apt-get clean \
68 | && rm -rf /var/lib/apt/lists/*
69 |
70 | # To support sudo within the guest.
71 | RUN chown root:root /usr/bin/sudo && chmod 4755 /usr/bin/sudo
72 |
73 | # TODO: Tighten permissions on this directory after testing.
74 | RUN mkdir -p /mnt/stateful && chmod 0777 /mnt/stateful
75 |
76 | # Set up directory for the vsock server. This is required in case the overlayfs setup fails, we
77 | # still need the vsockserver to be able to run.
78 | RUN mkdir -p /tmp/vsockserver && chmod 0644 /tmp/vsockserver
79 |
80 | # Add user binaries from the host into the guest rootfs in this section.
81 | ##############
82 | RUN ln -s /usr/lib/systemd/system/multi-user.target /etc/systemd/system/default.target
83 |
84 | ARG OUT_DIR=out
85 | ARG RESOURCES_DIR=resources
86 |
87 | ARG GUESTINIT_BIN=arrakis-guestinit
88 | COPY ${OUT_DIR}/${GUESTINIT_BIN} /usr/local/bin/${GUESTINIT_BIN}
89 | RUN chmod +x /usr/local/bin/${GUESTINIT_BIN}
90 | COPY ${RESOURCES_DIR}/${GUESTINIT_BIN}.service /usr/lib/systemd/system/${GUESTINIT_BIN}.service
91 | RUN ln -s /usr/lib/systemd/system/${GUESTINIT_BIN}.service /etc/systemd/system/multi-user.target.wants/${GUESTINIT_BIN}.service
92 |
93 | ARG CMDSERVER_BIN=arrakis-cmdserver
94 | COPY ${OUT_DIR}/${CMDSERVER_BIN} /usr/local/bin/${CMDSERVER_BIN}
95 | RUN chmod +x /usr/local/bin/${CMDSERVER_BIN}
96 | COPY ${RESOURCES_DIR}/${CMDSERVER_BIN}.service /usr/lib/systemd/system/${CMDSERVER_BIN}.service
97 | RUN ln -s /usr/lib/systemd/system/${CMDSERVER_BIN}.service /etc/systemd/system/multi-user.target.wants/${CMDSERVER_BIN}.service
98 |
99 | ARG VNCSERVER_BIN=arrakis-vncserver
100 | COPY ${RESOURCES_DIR}/${VNCSERVER_BIN}.service /usr/lib/systemd/system/${VNCSERVER_BIN}.service
101 | RUN ln -s /usr/lib/systemd/system/${VNCSERVER_BIN}.service /etc/systemd/system/multi-user.target.wants/${VNCSERVER_BIN}.service
102 |
103 | ARG VSOCKSERVER_BIN=arrakis-vsockserver
104 | COPY ${OUT_DIR}/${VSOCKSERVER_BIN} /usr/local/bin/${VSOCKSERVER_BIN}
105 | RUN chmod +x /usr/local/bin/${VSOCKSERVER_BIN}
106 | COPY ${RESOURCES_DIR}/${VSOCKSERVER_BIN}.service /usr/lib/systemd/system/${VSOCKSERVER_BIN}.service
107 | RUN ln -s /usr/lib/systemd/system/${VSOCKSERVER_BIN}.service /etc/systemd/system/multi-user.target.wants/${VSOCKSERVER_BIN}.service
108 |
109 | # Prevent the renaming service that will change "eth0" to "ens*". If not done our init service
110 | # inside the guest has race conditions while configuring the network.
111 | RUN ln -s /dev/null /etc/systemd/network/99-default.link
112 | ##############
113 |
114 | # Install Chrome.
115 | RUN wget -O /tmp/google-chrome-stable_current_amd64.deb https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb && \
116 | # Any failure here will be fixed by the `install -f` command below.
117 | dpkg -i /tmp/google-chrome-stable_current_amd64.deb || true && \
118 | apt-get update && apt-get install -f -y && \
119 | rm -rf /tmp/google-chrome-stable_current_amd64.deb && \
120 | apt-get clean && rm -rf /var/lib/apt/lists/*
121 |
122 | # Install Node.js and npm
123 | RUN curl -fsSL https://deb.nodesource.com/setup_22.x -o nodesource_setup.sh && \
124 | sudo -E bash nodesource_setup.sh && \
125 | sudo apt-get install -y nodejs && \
126 | rm -f nodesource_setup.sh && \
127 | apt-get clean && rm -rf /var/lib/apt/lists/*
128 |
--------------------------------------------------------------------------------
/setup/gcp-instructions.md:
--------------------------------------------------------------------------------
1 | # Setup Instructions on GCP
2 |
3 | ## Setting Up a GCE VM with Nested Virtualization Support
4 |
5 | - To create a Google Compute Engine (GCE) virtual machine with nested virtualization enabled, run the following command make sure to replace the $VM_NAME and $PROJECT with your own values.
6 |
7 | ```bash
8 | VM_NAME=
9 | PROJECT_ID=
10 | SERVICE_ACCOUNT=
11 | ZONE=
12 |
13 | gcloud compute instances create ${VM_NAME} --project=${PROJECT_ID} --zone=${ZONE} --machine-type=n1-standard-1 --network-interface=network-tier=STANDARD,stack-type=IPV4_ONLY,subnet=default --maintenance-policy=MIGRATE --provisioning-model=STANDARD --service-account=${SERVICE_ACCOUNT} --scopes=https://www.googleapis.com/auth/devstorage.read_only,https://www.googleapis.com/auth/logging.write,https://www.googleapis.com/auth/monitoring.write,https://www.googleapis.com/auth/service.management.readonly,https://www.googleapis.com/auth/servicecontrol,https://www.googleapis.com/auth/trace.append --create-disk=auto-delete=yes,boot=yes,device-name=maverick-gcp-dev-vm3,image=projects/ubuntu-os-cloud/global/images/ubuntu-2204-jammy-v20250128,mode=rw,size=20,type=pd-standard --no-shielded-secure-boot --shielded-vtpm --shielded-integrity-monitoring --labels=goog-ec-src=vm_add-gcloud --reservation-affinity=any --enable-nested-virtualization
14 |
15 | NETWORK_TAG=allow-ingress-ports
16 | FIREWALL_RULE=allow-ingress-ports-rule
17 | gcloud compute instances add-tags ${VM_NAME} --tags=${NETWORK_TAG} --zone=${ZONE}
18 | gcloud compute firewall-rules create ${FIREWALL_RULE} \
19 | --direction=INGRESS \
20 | --priority=1000 \
21 | --network=default \
22 | --action=ALLOW \
23 | --rules=tcp:3000-5000,tcp:7000 \
24 | --source-ranges=0.0.0.0/0 \
25 | --target-tags=${NETWORK_TAG} \
26 | --description="Allow TCP ingress on ports 3000-5000 and 7000 for VMs with the ${NETWORK_TAG} tag"
27 | ```
28 |
29 | ## Instructions to run on the GCE VM
30 |
31 | - SSH into the VM.
32 |
33 | ```bash
34 | # Use the setup script to install Arrakis
35 | cd $HOME
36 | curl -sSL "https://raw.githubusercontent.com/abshkbh/arrakis/main/setup/setup.sh" | bash
37 | ```
38 |
39 | - Verify the installation
40 |
41 | ```bash
42 | cd $HOME/arrakis-prebuilt
43 | ls
44 | ```
45 |
46 | - Run the Arrakis REST server
47 |
48 | ```bash
49 | sudo ./arrakis-restserver
50 | ```
51 |
52 | - In another terminal, use the client to start sandboxes.
53 |
54 | ```bash
55 | cd ./arrakis-prebuilt
56 | ./arrakis-client
57 | ```
58 |
59 | - Or use the Python SDK [py-arrakis](https://pypi.org/project/py-arrakis/) to start sandboxes.
60 |
--------------------------------------------------------------------------------
/setup/install-deps.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 |
4 | # Update apt package list
5 | echo "Updating apt package list..."
6 | sudo apt update
7 |
8 | # Install make
9 | echo "Installing make..."
10 | sudo apt install -y make
11 |
12 | # Install nvm using the provided install script
13 | echo "Installing nvm..."
14 | curl -o- https://raw.githubusercontent.com/nvm-sh/nvm/v0.40.1/install.sh | bash
15 |
16 | # Load nvm into the current shell session
17 | export NVM_DIR="$HOME/.nvm"
18 | if [ -s "$NVM_DIR/nvm.sh" ]; then
19 | . "$NVM_DIR/nvm.sh"
20 | else
21 | echo "nvm installation failed or nvm.sh not found."
22 | exit 1
23 | fi
24 |
25 | # Install Node.js using nvm
26 | echo "Installing Node.js..."
27 | nvm install node
28 |
29 | # Install OpenAPI Generator CLI globally using npm
30 | echo "Installing OpenAPI Generator CLI..."
31 | npm install @openapitools/openapi-generator-cli -g
32 |
33 | # Install Go programming language
34 | # Ensure the go1.23.6.linux-amd64.tar.gz file is present in the current directory.
35 | echo "Installing Go..."
36 | sudo rm -rf /usr/local/go
37 | curl -LO https://go.dev/dl/go1.23.6.linux-amd64.tar.gz
38 | sudo tar -C /usr/local -xzf go1.23.6.linux-amd64.tar.gz
39 | echo "export PATH=$PATH:/usr/local/go/bin" >> ~/.bashrc
40 |
41 | # Install default JDK without prompting for confirmation
42 | echo "Installing default JDK..."
43 | sudo apt install -y default-jdk
44 |
45 | # Install Docker
46 | echo "Installing Docker..."
47 | echo "Removing old Docker packages if any..."
48 | for pkg in docker.io docker-doc docker-compose docker-compose-v2 podman-docker containerd runc; do
49 | sudo apt-get remove -y "$pkg" || true
50 | done
51 |
52 | echo "Adding Docker's official GPG key and repository..."
53 | sudo apt-get update
54 | sudo apt-get install -y ca-certificates curl
55 | sudo install -m 0755 -d /etc/apt/keyrings
56 | sudo curl -fsSL https://download.docker.com/linux/ubuntu/gpg -o /etc/apt/keyrings/docker.asc
57 | sudo chmod a+r /etc/apt/keyrings/docker.asc
58 |
59 | echo "deb [arch=$(dpkg --print-architecture) signed-by=/etc/apt/keyrings/docker.asc] https://download.docker.com/linux/ubuntu $(. /etc/os-release && echo "${UBUNTU_CODENAME:-$VERSION_CODENAME}") stable" | sudo tee /etc/apt/sources.list.d/docker.list > /dev/null
60 | sudo apt-get update
61 |
62 | echo "Installing Docker CE and related packages..."
63 | sudo apt-get install -y docker-ce docker-ce-cli containerd.io docker-buildx-plugin docker-compose-plugin
64 |
65 | echo "Cloning project..."
66 | mkdir -p "$HOME/projects"
67 | if [ -d "$HOME/projects/arrakis" ]; then
68 | echo "arrakis already exists. Skipping clone."
69 | else
70 | cd "$HOME/projects"
71 | git clone https://github.com/abshkbh/arrakis.git
72 | ./setup/install-images.py
73 | fi
74 | cd "$HOME"
75 |
76 | echo "Installation completed successfully."
--------------------------------------------------------------------------------
/setup/install-images.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 |
3 | import os
4 | import requests
5 | import stat
6 | from pathlib import Path
7 |
8 | def ensure_directory_exists(path):
9 | """Create directory if it doesn't exist."""
10 | Path(path).mkdir(parents=True, exist_ok=True)
11 |
12 | def download_file(url, destination, make_executable=False):
13 | """Download a file from URL to destination."""
14 | print(f"Downloading {url} to {destination}...")
15 |
16 | # For GitHub blob URLs, we need to get the raw content URL
17 | if "blob" in url:
18 | url = url.replace("github.com", "raw.githubusercontent.com").replace("/blob/", "/")
19 |
20 | response = requests.get(url, stream=True)
21 | response.raise_for_status()
22 |
23 | with open(destination, 'wb') as f:
24 | for chunk in response.iter_content(chunk_size=8192):
25 | f.write(chunk)
26 |
27 | if make_executable:
28 | # Make the file executable (chmod +x)
29 | current_permissions = os.stat(destination).st_mode
30 | os.chmod(destination, current_permissions | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH)
31 |
32 | def main():
33 | # Ensure resources/bin directory exists
34 | bin_dir = "resources/bin"
35 | ensure_directory_exists(bin_dir)
36 |
37 | # Download files
38 | files_to_download = [
39 | {
40 | "url": "https://github.com/abshkbh/arrakis-images/blob/main/guest/kernel/vmlinux.bin",
41 | "destination": f"{bin_dir}/vmlinux.bin",
42 | "executable": False
43 | },
44 | {
45 | "url": "https://github.com/cloud-hypervisor/cloud-hypervisor/releases/download/v44.0/cloud-hypervisor-static",
46 | "destination": f"{bin_dir}/cloud-hypervisor",
47 | "executable": True
48 | },
49 | {
50 | "url": "https://github.com/abshkbh/arrakis-images/blob/main/busybox",
51 | "destination": f"{bin_dir}/busybox",
52 | "executable": True
53 | }
54 | ]
55 |
56 | for file_info in files_to_download:
57 | try:
58 | download_file(
59 | file_info["url"],
60 | file_info["destination"],
61 | file_info["executable"]
62 | )
63 | print(f"Successfully downloaded {file_info['destination']}")
64 | except Exception as e:
65 | print(f"Error downloading {file_info['url']}: {str(e)}")
66 | exit(1)
67 |
68 | print("All files downloaded successfully!")
69 |
70 | if __name__ == "__main__":
71 | main()
72 |
--------------------------------------------------------------------------------
/setup/setup.sh:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env bash
2 | set -euo pipefail
3 |
4 | # Define colors for output
5 | GREEN='\033[0;32m'
6 | YELLOW='\033[1;33m'
7 | NC='\033[0m' # No Color
8 |
9 | # Define variables
10 | ARRAKIS_DIR="./arrakis-prebuilt"
11 | LATEST_RELEASE_URL="https://github.com/abshkbh/arrakis/releases/latest"
12 | RESOURCES_DIR="$ARRAKIS_DIR/resources"
13 | RESOURCES_BIN_DIR="$RESOURCES_DIR/bin"
14 | OUT_DIR="$ARRAKIS_DIR/out"
15 | CONFIG_FILE="$ARRAKIS_DIR/config.yaml"
16 | INSTALL_IMAGES_SCRIPT="$ARRAKIS_DIR/install-images.py"
17 |
18 | # Print colored message
19 | print_message() {
20 | echo -e "${GREEN}[Arrakis Setup]${NC} $1"
21 | }
22 |
23 | print_warning() {
24 | echo -e "${YELLOW}[Warning]${NC} $1"
25 | }
26 |
27 | # Function to download a file
28 | download_file() {
29 | local url="$1"
30 | local destination="$2"
31 | local description="$3"
32 |
33 | print_message "Downloading $description from $url..."
34 | curl -L -o "$destination" "$url"
35 |
36 | if [ $? -eq 0 ]; then
37 | print_message "$description downloaded successfully to $destination"
38 | else
39 | print_warning "Failed to download $description. Please check the URL and try again."
40 | exit 1
41 | fi
42 | }
43 |
44 | # Function to make a file executable
45 | make_executable() {
46 | local file="$1"
47 | chmod +x "$file"
48 | print_message "Made $file executable"
49 | }
50 |
51 | # Create arrakis-prebuilt directory
52 | print_message "Creating Arrakis directory structure..."
53 | mkdir -p "$ARRAKIS_DIR"
54 | mkdir -p "$RESOURCES_DIR"
55 | mkdir -p "$RESOURCES_BIN_DIR"
56 | mkdir -p "$OUT_DIR"
57 |
58 |
59 | # Get the latest release URL
60 | # Check if a release version is provided as an argument
61 | if [ -n "${1:-}" ]; then
62 | RELEASE_TAG="$1"
63 | print_message "Using specified release version: $RELEASE_TAG"
64 | else
65 | print_message "No release version specified. Determining latest release using original method..."
66 | RELEASE_TAG_LATEST=$(curl -s -L "$LATEST_RELEASE_URL" | grep -o "tag/release-[0-9]*" | head -1 | cut -d'/' -f2)
67 |
68 | if [ -z "$RELEASE_TAG_LATEST" ]; then
69 | print_warning "Could not determine the latest release tag using the original method. Please check your network connection or GitHub status, or specify a release version manually (e.g., ./setup.sh release-33)."
70 | print_warning "Exiting due to inability to determine release tag."
71 | exit 1
72 | fi
73 | RELEASE_TAG="$RELEASE_TAG_LATEST"
74 | print_message "Using latest release version determined: $RELEASE_TAG"
75 | fi
76 | RELEASE_URL="https://github.com/abshkbh/arrakis/releases/download/$RELEASE_TAG"
77 |
78 | # Download arrakis-restserver
79 | download_file "$RELEASE_URL/arrakis-restserver" "$ARRAKIS_DIR/arrakis-restserver" "Arrakis REST Server"
80 | make_executable "$ARRAKIS_DIR/arrakis-restserver"
81 |
82 | # Download arrakis-client
83 | download_file "$RELEASE_URL/arrakis-client" "$ARRAKIS_DIR/arrakis-client" "Arrakis Client"
84 | make_executable "$ARRAKIS_DIR/arrakis-client"
85 |
86 | # Download and extract arrakis-guestrootfs-ext4.img.tar.gz
87 | print_message "Downloading and extracting Arrakis Guest Rootfs..."
88 | download_file "$RELEASE_URL/arrakis-guestrootfs-ext4.img.tar.gz" "$OUT_DIR/arrakis-guestrootfs-ext4.img.tar.gz" "Compressed Arrakis Guest Rootfs"
89 |
90 | print_message "Extracting rootfs image..."
91 | tar -xzf "$OUT_DIR/arrakis-guestrootfs-ext4.img.tar.gz" -C "$OUT_DIR"
92 | print_message "Extracted rootfs image to $OUT_DIR/arrakis-guestrootfs-ext4.img"
93 |
94 | # Download initramfs.cpio.gz
95 | download_file "$RELEASE_URL/initramfs.cpio.gz" "$OUT_DIR/initramfs.cpio.gz" "Initramfs image"
96 |
97 | # Download config.yaml
98 | download_file "$RELEASE_URL/config.yaml" "$CONFIG_FILE" "Configuration file"
99 |
100 | # Download VERSION file
101 | download_file "$RELEASE_URL/VERSION" "$ARRAKIS_DIR/VERSION" "Version information file"
102 |
103 | # Function to display version information
104 | display_version_info() {
105 | local version_file="$ARRAKIS_DIR/VERSION"
106 |
107 | if [ -f "$version_file" ]; then
108 | print_message "Installed Arrakis Version Information:"
109 | echo -e "${GREEN}================================${NC}"
110 | while IFS='=' read -r key value; do
111 | if [ -n "$key" ] && [ -n "$value" ]; then
112 | printf "${YELLOW}%-15s${NC}: %s\n" "$key" "$value"
113 | fi
114 | done < "$version_file"
115 | echo -e "${GREEN}================================${NC}"
116 | echo ""
117 | print_message "To check if you have the latest version, compare this with:"
118 | print_message "https://github.com/abshkbh/arrakis/releases/latest"
119 | else
120 | print_warning "VERSION file not found. Version information unavailable."
121 | fi
122 | }
123 |
124 | # Display version information
125 | display_version_info
126 |
127 | # Download install-images.py
128 | print_message "Downloading install-images.py script..."
129 | curl -L -o "$INSTALL_IMAGES_SCRIPT" "https://raw.githubusercontent.com/abshkbh/arrakis/main/setup/install-images.py"
130 | chmod +x "$INSTALL_IMAGES_SCRIPT"
131 |
132 | # Run install-images.py to download required images
133 | print_message "Running install-images.py to download required images..."
134 | cd "$ARRAKIS_DIR" && ./$(basename "$INSTALL_IMAGES_SCRIPT")
135 |
136 | print_message "Setup completed successfully!"
137 | print_message "You can now run the Arrakis REST server with:"
138 | print_message "cd "$ARRAKIS_DIR" && ./arrakis-restserver"
139 | print_message "And use the client with:"
140 | print_message "cd "$ARRAKIS_DIR" && ./arrakis-client"
141 |
--------------------------------------------------------------------------------