lazyfork 0.0.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.
@@ -0,0 +1,5 @@
1
+ .agent/
2
+ temp/
3
+
4
+ # Python
5
+ **/__pycache__/
lazyfork-0.0.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,214 @@
1
+ Metadata-Version: 2.5
2
+ Name: lazyfork
3
+ Version: 0.0.1
4
+ Summary: Fork a running containerised runtime N ways via CRIU lazy restore
5
+ License: Apache License
6
+ Version 2.0, January 2004
7
+ http://www.apache.org/licenses/
8
+
9
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
10
+
11
+ 1. Definitions.
12
+
13
+ "License" shall mean the terms and conditions for use, reproduction,
14
+ and distribution as defined by Sections 1 through 9 of this document.
15
+
16
+ "Licensor" shall mean the copyright owner or entity authorized by
17
+ the copyright owner that is granting the License.
18
+
19
+ "Legal Entity" shall mean the union of the acting entity and all
20
+ other entities that control, are controlled by, or are under common
21
+ control with that entity. For the purposes of this definition,
22
+ "control" means (i) the power, direct or indirect, to cause the
23
+ direction or management of such entity, whether by contract or
24
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
25
+ outstanding shares, or (iii) beneficial ownership of such entity.
26
+
27
+ "You" (or "Your") shall mean an individual or Legal Entity
28
+ exercising permissions granted by this License.
29
+
30
+ "Source" form shall mean the preferred form for making modifications,
31
+ including but not limited to software source code, documentation
32
+ source, and configuration files.
33
+
34
+ "Object" form shall mean any form resulting from mechanical
35
+ transformation or translation of a Source form, including but
36
+ not limited to compiled object code, generated documentation,
37
+ and conversions to other media types.
38
+
39
+ "Work" shall mean the work of authorship, whether in Source or
40
+ Object form, made available under the License, as indicated by a
41
+ copyright notice that is included in or attached to the work
42
+ (an example is provided in the Appendix below).
43
+
44
+ "Derivative Works" shall mean any work, whether in Source or Object
45
+ form, that is based on (or derived from) the Work and for which the
46
+ editorial revisions, annotations, elaborations, or other modifications
47
+ represent, as a whole, an original work of authorship. For the purposes
48
+ of this License, Derivative Works shall not include works that remain
49
+ separable from, or merely link (or bind by name) to the interfaces of,
50
+ the Work and Derivative Works thereof.
51
+
52
+ "Contribution" shall mean any work of authorship, including
53
+ the original version of the Work and any modifications or additions
54
+ to that Work or Derivative Works thereof, that is intentionally
55
+ submitted to Licensor for inclusion in the Work by the copyright owner
56
+ or by an individual or Legal Entity authorized to submit on behalf of
57
+ the copyright owner. For the purposes of this definition, "submitted"
58
+ means any form of electronic, verbal, or written communication sent
59
+ to the Licensor or its representatives, including but not limited to
60
+ communication on electronic mailing lists, source code control systems,
61
+ and issue tracking systems that are managed by, or on behalf of, the
62
+ Licensor for the purpose of discussing and improving the Work, but
63
+ excluding communication that is conspicuously marked or otherwise
64
+ designated in writing by the copyright owner as "Not a Contribution."
65
+
66
+ "Contributor" shall mean Licensor and any individual or Legal Entity
67
+ on behalf of whom a Contribution has been received by Licensor and
68
+ subsequently incorporated within the Work.
69
+
70
+ 2. Grant of Copyright License. Subject to the terms and conditions of
71
+ this License, each Contributor hereby grants to You a perpetual,
72
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
73
+ copyright license to reproduce, prepare Derivative Works of,
74
+ publicly display, publicly perform, sublicense, and distribute the
75
+ Work and such Derivative Works in Source or Object form.
76
+
77
+ 3. Grant of Patent License. Subject to the terms and conditions of
78
+ this License, each Contributor hereby grants to You a perpetual,
79
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
80
+ (except as stated in this section) patent license to make, have made,
81
+ use, offer to sell, sell, import, and otherwise transfer the Work,
82
+ where such license applies only to those patent claims licensable
83
+ by such Contributor that are necessarily infringed by their
84
+ Contribution(s) alone or by combination of their Contribution(s)
85
+ with the Work to which such Contribution(s) was submitted. If You
86
+ institute patent litigation against any entity (including a
87
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
88
+ or a Contribution incorporated within the Work constitutes direct
89
+ or contributory patent infringement, then any patent licenses
90
+ granted to You under this License for that Work shall terminate
91
+ as of the date such litigation is filed.
92
+
93
+ 4. Redistribution. You may reproduce and distribute copies of the
94
+ Work or Derivative Works thereof in any medium, with or without
95
+ modifications, and in Source or Object form, provided that You
96
+ meet the following conditions:
97
+
98
+ (a) You must give any other recipients of the Work or
99
+ Derivative Works a copy of this License; and
100
+
101
+ (b) You must cause any modified files to carry prominent notices
102
+ stating that You changed the files; and
103
+
104
+ (c) You must retain, in the Source form of any Derivative Works
105
+ that You distribute, all copyright, patent, trademark, and
106
+ attribution notices from the Source form of the Work,
107
+ excluding those notices that do not pertain to any part of
108
+ the Derivative Works; and
109
+
110
+ (d) If the Work includes a "NOTICE" text file as part of its
111
+ distribution, then any Derivative Works that You distribute must
112
+ include a readable copy of the attribution notices contained
113
+ within such NOTICE file, excluding those notices that do not
114
+ pertain to any part of the Derivative Works, in at least one
115
+ of the following places: within a NOTICE text file distributed
116
+ as part of the Derivative Works; within the Source form or
117
+ documentation, if provided along with the Derivative Works; or,
118
+ within a display generated by the Derivative Works, if and
119
+ wherever such third-party notices normally appear. The contents
120
+ of the NOTICE file are for informational purposes only and
121
+ do not modify the License. You may add Your own attribution
122
+ notices within Derivative Works that You distribute, alongside
123
+ or as an addendum to the NOTICE text from the Work, provided
124
+ that such additional attribution notices cannot be construed
125
+ as modifying the License.
126
+
127
+ You may add Your own copyright statement to Your modifications and
128
+ may provide additional or different license terms and conditions
129
+ for use, reproduction, or distribution of Your modifications, or
130
+ for any such Derivative Works as a whole, provided Your use,
131
+ reproduction, and distribution of the Work otherwise complies with
132
+ the conditions stated in this License.
133
+
134
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
135
+ any Contribution intentionally submitted for inclusion in the Work
136
+ by You to the Licensor shall be under the terms and conditions of
137
+ this License, without any additional terms or conditions.
138
+ Notwithstanding the above, nothing herein shall supersede or modify
139
+ the terms of any separate license agreement you may have executed
140
+ with Licensor regarding such Contributions.
141
+
142
+ 6. Trademarks. This License does not grant permission to use the trade
143
+ names, trademarks, service marks, or product names of the Licensor,
144
+ except as required for reasonable and customary use in describing the
145
+ origin of the Work and reproducing the content of the NOTICE file.
146
+
147
+ 7. Disclaimer of Warranty. Unless required by applicable law or
148
+ agreed to in writing, Licensor provides the Work (and each
149
+ Contributor provides its Contributions) on an "AS IS" BASIS,
150
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
151
+ implied, including, without limitation, any warranties or conditions
152
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
153
+ PARTICULAR PURPOSE. You are solely responsible for determining the
154
+ appropriateness of using or redistributing the Work and assume any
155
+ risks associated with Your exercise of permissions under this License.
156
+
157
+ 8. Limitation of Liability. In no event and under no legal theory,
158
+ whether in tort (including negligence), contract, or otherwise,
159
+ unless required by applicable law (such as deliberate and grossly
160
+ negligent acts) or agreed to in writing, shall any Contributor be
161
+ liable to You for damages, including any direct, indirect, special,
162
+ incidental, or consequential damages of any character arising as a
163
+ result of this License or out of the use or inability to use the
164
+ Work (including but not limited to damages for loss of goodwill,
165
+ work stoppage, computer failure or malfunction, or any and all
166
+ other commercial damages or losses), even if such Contributor
167
+ has been advised of the possibility of such damages.
168
+
169
+ 9. Accepting Warranty or Additional Liability. While redistributing
170
+ the Work or Derivative Works thereof, You may choose to offer,
171
+ and charge a fee for, acceptance of support, warranty, indemnity,
172
+ or other liability obligations and/or rights consistent with this
173
+ License. However, in accepting such obligations, You may act only
174
+ on Your own behalf and on Your sole responsibility, not on behalf
175
+ of any other Contributor, and only if You agree to indemnify,
176
+ defend, and hold each Contributor harmless for any liability
177
+ incurred by, or claims asserted against, such Contributor by reason
178
+ of your accepting any such warranty or additional liability.
179
+
180
+ END OF TERMS AND CONDITIONS
181
+
182
+ APPENDIX: How to apply the Apache License to your work.
183
+
184
+ To apply the Apache License to your work, attach the following
185
+ boilerplate notice, with the fields enclosed by brackets "[]"
186
+ replaced with your own identifying information. (Don't include
187
+ the brackets!) The text should be enclosed in the appropriate
188
+ comment syntax for the file format. We also recommend that a
189
+ file or class name and description of purpose be included on the
190
+ same "printed page" as the copyright notice for easier
191
+ identification within third-party archives.
192
+
193
+ Copyright [yyyy] [name of copyright owner]
194
+
195
+ Licensed under the Apache License, Version 2.0 (the "License");
196
+ you may not use this file except in compliance with the License.
197
+ You may obtain a copy of the License at
198
+
199
+ http://www.apache.org/licenses/LICENSE-2.0
200
+
201
+ Unless required by applicable law or agreed to in writing, software
202
+ distributed under the License is distributed on an "AS IS" BASIS,
203
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
204
+ See the License for the specific language governing permissions and
205
+ limitations under the License.
206
+ License-File: LICENSE
207
+ Requires-Python: >=3.12
208
+ Description-Content-Type: text/markdown
209
+
210
+ # LazyFork
211
+
212
+ Fork a running containerised agent runtime N ways, cheaply. A fork is an exact copy of the parent mid-execution, built from one CRIU dump and many lazy restores that share untouched pages through the page cache.
213
+
214
+ Early development. The API is not stable yet.
@@ -0,0 +1,5 @@
1
+ # LazyFork
2
+
3
+ Fork a running containerised agent runtime N ways, cheaply. A fork is an exact copy of the parent mid-execution, built from one CRIU dump and many lazy restores that share untouched pages through the page cache.
4
+
5
+ Early development. The API is not stable yet.
@@ -0,0 +1,261 @@
1
+ import ctypes
2
+ import errno
3
+ import fcntl
4
+ import logging
5
+ import mmap
6
+ import os
7
+ import select
8
+ import socket
9
+ import struct
10
+ import threading
11
+ from dataclasses import dataclass, field
12
+ from pathlib import Path
13
+
14
+ PAGE = 4096
15
+ IMG_COMMON_MAGIC = 0x54564319
16
+ PAGEMAP_MAGIC = 0x56084025
17
+ RESTORE_FINISHED = 0x52535446
18
+ PE_PRESENT = 1 << 2
19
+
20
+ UFFD_EVENT_PAGEFAULT = 0x12
21
+ UFFD_EVENT_FORK = 0x13
22
+ UFFD_EVENT_REMAP = 0x14
23
+ UFFD_EVENT_REMOVE = 0x15
24
+ UFFD_EVENT_UNMAP = 0x16
25
+ UFFDIO_COPY = 0xC028AA03
26
+ UFFDIO_ZEROPAGE = 0xC020AA04
27
+ UFFD_MSG_SIZE = 32
28
+
29
+ log = logging.getLogger("uffd")
30
+
31
+
32
+ def _varint(buf: bytes, pos: int) -> tuple[int, int]:
33
+ value = shift = 0
34
+ while True:
35
+ b = buf[pos]
36
+ pos += 1
37
+ value |= (b & 0x7F) << shift
38
+ if not b & 0x80:
39
+ return value, pos
40
+ shift += 7
41
+
42
+
43
+ def _decode(buf: bytes) -> dict[int, int]:
44
+ fields: dict[int, int] = {}
45
+ pos = 0
46
+ while pos < len(buf):
47
+ tag, pos = _varint(buf, pos)
48
+ if tag & 7 != 0:
49
+ raise ValueError(f"unexpected wire type in tag {tag}")
50
+ fields[tag >> 3], pos = _varint(buf, pos)
51
+ return fields
52
+
53
+
54
+ class PageImage:
55
+ def __init__(self, images: Path, pid: int) -> None:
56
+ pagemap = (images / f"pagemap-{pid}.img").read_bytes()
57
+ common, magic = struct.unpack_from("<II", pagemap, 0)
58
+ if (common, magic) != (IMG_COMMON_MAGIC, PAGEMAP_MAGIC):
59
+ raise ValueError(f"bad pagemap magic {common:#x} {magic:#x}")
60
+ entries = []
61
+ pos = 8
62
+ while pos < len(pagemap):
63
+ (size,) = struct.unpack_from("<I", pagemap, pos)
64
+ pos += 4
65
+ entries.append(_decode(pagemap[pos:pos + size]))
66
+ pos += size
67
+ pages_id = entries[0][1]
68
+ self.pages: dict[int, int] = {}
69
+ offset = 0
70
+ for e in entries[1:]:
71
+ vaddr, flags = e[1], e.get(4, 0)
72
+ nr = e.get(5, e.get(2, 0))
73
+ if not flags & PE_PRESENT:
74
+ continue
75
+ for i in range(nr):
76
+ self.pages[vaddr + i * PAGE] = offset
77
+ offset += PAGE
78
+ fd = os.open(images / f"pages-{pages_id}.img", os.O_RDONLY)
79
+ try:
80
+ self.map = mmap.mmap(fd, 0, flags=mmap.MAP_PRIVATE, prot=mmap.PROT_READ | mmap.PROT_WRITE)
81
+ finally:
82
+ os.close(fd)
83
+ self.base = ctypes.addressof(ctypes.c_char.from_buffer(self.map))
84
+
85
+
86
+ @dataclass
87
+ class Task:
88
+ uffd: int
89
+ pid: int
90
+ image: PageImage
91
+ pages: dict[int, int]
92
+ owns_pages: bool = False
93
+ faults: int = 0
94
+ copied: int = 0
95
+ zeroed: int = 0
96
+ alive: bool = True
97
+
98
+ def private_pages(self) -> dict[int, int]:
99
+ if not self.owns_pages:
100
+ self.pages = dict(self.pages)
101
+ self.owns_pages = True
102
+ return self.pages
103
+
104
+
105
+ @dataclass
106
+ class Client:
107
+ sock: socket.socket
108
+ finished: bool = False
109
+ tasks: list[Task] = field(default_factory=list)
110
+
111
+
112
+ class LazyPagesServer:
113
+ def __init__(self, images: Path, workdir: Path) -> None:
114
+ self.images = images
115
+ self.socket_path = workdir / "lazy-pages.socket"
116
+ self.socket_path.unlink(missing_ok=True)
117
+ self.listener = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM)
118
+ self.listener.bind(str(self.socket_path))
119
+ self.listener.listen(64)
120
+ self.epoll = select.epoll()
121
+ self.epoll.register(self.listener.fileno(), select.EPOLLIN)
122
+ self.stop_r, self.stop_w = os.pipe()
123
+ self.epoll.register(self.stop_r, select.EPOLLIN)
124
+ self.image_cache: dict[int, PageImage] = {}
125
+ self.clients: dict[int, Client] = {}
126
+ self.tasks: dict[int, Task] = {}
127
+ self.accepted: list[Client] = []
128
+ self.thread = threading.Thread(target=self._loop, name="lazy-pages", daemon=True)
129
+
130
+ def start(self) -> None:
131
+ self.thread.start()
132
+
133
+ def stop(self) -> None:
134
+ os.write(self.stop_w, b"x")
135
+ self.thread.join()
136
+ for t in self.tasks.values():
137
+ os.close(t.uffd)
138
+ for c in self.clients.values():
139
+ c.sock.close()
140
+ self.listener.close()
141
+ self.socket_path.unlink(missing_ok=True)
142
+
143
+ def _image(self, pid: int) -> PageImage:
144
+ if pid not in self.image_cache:
145
+ self.image_cache[pid] = PageImage(self.images, pid)
146
+ return self.image_cache[pid]
147
+
148
+ def _loop(self) -> None:
149
+ while True:
150
+ for fd, ev in self.epoll.poll():
151
+ if fd == self.stop_r:
152
+ return
153
+ if fd == self.listener.fileno():
154
+ self._accept()
155
+ elif fd in self.clients:
156
+ self._client_event(self.clients[fd], ev)
157
+ elif fd in self.tasks:
158
+ self._task_event(self.tasks[fd], ev)
159
+
160
+ def _accept(self) -> None:
161
+ sock, _ = self.listener.accept()
162
+ client = Client(sock)
163
+ self.clients[sock.fileno()] = client
164
+ self.accepted.append(client)
165
+ self.epoll.register(sock.fileno(), select.EPOLLIN)
166
+ log.debug("client %d connected", sock.fileno())
167
+
168
+ def _client_event(self, client: Client, ev: int) -> None:
169
+ sock = client.sock
170
+ head = sock.recv(4, socket.MSG_WAITALL) if ev & select.EPOLLIN else b""
171
+ if len(head) < 4:
172
+ self.epoll.unregister(sock.fileno())
173
+ del self.clients[sock.fileno()]
174
+ sock.close()
175
+ log.debug("client closed, finished=%s", client.finished)
176
+ return
177
+ (value,) = struct.unpack("<i", head)
178
+ if value == RESTORE_FINISHED:
179
+ client.finished = True
180
+ return
181
+ if value < 0:
182
+ log.debug("zombie pid %d", -value)
183
+ return
184
+ _, fds, _, _ = socket.recv_fds(sock, 1, 1)
185
+ image = self._image(value)
186
+ task = Task(fds[0], value, image, image.pages)
187
+ self.tasks[task.uffd] = task
188
+ client.tasks.append(task)
189
+ self.epoll.register(task.uffd, select.EPOLLIN)
190
+ log.debug("task pid %d uffd %d registered, %d pages in image", value, task.uffd, len(image.pages))
191
+
192
+ def _task_event(self, task: Task, ev: int) -> None:
193
+ if ev & select.EPOLLIN:
194
+ while True:
195
+ try:
196
+ msg = os.read(task.uffd, UFFD_MSG_SIZE)
197
+ except BlockingIOError:
198
+ break
199
+ except OSError as e:
200
+ if e.errno != errno.EBADF:
201
+ raise
202
+ msg = b""
203
+ if len(msg) < UFFD_MSG_SIZE:
204
+ self._task_exit(task)
205
+ return
206
+ self._handle(task, msg)
207
+ if ev & (select.EPOLLHUP | select.EPOLLERR) and task.alive:
208
+ self._task_exit(task)
209
+
210
+ def _handle(self, task: Task, msg: bytes) -> None:
211
+ event = msg[0]
212
+ if event == UFFD_EVENT_PAGEFAULT:
213
+ address = struct.unpack_from("<Q", msg, 16)[0] & ~(PAGE - 1)
214
+ task.faults += 1
215
+ offset = task.pages.get(address)
216
+ if offset is None:
217
+ arg = bytearray(struct.pack("<QQQq", address, PAGE, 0, 0))
218
+ if self._ioctl(task, UFFDIO_ZEROPAGE, arg):
219
+ task.zeroed += 1
220
+ else:
221
+ arg = bytearray(struct.pack("<QQQQq", address, task.image.base + offset, PAGE, 0, 0))
222
+ if self._ioctl(task, UFFDIO_COPY, arg):
223
+ task.copied += 1
224
+ elif event in (UFFD_EVENT_REMOVE, UFFD_EVENT_UNMAP):
225
+ start, end = struct.unpack_from("<QQ", msg, 8)
226
+ pages = task.private_pages()
227
+ for addr in range(start, end, PAGE):
228
+ pages.pop(addr, None)
229
+ elif event == UFFD_EVENT_REMAP:
230
+ src, dst, length = struct.unpack_from("<QQQ", msg, 8)
231
+ pages = task.private_pages()
232
+ moved = {dst + (a - src): pages.pop(a) for a in list(pages) if src <= a < src + length}
233
+ pages.update(moved)
234
+ elif event == UFFD_EVENT_FORK:
235
+ (child_fd,) = struct.unpack_from("<I", msg, 8)
236
+ child = Task(child_fd, task.pid, task.image, dict(task.pages), owns_pages=True)
237
+ self.tasks[child_fd] = child
238
+ self.epoll.register(child_fd, select.EPOLLIN)
239
+ log.debug("fork: uffd %d -> child uffd %d", task.uffd, child_fd)
240
+ else:
241
+ raise RuntimeError(f"unexpected uffd event {event:#x}")
242
+
243
+ def _ioctl(self, task: Task, request: int, arg: bytearray) -> bool:
244
+ try:
245
+ fcntl.ioctl(task.uffd, request, arg, True)
246
+ return True
247
+ except OSError as e:
248
+ if e.errno in (errno.EEXIST, errno.EAGAIN):
249
+ return False
250
+ if e.errno in (errno.ESRCH, errno.ENOSPC):
251
+ self._task_exit(task)
252
+ return False
253
+ raise
254
+
255
+ def _task_exit(self, task: Task) -> None:
256
+ if not task.alive:
257
+ return
258
+ task.alive = False
259
+ self.epoll.unregister(task.uffd)
260
+ log.debug("task uffd %d exited: faults=%d copied=%d zeroed=%d",
261
+ task.uffd, task.faults, task.copied, task.zeroed)
@@ -0,0 +1,220 @@
1
+ import argparse
2
+ import logging
3
+ import os
4
+ import shutil
5
+ import signal
6
+ import subprocess
7
+ import sys
8
+ import time
9
+ from dataclasses import dataclass
10
+ from pathlib import Path
11
+
12
+ from lazy_pages_server import LazyPagesServer, Task
13
+
14
+ HEAP_MB = 256
15
+
16
+ log = logging.getLogger("experiment")
17
+
18
+
19
+ def template_process() -> None:
20
+ os.setsid()
21
+ heap = bytearray(HEAP_MB << 20)
22
+ for i in range(0, len(heap), 4096):
23
+ heap[i] = i // 4096 % 251
24
+ print("ready", flush=True)
25
+ counter = 0
26
+ while True:
27
+ time.sleep(1)
28
+ counter += 1
29
+ page = (counter * 7919) % (len(heap) // 4096)
30
+ print(f"tick={counter} page={page} byte={heap[page * 4096]}", flush=True)
31
+
32
+
33
+ @dataclass
34
+ class MemSample:
35
+ rss_kb: int
36
+ pss_kb: int
37
+ shared_clean_kb: int
38
+ private_dirty_kb: int
39
+ pte_kb: int
40
+
41
+ @classmethod
42
+ def of(cls, pid: int) -> "MemSample":
43
+ rollup = dict(_kv(Path(f"/proc/{pid}/smaps_rollup")))
44
+ status = dict(_kv(Path(f"/proc/{pid}/status")))
45
+ return cls(
46
+ rss_kb=rollup["Rss"],
47
+ pss_kb=rollup["Pss"],
48
+ shared_clean_kb=rollup["Shared_Clean"],
49
+ private_dirty_kb=rollup["Private_Dirty"],
50
+ pte_kb=status["VmPTE"],
51
+ )
52
+
53
+ def row(self) -> str:
54
+ return (
55
+ f"{self.rss_kb / 1024:8.1f} {self.pss_kb / 1024:8.1f} "
56
+ f"{self.shared_clean_kb / 1024:8.1f} {self.private_dirty_kb / 1024:8.1f} "
57
+ f"{self.pte_kb:6d}"
58
+ )
59
+
60
+
61
+ def _kv(path: Path) -> list[tuple[str, int]]:
62
+ out = []
63
+ for line in path.read_text().splitlines():
64
+ key, _, rest = line.partition(":")
65
+ parts = rest.split()
66
+ if parts and parts[-1] == "kB":
67
+ out.append((key, int(parts[0])))
68
+ return out
69
+
70
+
71
+ def _mem_available_kb() -> int:
72
+ return dict(_kv(Path("/proc/meminfo")))["MemAvailable"]
73
+
74
+
75
+ @dataclass
76
+ class Restore:
77
+ index: int
78
+ workdir: Path
79
+ pid: int
80
+ restore_s: float
81
+ initial: MemSample
82
+
83
+
84
+ class Experiment:
85
+ def __init__(self, images: Path, work: Path, count: int, settle_s: float, daemon: str) -> None:
86
+ self.images = images
87
+ self.work = work
88
+ self.count = count
89
+ self.settle_s = settle_s
90
+ self.daemon = daemon
91
+ self.server: LazyPagesServer | None = None
92
+
93
+ def run(self) -> None:
94
+ log.info("resetting %s and %s", self.images, self.work)
95
+ self._reset_dirs()
96
+ if self.daemon == "shared":
97
+ shared = self.work / "shared"
98
+ shared.mkdir()
99
+ server = LazyPagesServer(self.images, shared)
100
+ server.start()
101
+ self.server = server
102
+ log.info("shared lazy-pages server listening on %s", server.socket_path)
103
+ log.info("launching template")
104
+ template_pid = self._launch_template()
105
+ log.info("template ready, host pid %d", template_pid)
106
+ before = MemSample.of(template_pid)
107
+ log.info("dumping (log: %s)", self.images / "dump.log")
108
+ dump_s = self._timed(
109
+ ["criu", "dump", "-t", str(template_pid), "-D", str(self.images),
110
+ "-v4", "-o", "dump.log"]
111
+ )
112
+ image_mb = sum(p.stat().st_size for p in self.images.iterdir()) / (1 << 20)
113
+ log.info("dump done in %.0f ms, image %.0f MB", dump_s * 1000, image_mb)
114
+ host_before_kb = _mem_available_kb()
115
+ restores = [self._restore(i) for i in range(self.count)]
116
+ log.info("settling %.0f s", self.settle_s)
117
+ time.sleep(self.settle_s)
118
+ settled = [MemSample.of(r.pid) for r in restores]
119
+ host_delta_mb = (host_before_kb - _mem_available_kb()) / 1024
120
+ log.info("sampled after settle")
121
+
122
+ print(f"template pid={template_pid} dump={dump_s * 1000:.0f} ms image={image_mb:.0f} MB daemon={self.daemon}")
123
+ print(f"{'who':<22} {'restore':>8} {'rss':>8} {'pss':>8} {'shared':>8} {'privdty':>8} {'pte':>6} {'faults':>16}")
124
+ print(f"{'template (pre-dump)':<22} {'':>8} {before.row()}")
125
+ for r, s in zip(restores, settled):
126
+ print(f"{'fork ' + str(r.index) + ' t=0':<22} {r.restore_s * 1000:6.0f}ms {r.initial.row()}")
127
+ print(f"{'fork ' + str(r.index) + f' t={self.settle_s:.0f}s':<22} {'':>8} {s.row()} {self._faults(r.index):>16}")
128
+ print("units: MB except pte (kB); faults = served (copied/zeroed)")
129
+ print(f"host MemAvailable drop for {self.count} forks: {host_delta_mb:.1f} MB "
130
+ f"({host_delta_mb / self.count:.2f} MB per fork)")
131
+
132
+ log.info("killing forks %s", [r.pid for r in restores])
133
+ for r in restores:
134
+ os.kill(r.pid, signal.SIGKILL)
135
+ if self.server:
136
+ time.sleep(0.2)
137
+ self.server.stop()
138
+
139
+ def _faults(self, index: int) -> str:
140
+ if not self.server:
141
+ return "-"
142
+ task: Task = self.server.accepted[index].tasks[0]
143
+ return f"{task.faults} ({task.copied}/{task.zeroed})"
144
+
145
+ def _reset_dirs(self) -> None:
146
+ for d in (self.images, self.work):
147
+ shutil.rmtree(d, ignore_errors=True)
148
+ d.mkdir(parents=True)
149
+
150
+ def _launch_template(self) -> int:
151
+ log_path = self.work / "template.log"
152
+ proc = subprocess.Popen(
153
+ ["unshare", "--pid", "--fork", sys.executable, __file__, "--template"],
154
+ stdin=subprocess.DEVNULL, stdout=log_path.open("w"), stderr=subprocess.STDOUT,
155
+ )
156
+ log.info("unshare pid %d, waiting for ready in %s", proc.pid, log_path)
157
+ deadline = time.monotonic() + 60
158
+ while "ready" not in log_path.read_text():
159
+ if time.monotonic() > deadline or proc.poll() is not None:
160
+ raise RuntimeError(f"template did not become ready: {log_path.read_text()}")
161
+ time.sleep(0.1)
162
+ children = Path(f"/proc/{proc.pid}/task/{proc.pid}/children").read_text().split()
163
+ return int(children[0])
164
+
165
+ def _restore(self, index: int) -> Restore:
166
+ if self.server:
167
+ workdir = self.server.socket_path.parent
168
+ else:
169
+ workdir = self.work / f"w{index}"
170
+ workdir.mkdir()
171
+ log.info("fork %d: starting lazy-pages daemon (log: %s)", index, workdir / "lp.log")
172
+ daemon_s = self._timed(
173
+ ["criu", "lazy-pages", "-D", str(self.images), "-W", str(workdir),
174
+ "--daemon", "-v4", "-o", "lp.log"]
175
+ )
176
+ log.info("fork %d: daemon started in %.0f ms", index, daemon_s * 1000)
177
+ restore_log = f"restore-{index}.log"
178
+ pidfile = workdir / f"pid-{index}"
179
+ log.info("fork %d: restoring (log: %s)", index, workdir / restore_log)
180
+ restore_s = self._timed(
181
+ ["criu", "restore", "-D", str(self.images), "-W", str(workdir), "--lazy-pages",
182
+ "--restore-detached", "--pidfile", str(pidfile), "-v4", "-o", restore_log]
183
+ )
184
+ pid = int(pidfile.read_text())
185
+ log.info("fork %d: restored pid %d in %.0f ms", index, pid, restore_s * 1000)
186
+ return Restore(index, workdir, pid, restore_s, MemSample.of(pid))
187
+
188
+ @staticmethod
189
+ def _timed(cmd: list[str]) -> float:
190
+ log.debug("running: %s", " ".join(cmd))
191
+ start = time.perf_counter()
192
+ subprocess.run(cmd, check=True)
193
+ return time.perf_counter() - start
194
+
195
+
196
+ def main() -> None:
197
+ parser = argparse.ArgumentParser()
198
+ parser.add_argument("--template", action="store_true")
199
+ parser.add_argument("--images", type=Path, default=Path("/var/lib/lazyfork/images/lazy_restore_sharing"))
200
+ parser.add_argument("--work", type=Path, default=Path("/tmp/lazyfork/lazy_restore_sharing"))
201
+ parser.add_argument("-n", "--count", type=int, default=2)
202
+ parser.add_argument("--settle", type=float, default=10.0)
203
+ parser.add_argument("-v", "--verbose", action="store_true")
204
+ parser.add_argument("--daemon", choices=["shared", "stock"], default="shared")
205
+ args = parser.parse_args()
206
+ if args.template:
207
+ template_process()
208
+ return
209
+ logging.basicConfig(
210
+ level=logging.DEBUG if args.verbose else logging.INFO,
211
+ format="%(relativeCreated)8.0f ms %(message)s",
212
+ stream=sys.stderr,
213
+ )
214
+ if os.geteuid() != 0:
215
+ sys.exit("run as root")
216
+ Experiment(args.images, args.work, args.count, args.settle, args.daemon).run()
217
+
218
+
219
+ if __name__ == "__main__":
220
+ main()
@@ -0,0 +1,15 @@
1
+ [project]
2
+ name = "lazyfork"
3
+ version = "0.0.1"
4
+ description = "Fork a running containerised runtime N ways via CRIU lazy restore"
5
+ readme = "README.md"
6
+ requires-python = ">=3.12"
7
+ license = { file = "LICENSE" }
8
+ dependencies = []
9
+
10
+ [build-system]
11
+ requires = ["hatchling"]
12
+ build-backend = "hatchling.build"
13
+
14
+ [tool.hatch.build.targets.wheel]
15
+ packages = ["src/lazyfork"]
File without changes
@@ -0,0 +1,96 @@
1
+ import json
2
+ import logging
3
+ import shutil
4
+ import subprocess
5
+ import sys
6
+ from dataclasses import dataclass, asdict
7
+ from pathlib import Path
8
+
9
+ DEFAULT_STORE = Path("/var/lib/lazyfork/rootfs")
10
+
11
+ log = logging.getLogger(__name__)
12
+
13
+
14
+ @dataclass(frozen=True)
15
+ class ImageConfig:
16
+ ref: str
17
+ id: str
18
+ env: list[str]
19
+ entrypoint: list[str]
20
+ cmd: list[str]
21
+ workdir: str
22
+ user: str
23
+
24
+ @classmethod
25
+ def from_inspect(cls, ref: str, inspect: dict) -> "ImageConfig":
26
+ config = inspect["Config"]
27
+ return cls(
28
+ ref=ref,
29
+ id=inspect["Id"].removeprefix("sha256:"),
30
+ env=config.get("Env") or [],
31
+ entrypoint=config.get("Entrypoint") or [],
32
+ cmd=config.get("Cmd") or [],
33
+ workdir=config.get("WorkingDir") or "/",
34
+ user=config.get("User") or "root",
35
+ )
36
+
37
+ def command(self, override: list[str] | None = None) -> list[str]:
38
+ return self.entrypoint + (override if override is not None else self.cmd)
39
+
40
+ def environ(self) -> dict[str, str]:
41
+ return dict(item.split("=", 1) for item in self.env)
42
+
43
+
44
+ class ImageStore:
45
+ def __init__(self, root: Path = DEFAULT_STORE) -> None:
46
+ self.root = root
47
+
48
+ def pull(self, ref: str) -> ImageConfig:
49
+ if not self._inspect(ref):
50
+ log.info("pulling %s", ref)
51
+ subprocess.run(["nerdctl", "pull", "--quiet", ref], check=True)
52
+ inspect = self._inspect(ref)
53
+ if not inspect:
54
+ raise RuntimeError(f"image {ref} not found after pull")
55
+ return ImageConfig.from_inspect(ref, inspect[0])
56
+
57
+ def rootfs(self, image: ImageConfig) -> Path:
58
+ target = self.root / image.id
59
+ if (target / "rootfs").is_dir():
60
+ return target / "rootfs"
61
+ log.info("flattening %s into %s", image.ref, target)
62
+ staging = self.root / f".{image.id}.tmp"
63
+ shutil.rmtree(staging, ignore_errors=True)
64
+ (staging / "rootfs").mkdir(parents=True)
65
+ container = subprocess.run(
66
+ ["nerdctl", "create", image.ref], check=True, capture_output=True, text=True
67
+ ).stdout.strip()
68
+ try:
69
+ export = subprocess.Popen(["nerdctl", "export", container], stdout=subprocess.PIPE)
70
+ subprocess.run(["tar", "-x", "-C", str(staging / "rootfs")], stdin=export.stdout, check=True)
71
+ if export.wait() != 0:
72
+ raise RuntimeError(f"nerdctl export failed for {image.ref}")
73
+ finally:
74
+ subprocess.run(["nerdctl", "rm", "-f", container], check=True, capture_output=True)
75
+ (staging / "config.json").write_text(json.dumps(asdict(image), indent=2))
76
+ staging.rename(target)
77
+ return target / "rootfs"
78
+
79
+ def _inspect(self, ref: str) -> list[dict]:
80
+ result = subprocess.run(
81
+ ["nerdctl", "image", "inspect", ref], capture_output=True, text=True
82
+ )
83
+ return json.loads(result.stdout) if result.returncode == 0 else []
84
+
85
+
86
+ def main() -> None:
87
+ logging.basicConfig(level=logging.INFO, format="%(message)s", stream=sys.stderr)
88
+ store = ImageStore()
89
+ image = store.pull(sys.argv[1])
90
+ rootfs = store.rootfs(image)
91
+ print(json.dumps(asdict(image), indent=2))
92
+ print(rootfs)
93
+
94
+
95
+ if __name__ == "__main__":
96
+ main()
@@ -0,0 +1,37 @@
1
+ # LazyFork development VM.
2
+ # Create once: limactl create --name=lazyfork vm/lazyfork.yaml
3
+ # Start / stop: limactl start lazyfork / limactl stop lazyfork
4
+ # Status: limactl list
5
+ # Shell: limactl shell lazyfork
6
+ base: template://ubuntu-26.04
7
+
8
+ vmType: vz
9
+ cpus: 4
10
+ memory: "8GiB"
11
+ disk: "40GiB"
12
+
13
+ mounts:
14
+ - location: "~"
15
+ writable: true
16
+
17
+ # The daemon's unix socket, forwarded to the Mac so the CLI/SDK can reach it.
18
+ portForwards:
19
+ - guestSocket: "/run/lazyfork.sock"
20
+ hostSocket: "{{.Dir}}/sock/lazyfork.sock"
21
+
22
+ provision:
23
+ # Runs as root on every boot.
24
+ - mode: system
25
+ script: |
26
+ #!/bin/bash
27
+ set -eux
28
+ # Disable transparent huge pages to avoid huge page faults.
29
+ echo never > /sys/kernel/mm/transparent_hugepage/enabled
30
+ # CRIU images live on tmpfs so restore-many reads from the page cache.
31
+ mkdir -p /var/lib/lazyfork/images
32
+ mountpoint -q /var/lib/lazyfork/images || mount -t tmpfs -o size=4G tmpfs /var/lib/lazyfork/images
33
+ if ! command -v criu >/dev/null; then
34
+ export DEBIAN_FRONTEND=noninteractive
35
+ apt-get update
36
+ apt-get install -y criu
37
+ fi