clonebox 0.1.1__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
clonebox-0.1.1/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: clonebox
3
+ Version: 0.1.1
4
+ Summary: Clone your workstation environment to an isolated VM with selective apps, paths and services
5
+ Author: CloneBox Team
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/wronai/clonebox
8
+ Project-URL: Repository, https://github.com/wronai/clonebox
9
+ Project-URL: Issues, https://github.com/wronai/clonebox/issues
10
+ Keywords: vm,virtualization,libvirt,clone,workstation,qemu,kvm
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: System :: Systems Administration
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: libvirt-python>=9.0.0
29
+ Requires-Dist: rich>=13.0.0
30
+ Requires-Dist: questionary>=2.0.0
31
+ Requires-Dist: psutil>=5.9.0
32
+ Requires-Dist: pyyaml>=6.0
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
35
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
36
+ Requires-Dist: black>=23.0.0; extra == "dev"
37
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # clonebox
@@ -0,0 +1 @@
1
+ # clonebox
@@ -0,0 +1,66 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "clonebox"
7
+ version = "0.1.1"
8
+ description = "Clone your workstation environment to an isolated VM with selective apps, paths and services"
9
+ readme = "README.md"
10
+ license = {text = "MIT"}
11
+ requires-python = ">=3.8"
12
+ authors = [
13
+ {name = "CloneBox Team"}
14
+ ]
15
+ keywords = ["vm", "virtualization", "libvirt", "clone", "workstation", "qemu", "kvm"]
16
+ classifiers = [
17
+ "Development Status :: 4 - Beta",
18
+ "Environment :: Console",
19
+ "Intended Audience :: Developers",
20
+ "Intended Audience :: System Administrators",
21
+ "License :: OSI Approved :: MIT License",
22
+ "Operating System :: POSIX :: Linux",
23
+ "Programming Language :: Python :: 3",
24
+ "Programming Language :: Python :: 3.8",
25
+ "Programming Language :: Python :: 3.9",
26
+ "Programming Language :: Python :: 3.10",
27
+ "Programming Language :: Python :: 3.11",
28
+ "Programming Language :: Python :: 3.12",
29
+ "Topic :: System :: Systems Administration",
30
+ "Topic :: Utilities",
31
+ ]
32
+
33
+ dependencies = [
34
+ "libvirt-python>=9.0.0",
35
+ "rich>=13.0.0",
36
+ "questionary>=2.0.0",
37
+ "psutil>=5.9.0",
38
+ "pyyaml>=6.0",
39
+ ]
40
+
41
+ [project.optional-dependencies]
42
+ dev = [
43
+ "pytest>=7.0.0",
44
+ "pytest-cov>=4.0.0",
45
+ "black>=23.0.0",
46
+ "ruff>=0.1.0",
47
+ ]
48
+
49
+ [project.scripts]
50
+ clonebox = "clonebox.cli:main"
51
+
52
+ [project.urls]
53
+ Homepage = "https://github.com/wronai/clonebox"
54
+ Repository = "https://github.com/wronai/clonebox"
55
+ Issues = "https://github.com/wronai/clonebox/issues"
56
+
57
+ [tool.setuptools.packages.find]
58
+ where = ["src"]
59
+
60
+ [tool.black]
61
+ line-length = 100
62
+ target-version = ["py38", "py39", "py310", "py311", "py312"]
63
+
64
+ [tool.ruff]
65
+ line-length = 100
66
+ select = ["E", "F", "W", "I", "N", "UP", "B", "C4"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,14 @@
1
+ """
2
+ CloneBox - Clone your workstation environment to an isolated VM.
3
+
4
+ Selectively clone applications, paths and services to a new virtual machine
5
+ with bind mounts instead of full disk cloning.
6
+ """
7
+
8
+ __version__ = "0.1.0"
9
+ __author__ = "CloneBox Team"
10
+
11
+ from clonebox.cloner import SelectiveVMCloner
12
+ from clonebox.detector import SystemDetector
13
+
14
+ __all__ = ["SelectiveVMCloner", "SystemDetector", "__version__"]
@@ -0,0 +1,419 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ SelectiveVMCloner - Creates isolated VMs with only selected apps/paths/services.
4
+ """
5
+
6
+ import os
7
+ import uuid
8
+ import time
9
+ import subprocess
10
+ import xml.etree.ElementTree as ET
11
+ from pathlib import Path
12
+ from typing import Optional
13
+ from dataclasses import dataclass, field
14
+
15
+ try:
16
+ import libvirt
17
+ except ImportError:
18
+ libvirt = None
19
+
20
+
21
+ @dataclass
22
+ class VMConfig:
23
+ """Configuration for the VM to create."""
24
+
25
+ name: str = "clonebox-vm"
26
+ ram_mb: int = 4096
27
+ vcpus: int = 4
28
+ disk_size_gb: int = 10
29
+ gui: bool = True
30
+ base_image: Optional[str] = None
31
+ paths: dict = field(default_factory=dict)
32
+ packages: list = field(default_factory=list)
33
+ services: list = field(default_factory=list)
34
+
35
+ def to_dict(self) -> dict:
36
+ return {
37
+ "paths": self.paths,
38
+ "packages": self.packages,
39
+ "services": self.services,
40
+ }
41
+
42
+
43
+ class SelectiveVMCloner:
44
+ """
45
+ Creates VMs with only selected applications, paths and services.
46
+ Uses bind mounts instead of full disk cloning.
47
+ """
48
+
49
+ def __init__(self, conn_uri: str = "qemu:///system"):
50
+ self.conn_uri = conn_uri
51
+ self.conn = None
52
+ self._connect()
53
+
54
+ def _connect(self):
55
+ """Connect to libvirt."""
56
+ if libvirt is None:
57
+ raise ImportError(
58
+ "libvirt-python is required. Install with: pip install libvirt-python\n"
59
+ "Also ensure libvirt is installed: sudo apt install libvirt-daemon-system"
60
+ )
61
+
62
+ self.conn = libvirt.open(self.conn_uri)
63
+ if self.conn is None:
64
+ raise ConnectionError(f"Cannot connect to {self.conn_uri}")
65
+
66
+ def check_prerequisites(self) -> dict:
67
+ """Check system prerequisites for VM creation."""
68
+ checks = {
69
+ "libvirt_connected": False,
70
+ "kvm_available": False,
71
+ "default_network": False,
72
+ "images_dir_writable": False,
73
+ }
74
+
75
+ # Check libvirt connection
76
+ if self.conn and self.conn.isAlive():
77
+ checks["libvirt_connected"] = True
78
+
79
+ # Check KVM
80
+ checks["kvm_available"] = Path("/dev/kvm").exists()
81
+
82
+ # Check default network
83
+ try:
84
+ net = self.conn.networkLookupByName("default")
85
+ checks["default_network"] = net.isActive() == 1
86
+ except libvirt.libvirtError:
87
+ pass
88
+
89
+ # Check images directory
90
+ images_dir = Path("/var/lib/libvirt/images")
91
+ checks["images_dir_writable"] = images_dir.exists() and os.access(images_dir, os.W_OK)
92
+
93
+ return checks
94
+
95
+ def create_vm(self, config: VMConfig, console=None) -> str:
96
+ """
97
+ Create a VM with only selected applications/paths.
98
+
99
+ Args:
100
+ config: VMConfig with paths, packages, services
101
+ console: Rich console for output (optional)
102
+
103
+ Returns:
104
+ UUID of created VM
105
+ """
106
+ def log(msg):
107
+ if console:
108
+ console.print(msg)
109
+ else:
110
+ print(msg)
111
+
112
+ vm_dir = Path(f"/var/lib/libvirt/images/{config.name}")
113
+ vm_dir.mkdir(parents=True, exist_ok=True)
114
+
115
+ # Create root disk
116
+ root_disk = vm_dir / "root.qcow2"
117
+
118
+ if config.base_image and Path(config.base_image).exists():
119
+ # Use backing file for faster creation
120
+ log(f"[cyan]📀 Creating disk with backing file: {config.base_image}[/]")
121
+ cmd = [
122
+ "qemu-img", "create", "-f", "qcow2",
123
+ "-b", config.base_image, "-F", "qcow2",
124
+ str(root_disk), f"{config.disk_size_gb}G"
125
+ ]
126
+ else:
127
+ # Create empty disk
128
+ log(f"[cyan]📀 Creating empty {config.disk_size_gb}GB disk...[/]")
129
+ cmd = [
130
+ "qemu-img", "create", "-f", "qcow2",
131
+ str(root_disk), f"{config.disk_size_gb}G"
132
+ ]
133
+
134
+ subprocess.run(cmd, check=True, capture_output=True)
135
+
136
+ # Create cloud-init ISO if packages/services specified
137
+ cloudinit_iso = None
138
+ if config.packages or config.services:
139
+ cloudinit_iso = self._create_cloudinit_iso(vm_dir, config)
140
+ log(f"[cyan]☁️ Created cloud-init ISO with {len(config.packages)} packages[/]")
141
+
142
+ # Generate VM XML
143
+ vm_xml = self._generate_vm_xml(config, root_disk, cloudinit_iso)
144
+
145
+ # Define and create VM
146
+ log(f"[cyan]🔧 Defining VM '{config.name}'...[/]")
147
+ vm = self.conn.defineXML(vm_xml)
148
+
149
+ log(f"[green]✅ VM '{config.name}' created successfully![/]")
150
+ log(f"[dim] UUID: {vm.UUIDString()}[/]")
151
+
152
+ return vm.UUIDString()
153
+
154
+ def _generate_vm_xml(
155
+ self,
156
+ config: VMConfig,
157
+ root_disk: Path,
158
+ cloudinit_iso: Optional[Path]
159
+ ) -> str:
160
+ """Generate libvirt XML for the VM."""
161
+
162
+ root = ET.Element("domain", type="kvm")
163
+
164
+ # Basic metadata
165
+ ET.SubElement(root, "name").text = config.name
166
+ ET.SubElement(root, "uuid").text = str(uuid.uuid4())
167
+ ET.SubElement(root, "memory", unit="MiB").text = str(config.ram_mb)
168
+ ET.SubElement(root, "currentMemory", unit="MiB").text = str(config.ram_mb)
169
+ ET.SubElement(root, "vcpu", placement="static").text = str(config.vcpus)
170
+
171
+ # OS configuration
172
+ os_elem = ET.SubElement(root, "os")
173
+ ET.SubElement(os_elem, "type", arch="x86_64", machine="q35").text = "hvm"
174
+ ET.SubElement(os_elem, "boot", dev="hd")
175
+
176
+ # Features
177
+ features = ET.SubElement(root, "features")
178
+ ET.SubElement(features, "acpi")
179
+ ET.SubElement(features, "apic")
180
+
181
+ # CPU
182
+ ET.SubElement(root, "cpu", mode="host-passthrough", check="none")
183
+
184
+ # Devices
185
+ devices = ET.SubElement(root, "devices")
186
+
187
+ # Emulator
188
+ ET.SubElement(devices, "emulator").text = "/usr/bin/qemu-system-x86_64"
189
+
190
+ # Root disk
191
+ disk = ET.SubElement(devices, "disk", type="file", device="disk")
192
+ ET.SubElement(disk, "driver", name="qemu", type="qcow2", cache="writeback")
193
+ ET.SubElement(disk, "source", file=str(root_disk))
194
+ ET.SubElement(disk, "target", dev="vda", bus="virtio")
195
+
196
+ # Cloud-init ISO
197
+ if cloudinit_iso:
198
+ cdrom = ET.SubElement(devices, "disk", type="file", device="cdrom")
199
+ ET.SubElement(cdrom, "driver", name="qemu", type="raw")
200
+ ET.SubElement(cdrom, "source", file=str(cloudinit_iso))
201
+ ET.SubElement(cdrom, "target", dev="sda", bus="sata")
202
+ ET.SubElement(cdrom, "readonly")
203
+
204
+ # 9p filesystem mounts (bind mounts from host)
205
+ for idx, (host_path, guest_tag) in enumerate(config.paths.items()):
206
+ if Path(host_path).exists():
207
+ fs = ET.SubElement(devices, "filesystem", type="mount", accessmode="passthrough")
208
+ ET.SubElement(fs, "driver", type="path", wrpolicy="immediate")
209
+ ET.SubElement(fs, "source", dir=host_path)
210
+ # Use simple tag names for 9p mounts
211
+ tag = f"mount{idx}"
212
+ ET.SubElement(fs, "target", dir=tag)
213
+
214
+ # Network interface
215
+ iface = ET.SubElement(devices, "interface", type="network")
216
+ ET.SubElement(iface, "source", network="default")
217
+ ET.SubElement(iface, "model", type="virtio")
218
+
219
+ # Serial console
220
+ serial = ET.SubElement(devices, "serial", type="pty")
221
+ ET.SubElement(serial, "target", port="0")
222
+
223
+ console_elem = ET.SubElement(devices, "console", type="pty")
224
+ ET.SubElement(console_elem, "target", type="serial", port="0")
225
+
226
+ # Graphics (SPICE)
227
+ if config.gui:
228
+ graphics = ET.SubElement(
229
+ devices, "graphics",
230
+ type="spice",
231
+ autoport="yes",
232
+ listen="127.0.0.1"
233
+ )
234
+ ET.SubElement(graphics, "listen", type="address", address="127.0.0.1")
235
+
236
+ # Video
237
+ video = ET.SubElement(devices, "video")
238
+ ET.SubElement(video, "model", type="virtio", heads="1", primary="yes")
239
+
240
+ # Input devices
241
+ ET.SubElement(devices, "input", type="tablet", bus="usb")
242
+ ET.SubElement(devices, "input", type="keyboard", bus="usb")
243
+
244
+ # Channel for guest agent
245
+ channel = ET.SubElement(devices, "channel", type="unix")
246
+ ET.SubElement(channel, "target", type="virtio", name="org.qemu.guest_agent.0")
247
+
248
+ # Memory balloon
249
+ memballoon = ET.SubElement(devices, "memballoon", model="virtio")
250
+ ET.SubElement(memballoon, "address", type="pci", domain="0x0000",
251
+ bus="0x00", slot="0x08", function="0x0")
252
+
253
+ return ET.tostring(root, encoding="unicode")
254
+
255
+ def _create_cloudinit_iso(self, vm_dir: Path, config: VMConfig) -> Path:
256
+ """Create cloud-init ISO with user-data and meta-data."""
257
+
258
+ cloudinit_dir = vm_dir / "cloud-init"
259
+ cloudinit_dir.mkdir(exist_ok=True)
260
+
261
+ # Meta-data
262
+ meta_data = f"instance-id: {config.name}\nlocal-hostname: {config.name}\n"
263
+ (cloudinit_dir / "meta-data").write_text(meta_data)
264
+
265
+ # Generate mount commands for 9p filesystems
266
+ mount_commands = []
267
+ for idx, (host_path, guest_path) in enumerate(config.paths.items()):
268
+ if Path(host_path).exists():
269
+ tag = f"mount{idx}"
270
+ mount_commands.append(f" - mkdir -p {guest_path}")
271
+ mount_commands.append(
272
+ f" - mount -t 9p -o trans=virtio,version=9p2000.L {tag} {guest_path}"
273
+ )
274
+
275
+ # User-data
276
+ packages_yaml = "\n".join(f" - {pkg}" for pkg in config.packages) if config.packages else ""
277
+ services_enable = "\n".join(
278
+ f" - systemctl enable --now {svc}" for svc in config.services
279
+ ) if config.services else ""
280
+ mounts_yaml = "\n".join(mount_commands) if mount_commands else ""
281
+
282
+ user_data = f"""#cloud-config
283
+ hostname: {config.name}
284
+ manage_etc_hosts: true
285
+
286
+ packages:
287
+ {packages_yaml}
288
+
289
+ runcmd:
290
+ {services_enable}
291
+ {mounts_yaml}
292
+ - echo "CloneBox VM ready!" > /var/log/clonebox-ready
293
+
294
+ final_message: "CloneBox VM is ready after $UPTIME seconds"
295
+ """
296
+ (cloudinit_dir / "user-data").write_text(user_data)
297
+
298
+ # Create ISO
299
+ iso_path = vm_dir / "cloud-init.iso"
300
+ subprocess.run([
301
+ "genisoimage", "-output", str(iso_path),
302
+ "-volid", "cidata", "-joliet", "-rock",
303
+ str(cloudinit_dir / "user-data"),
304
+ str(cloudinit_dir / "meta-data")
305
+ ], check=True, capture_output=True)
306
+
307
+ return iso_path
308
+
309
+ def start_vm(self, vm_name: str, open_viewer: bool = True, console=None) -> bool:
310
+ """Start a VM and optionally open virt-viewer."""
311
+
312
+ def log(msg):
313
+ if console:
314
+ console.print(msg)
315
+ else:
316
+ print(msg)
317
+
318
+ try:
319
+ vm = self.conn.lookupByName(vm_name)
320
+ except libvirt.libvirtError:
321
+ log(f"[red]❌ VM '{vm_name}' not found[/]")
322
+ return False
323
+
324
+ if vm.isActive():
325
+ log(f"[yellow]⚠️ VM '{vm_name}' is already running[/]")
326
+ else:
327
+ log(f"[cyan]🚀 Starting VM '{vm_name}'...[/]")
328
+ vm.create()
329
+ log(f"[green]✅ VM started![/]")
330
+
331
+ if open_viewer:
332
+ log(f"[cyan]🖥️ Opening virt-viewer...[/]")
333
+ subprocess.Popen(
334
+ ["virt-viewer", "-c", self.conn_uri, vm_name],
335
+ stdout=subprocess.DEVNULL,
336
+ stderr=subprocess.DEVNULL
337
+ )
338
+
339
+ return True
340
+
341
+ def stop_vm(self, vm_name: str, force: bool = False, console=None) -> bool:
342
+ """Stop a VM."""
343
+
344
+ def log(msg):
345
+ if console:
346
+ console.print(msg)
347
+ else:
348
+ print(msg)
349
+
350
+ try:
351
+ vm = self.conn.lookupByName(vm_name)
352
+ except libvirt.libvirtError:
353
+ log(f"[red]❌ VM '{vm_name}' not found[/]")
354
+ return False
355
+
356
+ if not vm.isActive():
357
+ log(f"[yellow]⚠️ VM '{vm_name}' is not running[/]")
358
+ return True
359
+
360
+ if force:
361
+ log(f"[yellow]⚡ Force stopping VM '{vm_name}'...[/]")
362
+ vm.destroy()
363
+ else:
364
+ log(f"[cyan]🛑 Shutting down VM '{vm_name}'...[/]")
365
+ vm.shutdown()
366
+
367
+ log(f"[green]✅ VM stopped![/]")
368
+ return True
369
+
370
+ def delete_vm(self, vm_name: str, delete_storage: bool = True, console=None) -> bool:
371
+ """Delete a VM and optionally its storage."""
372
+
373
+ def log(msg):
374
+ if console:
375
+ console.print(msg)
376
+ else:
377
+ print(msg)
378
+
379
+ try:
380
+ vm = self.conn.lookupByName(vm_name)
381
+ except libvirt.libvirtError:
382
+ log(f"[red]❌ VM '{vm_name}' not found[/]")
383
+ return False
384
+
385
+ # Stop if running
386
+ if vm.isActive():
387
+ vm.destroy()
388
+
389
+ # Undefine
390
+ vm.undefine()
391
+ log(f"[green]✅ VM '{vm_name}' undefined[/]")
392
+
393
+ # Delete storage
394
+ if delete_storage:
395
+ vm_dir = Path(f"/var/lib/libvirt/images/{vm_name}")
396
+ if vm_dir.exists():
397
+ import shutil
398
+ shutil.rmtree(vm_dir)
399
+ log(f"[green]🗑️ Storage deleted: {vm_dir}[/]")
400
+
401
+ return True
402
+
403
+ def list_vms(self) -> list:
404
+ """List all VMs."""
405
+ vms = []
406
+ for vm_id in self.conn.listDomainsID():
407
+ vm = self.conn.lookupByID(vm_id)
408
+ vms.append({"name": vm.name(), "state": "running", "uuid": vm.UUIDString()})
409
+
410
+ for name in self.conn.listDefinedDomains():
411
+ vm = self.conn.lookupByName(name)
412
+ vms.append({"name": name, "state": "stopped", "uuid": vm.UUIDString()})
413
+
414
+ return vms
415
+
416
+ def close(self):
417
+ """Close libvirt connection."""
418
+ if self.conn:
419
+ self.conn.close()
@@ -0,0 +1,324 @@
1
+ #!/usr/bin/env python3
2
+ """
3
+ SystemDetector - Detects running services, applications and important paths.
4
+ """
5
+
6
+ import os
7
+ import subprocess
8
+ import pwd
9
+ from pathlib import Path
10
+ from dataclasses import dataclass, field
11
+ from typing import Optional
12
+
13
+ import psutil
14
+
15
+
16
+ @dataclass
17
+ class DetectedService:
18
+ """A detected systemd service."""
19
+ name: str
20
+ status: str # running, stopped, failed
21
+ description: str = ""
22
+ enabled: bool = False
23
+
24
+
25
+ @dataclass
26
+ class DetectedApplication:
27
+ """A detected running application."""
28
+ name: str
29
+ pid: int
30
+ cmdline: str
31
+ exe: str
32
+ working_dir: str = ""
33
+ memory_mb: float = 0.0
34
+
35
+
36
+ @dataclass
37
+ class DetectedPath:
38
+ """A detected important path."""
39
+ path: str
40
+ type: str # config, data, project, home
41
+ size_mb: float = 0.0
42
+ description: str = ""
43
+
44
+
45
+ @dataclass
46
+ class SystemSnapshot:
47
+ """Complete snapshot of detected system state."""
48
+ services: list = field(default_factory=list)
49
+ applications: list = field(default_factory=list)
50
+ paths: list = field(default_factory=list)
51
+
52
+ @property
53
+ def running_services(self) -> list:
54
+ return [s for s in self.services if s.status == "running"]
55
+
56
+ @property
57
+ def running_apps(self) -> list:
58
+ return self.applications
59
+
60
+
61
+ class SystemDetector:
62
+ """Detects running services, applications and important paths on the system."""
63
+
64
+ # Common development/server services to look for
65
+ INTERESTING_SERVICES = [
66
+ "docker", "containerd", "podman",
67
+ "nginx", "apache2", "httpd", "caddy",
68
+ "postgresql", "mysql", "mariadb", "mongodb", "redis", "memcached",
69
+ "elasticsearch", "kibana", "grafana", "prometheus",
70
+ "jenkins", "gitlab-runner",
71
+ "sshd", "rsync",
72
+ "rabbitmq-server", "kafka",
73
+ "nodejs", "pm2",
74
+ "supervisor", "systemd-resolved",
75
+ "cups", "bluetooth", "NetworkManager",
76
+ "libvirtd", "virtlogd",
77
+ ]
78
+
79
+ # Interesting process names
80
+ INTERESTING_PROCESSES = [
81
+ "python", "python3", "node", "npm", "yarn", "pnpm",
82
+ "java", "gradle", "mvn",
83
+ "go", "cargo", "rustc",
84
+ "docker", "docker-compose", "podman",
85
+ "nginx", "apache", "httpd",
86
+ "postgres", "mysql", "mongod", "redis-server",
87
+ "code", "code-server", "cursor",
88
+ "vim", "nvim", "emacs",
89
+ "firefox", "chrome", "chromium",
90
+ "jupyter", "jupyter-lab",
91
+ "gunicorn", "uvicorn", "flask", "django",
92
+ "webpack", "vite", "esbuild",
93
+ "tmux", "screen",
94
+ ]
95
+
96
+ def __init__(self):
97
+ self.user = pwd.getpwuid(os.getuid()).pw_name
98
+ self.home = Path.home()
99
+
100
+ def detect_all(self) -> SystemSnapshot:
101
+ """Detect all services, applications and paths."""
102
+ return SystemSnapshot(
103
+ services=self.detect_services(),
104
+ applications=self.detect_applications(),
105
+ paths=self.detect_paths(),
106
+ )
107
+
108
+ def detect_services(self) -> list:
109
+ """Detect systemd services."""
110
+ services = []
111
+
112
+ try:
113
+ # Get all services
114
+ result = subprocess.run(
115
+ ["systemctl", "list-units", "--type=service", "--all", "--no-pager", "--plain"],
116
+ capture_output=True, text=True, timeout=10
117
+ )
118
+
119
+ for line in result.stdout.strip().split("\n")[1:]: # Skip header
120
+ parts = line.split()
121
+ if len(parts) >= 4:
122
+ name = parts[0].replace(".service", "")
123
+
124
+ # Filter to interesting services
125
+ if any(interesting in name.lower() for interesting in self.INTERESTING_SERVICES):
126
+ status = "running" if parts[3] == "running" else parts[3]
127
+
128
+ # Get description
129
+ desc = " ".join(parts[4:]) if len(parts) > 4 else ""
130
+
131
+ # Check if enabled
132
+ enabled = False
133
+ try:
134
+ en_result = subprocess.run(
135
+ ["systemctl", "is-enabled", name],
136
+ capture_output=True, text=True, timeout=5
137
+ )
138
+ enabled = en_result.stdout.strip() == "enabled"
139
+ except:
140
+ pass
141
+
142
+ services.append(DetectedService(
143
+ name=name,
144
+ status=status,
145
+ description=desc,
146
+ enabled=enabled
147
+ ))
148
+ except Exception:
149
+ pass
150
+
151
+ return services
152
+
153
+ def detect_applications(self) -> list:
154
+ """Detect running applications/processes."""
155
+ applications = []
156
+ seen_names = set()
157
+
158
+ for proc in psutil.process_iter(['pid', 'name', 'cmdline', 'exe', 'cwd', 'memory_info']):
159
+ try:
160
+ info = proc.info
161
+ name = info['name'] or ""
162
+
163
+ # Filter to interesting processes
164
+ if not any(interesting in name.lower() for interesting in self.INTERESTING_PROCESSES):
165
+ continue
166
+
167
+ # Skip duplicates by name (keep first)
168
+ if name in seen_names:
169
+ continue
170
+ seen_names.add(name)
171
+
172
+ cmdline = " ".join(info['cmdline'] or [])[:200]
173
+ exe = info['exe'] or ""
174
+ cwd = info['cwd'] or ""
175
+ mem = (info['memory_info'].rss / 1024 / 1024) if info['memory_info'] else 0
176
+
177
+ applications.append(DetectedApplication(
178
+ name=name,
179
+ pid=info['pid'],
180
+ cmdline=cmdline,
181
+ exe=exe,
182
+ working_dir=cwd,
183
+ memory_mb=round(mem, 1)
184
+ ))
185
+ except (psutil.NoSuchProcess, psutil.AccessDenied, psutil.ZombieProcess):
186
+ continue
187
+
188
+ # Sort by memory usage
189
+ applications.sort(key=lambda x: x.memory_mb, reverse=True)
190
+ return applications
191
+
192
+ def detect_paths(self) -> list:
193
+ """Detect important paths (projects, configs, data)."""
194
+ paths = []
195
+
196
+ # User home subdirectories
197
+ important_home_dirs = [
198
+ ("projects", "project"),
199
+ ("workspace", "project"),
200
+ ("code", "project"),
201
+ ("dev", "project"),
202
+ ("work", "project"),
203
+ ("repos", "project"),
204
+ ("github", "project"),
205
+ ("gitlab", "project"),
206
+ (".config", "config"),
207
+ (".local/share", "data"),
208
+ (".ssh", "config"),
209
+ (".docker", "config"),
210
+ (".kube", "config"),
211
+ (".npm", "config"),
212
+ (".cargo", "config"),
213
+ (".rustup", "data"),
214
+ (".pyenv", "data"),
215
+ (".nvm", "data"),
216
+ (".vscode", "config"),
217
+ ("Documents", "data"),
218
+ ("Downloads", "data"),
219
+ ]
220
+
221
+ for dirname, path_type in important_home_dirs:
222
+ full_path = self.home / dirname
223
+ if full_path.exists() and full_path.is_dir():
224
+ size = self._get_dir_size(full_path, max_depth=1)
225
+ paths.append(DetectedPath(
226
+ path=str(full_path),
227
+ type=path_type,
228
+ size_mb=round(size / 1024 / 1024, 1),
229
+ description=f"User {dirname}"
230
+ ))
231
+
232
+ # System paths that might be interesting
233
+ system_paths = [
234
+ ("/var/www", "data", "Web server root"),
235
+ ("/var/lib/docker", "data", "Docker data"),
236
+ ("/var/lib/postgresql", "data", "PostgreSQL data"),
237
+ ("/var/lib/mysql", "data", "MySQL data"),
238
+ ("/opt", "data", "Optional software"),
239
+ ("/etc/nginx", "config", "Nginx config"),
240
+ ("/etc/apache2", "config", "Apache config"),
241
+ ]
242
+
243
+ for path, path_type, desc in system_paths:
244
+ p = Path(path)
245
+ if p.exists():
246
+ size = self._get_dir_size(p, max_depth=1)
247
+ paths.append(DetectedPath(
248
+ path=path,
249
+ type=path_type,
250
+ size_mb=round(size / 1024 / 1024, 1),
251
+ description=desc
252
+ ))
253
+
254
+ # Detect project directories (with .git, package.json, etc.)
255
+ project_markers = [".git", "package.json", "Cargo.toml", "go.mod", "pyproject.toml", "setup.py"]
256
+ for search_dir in [self.home / "projects", self.home / "code", self.home / "github", self.home]:
257
+ if search_dir.exists():
258
+ for item in search_dir.iterdir():
259
+ if item.is_dir() and not item.name.startswith("."):
260
+ for marker in project_markers:
261
+ if (item / marker).exists():
262
+ size = self._get_dir_size(item, max_depth=2)
263
+ if str(item) not in [p.path for p in paths]:
264
+ paths.append(DetectedPath(
265
+ path=str(item),
266
+ type="project",
267
+ size_mb=round(size / 1024 / 1024, 1),
268
+ description=f"Project ({marker})"
269
+ ))
270
+ break
271
+
272
+ # Sort by type then path
273
+ paths.sort(key=lambda x: (x.type, x.path))
274
+ return paths
275
+
276
+ def _get_dir_size(self, path: Path, max_depth: int = 2) -> int:
277
+ """Get approximate directory size in bytes."""
278
+ total = 0
279
+ try:
280
+ for item in path.iterdir():
281
+ if item.is_file():
282
+ try:
283
+ total += item.stat().st_size
284
+ except:
285
+ pass
286
+ elif item.is_dir() and max_depth > 0 and not item.is_symlink():
287
+ total += self._get_dir_size(item, max_depth - 1)
288
+ except PermissionError:
289
+ pass
290
+ return total
291
+
292
+ def detect_docker_containers(self) -> list:
293
+ """Detect running Docker containers."""
294
+ containers = []
295
+ try:
296
+ result = subprocess.run(
297
+ ["docker", "ps", "--format", "{{.Names}}\t{{.Image}}\t{{.Status}}"],
298
+ capture_output=True, text=True, timeout=10
299
+ )
300
+ for line in result.stdout.strip().split("\n"):
301
+ if line:
302
+ parts = line.split("\t")
303
+ if len(parts) >= 3:
304
+ containers.append({
305
+ "name": parts[0],
306
+ "image": parts[1],
307
+ "status": parts[2]
308
+ })
309
+ except:
310
+ pass
311
+ return containers
312
+
313
+ def get_system_info(self) -> dict:
314
+ """Get basic system information."""
315
+ return {
316
+ "hostname": os.uname().nodename,
317
+ "user": self.user,
318
+ "home": str(self.home),
319
+ "cpu_count": psutil.cpu_count(),
320
+ "memory_total_gb": round(psutil.virtual_memory().total / 1024 / 1024 / 1024, 1),
321
+ "memory_available_gb": round(psutil.virtual_memory().available / 1024 / 1024 / 1024, 1),
322
+ "disk_total_gb": round(psutil.disk_usage("/").total / 1024 / 1024 / 1024, 1),
323
+ "disk_free_gb": round(psutil.disk_usage("/").free / 1024 / 1024 / 1024, 1),
324
+ }
@@ -0,0 +1,40 @@
1
+ Metadata-Version: 2.4
2
+ Name: clonebox
3
+ Version: 0.1.1
4
+ Summary: Clone your workstation environment to an isolated VM with selective apps, paths and services
5
+ Author: CloneBox Team
6
+ License: MIT
7
+ Project-URL: Homepage, https://github.com/wronai/clonebox
8
+ Project-URL: Repository, https://github.com/wronai/clonebox
9
+ Project-URL: Issues, https://github.com/wronai/clonebox/issues
10
+ Keywords: vm,virtualization,libvirt,clone,workstation,qemu,kvm
11
+ Classifier: Development Status :: 4 - Beta
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: Intended Audience :: System Administrators
15
+ Classifier: License :: OSI Approved :: MIT License
16
+ Classifier: Operating System :: POSIX :: Linux
17
+ Classifier: Programming Language :: Python :: 3
18
+ Classifier: Programming Language :: Python :: 3.8
19
+ Classifier: Programming Language :: Python :: 3.9
20
+ Classifier: Programming Language :: Python :: 3.10
21
+ Classifier: Programming Language :: Python :: 3.11
22
+ Classifier: Programming Language :: Python :: 3.12
23
+ Classifier: Topic :: System :: Systems Administration
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.8
26
+ Description-Content-Type: text/markdown
27
+ License-File: LICENSE
28
+ Requires-Dist: libvirt-python>=9.0.0
29
+ Requires-Dist: rich>=13.0.0
30
+ Requires-Dist: questionary>=2.0.0
31
+ Requires-Dist: psutil>=5.9.0
32
+ Requires-Dist: pyyaml>=6.0
33
+ Provides-Extra: dev
34
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
35
+ Requires-Dist: pytest-cov>=4.0.0; extra == "dev"
36
+ Requires-Dist: black>=23.0.0; extra == "dev"
37
+ Requires-Dist: ruff>=0.1.0; extra == "dev"
38
+ Dynamic: license-file
39
+
40
+ # clonebox
@@ -0,0 +1,12 @@
1
+ LICENSE
2
+ README.md
3
+ pyproject.toml
4
+ src/clonebox/__init__.py
5
+ src/clonebox/cloner.py
6
+ src/clonebox/detector.py
7
+ src/clonebox.egg-info/PKG-INFO
8
+ src/clonebox.egg-info/SOURCES.txt
9
+ src/clonebox.egg-info/dependency_links.txt
10
+ src/clonebox.egg-info/entry_points.txt
11
+ src/clonebox.egg-info/requires.txt
12
+ src/clonebox.egg-info/top_level.txt
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ clonebox = clonebox.cli:main
@@ -0,0 +1,11 @@
1
+ libvirt-python>=9.0.0
2
+ rich>=13.0.0
3
+ questionary>=2.0.0
4
+ psutil>=5.9.0
5
+ pyyaml>=6.0
6
+
7
+ [dev]
8
+ pytest>=7.0.0
9
+ pytest-cov>=4.0.0
10
+ black>=23.0.0
11
+ ruff>=0.1.0
@@ -0,0 +1 @@
1
+ clonebox