├── COPYING
├── README.md
├── examples
└── example.yaml
├── livefs_edit
├── __init__.py
├── __main__.py
├── actions.py
├── cli.py
└── context.py
├── pyproject.toml
└── setup.cfg
/COPYING:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 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 General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # A tool to "edit" Ubuntu live server CDs
2 |
3 | There are a few reasons the Ubuntu live server ISOs as shipped may not
4 | quite be what you want. Here are some examples:
5 |
6 | * You want to make an ISO that does a completely automated install
7 |
8 | * You want packages that are not in the package repository by default
9 | to be available during install, even when there is no network (or
10 | only a very isolated network).
11 |
12 | * You want to add an argument to the default kernel command line.
13 |
14 | * You want to inject a new version of the subiquity snap for testing.
15 |
16 | This script aims to help you making modified versions of the
17 | distributed ISOs with changes such as those above.
18 |
19 | Some of the things it does probably work on desktop installer ISOs too
20 | but I haven't thought very hard about that side of things yet.
21 |
22 | ## A warning
23 |
24 | Although this program was written by a Canonical employee on company
25 | time, it started out as essentially an overgrown shell script used as
26 | part of installer developement. It is not a Canonical product and is
27 | not supported as such. The "this program is distributed in the hope
28 | that it will be useful" part of the GPL stanza is as true as ever but
29 | the "without even the implied warranty of FITNESS FOR A PARTICULAR
30 | PURPOSE" is perhaps even more true than usual.
31 |
32 | ## Dependencies
33 |
34 | This script is pretty Linux-dependent and requires `xorriso` and
35 | `mksquashfs` to be available on `$PATH`. Some actions require the
36 | `python3-debian` package to be installed and `gpg` command to be
37 | available. Operating on ISOs from some Ubuntu releases will also need
38 | lz4cat (to unpack the initrd) which is found in `liblz4-tool`.
39 |
40 | It needs to be run as root (although possibly using FUSE variants for
41 | all the mounts would allow it to run as a regular user, maybe).
42 |
43 | ## General invocation
44 |
45 | The basic idea behind this tool is that you tell it where to find the
46 | source ISO, where to put the modified ISO and a list of actions that
47 | make up the modifications. So an invocation always looks somewhat like
48 | this:
49 |
50 | ```
51 | # livefs-edit $source.iso $dest.iso [actions]
52 | ```
53 |
54 | Actions can be specified two ways: on the command line or in a YAML
55 | file. Each action has a name and many of them take arguments.
56 |
57 | On the command line, actions and arguments are specified like:
58 |
59 | ```
60 | --action-name arg1 arg2 --next-action-name
61 | ```
62 |
63 | Arguments that are interpreted as boolean interpret 'on', 'yes',
64 | 'true' (case insensitively) as true.
65 |
66 | Alternatively (if shell quoting starts to get painful), the actions
67 | can be passed as a YAML file, using the `--action-yaml` flag:
68 |
69 | ```
70 | # livefs-edit $source.iso $dest.iso --action-yaml examples/example.yaml
71 | ```
72 |
73 | The YAML file should be a list of mappings. Each mapping names the
74 | actions with `name` and lists any arguments by name, for example:
75 |
76 | ```
77 | - name: add-cmdline-arg
78 | arg: autoinstall
79 | persist: false
80 | - name: shell
81 | - name: add-packages-to-pool
82 | packages:
83 | - casper
84 | - valgrind
85 | ```
86 |
87 | ## Directory structure
88 |
89 | This script does all its work in a temporary directory. Within that
90 | directory the original ISO is mounted at `old/iso` and what will be
91 | packed into the new ISO is present at `new/iso` (the script uses a lot
92 | of `overlayfs` mounts to avoid copying large amounts of data around,
93 | and also only repack things when there are changes).
94 |
95 | Many actions require a writable emulation of the root filesystem that
96 | the installer will run in. By default this is created at `rootfs` in
97 | the main temporary directory, but this can be customized.
98 |
99 | In general, things from the original ISO are mounted in `old/` and are
100 | either read-only or should be treated as such. Writable versions for
101 | the new ISO live in `new/` (mostly).
102 |
103 | ## Actions
104 |
105 | ### setup-rootfs
106 |
107 | **argument**: `target` (default: `"rootfs"`)
108 |
109 | This action sets up a writable emulation of the root filesystem that
110 | the installer will run in at the directory named by `target`. Changes
111 | to this rootfs will be present in the rootfs used by installer on the
112 | modified ISO.
113 |
114 | Many actions will do this implicitly but it may be clearer to be
115 | explicit about the target directory name if later `shell` or `cp`
116 | actions refer to paths in the rootfs.
117 |
118 | ### shell
119 |
120 | **argument**: `command` (default: `null`)
121 |
122 | Runs a shell (bash) in the main temporary directory. If `command` is
123 | present, this is the command that is run. If not, an interactive shell
124 | is run. If the shell (command or interactive) exits with a non-zero
125 | code, that aborts the run.
126 |
127 | ### cp
128 |
129 | **argument**: `source`
130 |
131 | **argument**: `dest`
132 |
133 | Copy a file. The paths `source` and `dest` are interpreted in a special way:
134 |
135 | * Absolute paths (i.e. paths starting with '/') are handled as is.
136 | * A magic prefix of '$LAYERS[n]' is handled by mounting the n'th layer
137 | if needed and interpreting the remainer of the path relative to the
138 | base of that layer.
139 | * Other paths are interpreted relative to the main temporary
140 | directory.
141 |
142 | So something like this:
143 |
144 | ```
145 | --cp /my/custom/initrd new/iso/casper/initrd
146 | ```
147 |
148 | to replace the initrd. And something like this:
149 |
150 | ```
151 | --cp /path/to/sources.list '$LAYERS[0]/etc/apt/sources.list'
152 | ```
153 |
154 | to overwrite sources.list in the base layer.
155 |
156 | ### rm
157 |
158 | **argument**: `path`
159 |
160 | Remove a file or directory. `path` is interpreted the same way as the
161 | paths passed to `--cp`.
162 |
163 | ```
164 | --rm new/iso/casper
165 | ```
166 |
167 | to remove the directory casper.
168 |
169 | ### inject-snap
170 |
171 | **argument**: `snap`
172 |
173 | **argument**: `channel` (default: `"stable"`)
174 |
175 | Inject the passed snap into the rootfs the installer runs in. This is
176 | used to test new versions of subiquity. If there is an assert
177 | alongside the snap, this will be copied into the ISO too and the snap
178 | set up to track the passed channel, otherwise it is installed
179 | unasserted.
180 |
181 | ### add-snap-from-store
182 |
183 | **argument**: `snap_name`
184 |
185 | **argument**: `channel` (default: `"stable"`)
186 |
187 | A wrapper around `--inject-snap` that downloads the specified snap
188 | from the store first.
189 |
190 | ### edit-squashfs
191 |
192 | **argument**: `squash_name`
193 |
194 | **argument**: `add_sys_mounts` (default: `true`)
195 |
196 | Mount the squashfs named `squash_name` at `new/{name}` and arrange for it be
197 | repacked if there are any changes before the new ISO is made.
198 |
199 | `add_sys_mounts` controls whether the usual chroot setup stuff is done
200 | (mounting /dev, /proc/ etc, setting up /etc/resolv.conf).
201 |
202 | ### add-cmdline-arg
203 |
204 | **argument**: `arg`
205 |
206 | **argument**: `persist` (default: `true`)
207 |
208 | Add an argument to the default kernel command line. If `persist` is
209 | true, it will be present on the default kernel command line of the
210 | installed system as well.
211 |
212 | ### add-autoinstall-config
213 |
214 | **argument**: `autoinstall_config`
215 |
216 | Add the provided autoinstall config to the ISO so it is used by
217 | default. This also adds "autoinstall" to the default kernel command
218 | line.
219 |
220 | `autoinstall_config` is the path to a YAML file which can contain
221 | either the autoinstall config directly or a cloud-init user-data file
222 | (in which case it can contain other configuration for the live
223 | installer session, such as ssh keys to be used for the `installer`
224 | user).
225 |
226 | ### add-xorriso-args
227 |
228 | **argument**: `xorriso_args` list of xorriso argument(s)
229 |
230 | Add one or more extra arguments for `xorriso`, after the ones that
231 | livefs-editor already supplies.
232 |
233 | ### resign-pool
234 |
235 | This will generate a new Ed25519 GPG key, sign the package repository
236 | on the ISO with it, arrange for the public part to end up in
237 | `/etc/apt/trusted.gpg.d/custom-iso-key.gpg` in the installed system,
238 | and then throw the private part away. You should be aware of this
239 | change to the default apt configuration! Deleting this file in an
240 | autoinstall `late-command` would be a reasonable thing to do, unless
241 | you want the option of using the ISO as an apt repository later on.
242 |
243 | ### add-debs-to-pool
244 |
245 | **argument**: list of deb files
246 |
247 | Add the passed deb files to the repository on the CD so that they are
248 | available for installation while the installer is running, even if the
249 | install is done offline.
250 |
251 | This calls `resign-pool` so do read the note about GPG in the
252 | description of that action.
253 |
254 | ### add-packages-to-pool
255 |
256 | **argument**: `packages` (list of package names)
257 |
258 | This is a wrapper around `add-debs-to-pool` which takes package names
259 | rather than deb files. It downloads the listed packages and any others
260 | needed to satisfy their dependencies from the main Ubuntu archive and
261 | passes them to `add-debs-to-pool`. Do read the note about GPG in the
262 | description of `resign-pool`.
263 |
264 | ### unpack-initrd
265 |
266 | **argument**: `target` (default: `"new/initrd"`)
267 |
268 | Unpack the initrd using unmkinitramfs into `target` (contents will
269 | likely end up in subdirectories called things like `early`, `early2`
270 | and `main`, or `cpioN`, at least on amd64) and arrange for these to be repacked
271 | into a replacement initrd for the modified ISO if any changes are made.
272 |
273 | ### add-apt-repository
274 |
275 | **argument**: `repo`
276 |
277 | Run `add-apt-repository ` in the base layer.
278 |
279 | ### install-debs
280 |
281 | **argument**: list of deb files
282 |
283 | Install the listed deb files in the installer environment.
284 |
285 | ### install-packages
286 |
287 | **argument**: `packages` (list of deb files)
288 |
289 | Install the listed packages in the base layer.
290 |
291 | ### python
292 |
293 | **argument**: `` (optional)
294 |
295 | Execute `` in a namespace that contains the context object as
296 | `ctxt` or start an interactive shell if `` is not passed.
297 |
298 | ### replace-kernel
299 |
300 | **argument**: ``
301 |
302 | Modify the ISO so the kernel installed via the metapackage
303 | `linux-` will be used to boot the ISO and be installed in the
304 | target system.
305 |
306 | ### mount-all-squashfses
307 |
308 | Mount all squashfses in `new/iso/casper` at `old/{squash_name}` (this
309 | is mostly to make poking at ISOs in a subsequent interactive `--shell`
310 | action easier).
311 |
--------------------------------------------------------------------------------
/examples/example.yaml:
--------------------------------------------------------------------------------
1 | - name: add-cmdline-arg
2 | arg: autoinstall
3 | persist: false
4 | - name: shell
5 | - name: add-packages-to-pool
6 | packages:
7 | - casper
8 | - valgrind
9 |
--------------------------------------------------------------------------------
/livefs_edit/__init__.py:
--------------------------------------------------------------------------------
1 | # Copyright 2021 Canonical Ltd.
2 | #
3 | # SPDX-License-Identifier: GPL-3.0
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License version 3, as
7 | # published by the Free Software Foundation.
8 | #
9 | # This program is distributed in the hope that it will be useful, but
10 | # WITHOUT ANY WARRANTY; without even the implied warranties of
11 | # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12 | # PURPOSE. See the GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see
16 | # .
17 |
18 | import subprocess
19 |
20 |
21 | def run(cmd, check=True, **kw):
22 | return subprocess.run(cmd, check=check, **kw)
23 |
24 |
25 | def run_capture(cmd, **kw):
26 | return run(
27 | cmd, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
28 | **kw)
29 |
--------------------------------------------------------------------------------
/livefs_edit/__main__.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/python3
2 |
3 | # Copyright 2021 Canonical Ltd.
4 | #
5 | # SPDX-License-Identifier: GPL-3.0
6 | #
7 | # This program is free software: you can redistribute it and/or modify
8 | # it under the terms of the GNU General Public License version 3, as
9 | # published by the Free Software Foundation.
10 | #
11 | # This program is distributed in the hope that it will be useful, but
12 | # WITHOUT ANY WARRANTY; without even the implied warranties of
13 | # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
14 | # PURPOSE. See the GNU General Public License for more details.
15 | #
16 | # You should have received a copy of the GNU General Public License
17 | # along with this program. If not, see
18 | # .
19 |
20 | import os
21 | import subprocess
22 | import sys
23 | import traceback
24 |
25 | import yaml
26 |
27 | from livefs_edit import cli
28 | from livefs_edit.context import EditContext
29 | from livefs_edit.actions import ACTIONS
30 |
31 |
32 | HELP_TXT = """\
33 | # livefs-edit source.{iso,img} dest.{iso,img} [actions]
34 |
35 | livefs-edit makes modifications to Ubuntu live ISOs and images.
36 |
37 | Actions include:
38 | """
39 |
40 |
41 | def main(argv=None):
42 | if argv is None:
43 | argv = sys.argv[1:]
44 | if '--help' in argv or len(argv) < 3:
45 | print(HELP_TXT)
46 | for action in sorted(ACTIONS.keys()):
47 | print(f" * --{action.replace('_', '-')}")
48 | print()
49 | sys.exit(0)
50 |
51 | debug = False
52 | if argv[0] == '--debug':
53 | debug = True
54 | argv.pop(0)
55 |
56 | sourcepath = argv[0]
57 | destpath = argv[1]
58 |
59 | inplace = False
60 | if destpath == '/dev/null':
61 | destpath = None
62 | elif destpath == sourcepath:
63 | destpath = destpath + '.new'
64 | inplace = True
65 |
66 | ctxt = EditContext(sourcepath, debug=debug)
67 |
68 | if argv[2] == '--action-yaml':
69 | calls = []
70 | with open(argv[3]) as fp:
71 | spec = yaml.safe_load(fp)
72 | print(spec)
73 | for action in spec:
74 | func = ACTIONS[action.pop('name')]
75 | calls.append((func, action))
76 | else:
77 | try:
78 | calls = cli.parse(ACTIONS, argv[2:])
79 | except cli.ArgException as e:
80 | print("parsing actions from command line failed:", e)
81 | sys.exit(1)
82 |
83 | try:
84 | ctxt.mount_source()
85 |
86 | for func, kw in calls:
87 | func(ctxt, **kw)
88 |
89 | if destpath is not None:
90 | changed = ctxt.repack(destpath)
91 | if changed and inplace:
92 | os.rename(destpath, sourcepath)
93 | except subprocess.CalledProcessError as cp:
94 | traceback.print_exc()
95 | if cp.stdout:
96 | print("\nStdout:\n\n"+cp.stdout)
97 | if cp.stderr:
98 | print("\nStderr:\n\n"+cp.stderr)
99 | sys.exit(1)
100 | finally:
101 | ctxt.teardown()
102 |
103 |
104 | if __name__ == '__main__':
105 | main(sys.argv[1:])
106 |
--------------------------------------------------------------------------------
/livefs_edit/actions.py:
--------------------------------------------------------------------------------
1 | # Copyright 2021 Canonical Ltd.
2 | #
3 | # SPDX-License-Identifier: GPL-3.0
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License version 3, as
7 | # published by the Free Software Foundation.
8 | #
9 | # This program is distributed in the hope that it will be useful, but
10 | # WITHOUT ANY WARRANTY; without even the implied warranties of
11 | # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12 | # PURPOSE. See the GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see
16 | # .
17 | import code
18 | import enum
19 | import functools
20 | import glob
21 | import gzip
22 | import os
23 | import pathlib
24 | import shlex
25 | import shutil
26 | import stat
27 | import subprocess
28 | from typing import List, Optional, Tuple
29 | import yaml
30 |
31 |
32 | ACTIONS = {}
33 |
34 |
35 | def cached(func):
36 |
37 | key = func.__name__
38 |
39 | @functools.wraps(func)
40 | def impl(ctxt, **kw):
41 | if key in ctxt._cache:
42 | return ctxt._cache[key]
43 | else:
44 | r = ctxt._cache[key] = func(ctxt, **kw)
45 | return r
46 |
47 | return impl
48 |
49 |
50 | def register_action(*, cache=False):
51 | def decorator(func):
52 | name = func.__name__.replace('_', '-')
53 |
54 | @functools.wraps(func)
55 | def impl(ctxt, **kw):
56 | with ctxt.logged(f"running {name} with arguments {kw}"):
57 | return func(ctxt, **kw)
58 |
59 | if cache:
60 | impl = cached(impl)
61 |
62 | ACTIONS[func.__name__.replace('_', '-')] = impl
63 | return impl
64 | return decorator
65 |
66 |
67 | class LayerfsLoc(enum.Enum):
68 | NONE = enum.auto()
69 | CMDLINE = enum.auto()
70 | INITRD = enum.auto()
71 |
72 |
73 | def _find_file_in_initrd(ctxt, relpath: str) -> Optional[str]:
74 | dir = pathlib.Path(unpack_initrd(ctxt))
75 | potential_file = dir / relpath
76 | if potential_file.exists():
77 | return str(potential_file)
78 |
79 | for subdir in sorted(dir.iterdir(), reverse=True):
80 | if not subdir.is_dir():
81 | continue
82 | potential_file = subdir / relpath
83 | if potential_file.exists():
84 | return str(potential_file)
85 |
86 | return None
87 |
88 |
89 | def get_layer_conf_path(ctxt) -> Optional[str]:
90 | return _find_file_in_initrd(ctxt, "conf/conf.d/default-layer.conf")
91 |
92 |
93 | def get_uuid_conf_path(ctxt) -> Optional[str]:
94 | return _find_file_in_initrd(ctxt, "conf/uuid.conf")
95 |
96 |
97 | @cached
98 | def get_layerfs_path(ctxt) -> Tuple[Optional[str], LayerfsLoc]:
99 | cmdline_val = get_cmdline_arg(ctxt, 'layerfs-path')
100 | if cmdline_val is not None:
101 | return cmdline_val, LayerfsLoc.CMDLINE
102 | layer_conf_path = get_layer_conf_path(ctxt)
103 | if layer_conf_path is not None:
104 | with open(layer_conf_path) as fp:
105 | for line in fp:
106 | line = line.strip()
107 | if line.startswith('LAYERFS_PATH='):
108 | return (
109 | line[len('LAYERFS_PATH='):],
110 | LayerfsLoc.INITRD,
111 | )
112 | return None, LayerfsLoc.NONE
113 |
114 |
115 | def get_layer_part_names(squash_base_name):
116 | parts = squash_base_name.split('.')
117 | basenames = []
118 | for i in range(0, len(parts)):
119 | basenames.append('.'.join(parts[:i+1]))
120 | return basenames
121 |
122 |
123 | @cached
124 | def get_squash_names(ctxt):
125 | layerfs_path = get_layerfs_path(ctxt)[0]
126 | if layerfs_path:
127 | return get_layer_part_names(os.path.splitext(layerfs_path)[0])
128 | else:
129 | return get_all_squash_names(ctxt)
130 |
131 |
132 | @cached
133 | def get_all_squash_names(ctxt):
134 | basenames = []
135 | for path in glob.glob(ctxt.p('old/iso/casper/*.squashfs')):
136 | basenames.append(os.path.splitext(os.path.basename(path))[0])
137 | return basenames
138 |
139 |
140 | @register_action(cache=True)
141 | def setup_rootfs(ctxt, target='rootfs'):
142 | target = ctxt.p(target)
143 |
144 | squash_names = get_squash_names(ctxt)
145 | lowers = [ctxt.mount_squash(name) for name in squash_names]
146 | overlay = ctxt.add_overlay(lowers, target)
147 | ctxt.add_sys_mounts(target)
148 |
149 | layerfs_path, layerfs_loc = get_layerfs_path(ctxt)
150 | last_squash = squash_names[-1]
151 | if layerfs_path is not None:
152 | new_squash_name = last_squash + '.custom'
153 | else:
154 | new_squash_name = chr(ord(last_squash[0])+1) + last_squash[1:]
155 | new_squash = ctxt.p(f'new/iso/casper/{new_squash_name}.squashfs')
156 |
157 | def _pre_repack():
158 | if overlay.unchanged():
159 | return
160 | with ctxt.logged(f'creating new squashfs {new_squash_name}'):
161 | ctxt.run(['mksquashfs', overlay.upperdir, new_squash])
162 | if layerfs_loc == LayerfsLoc.CMDLINE:
163 | add_cmdline_arg(
164 | ctxt,
165 | arg=f"layerfs-path={new_squash_name}.squashfs",
166 | persist=False)
167 | elif layerfs_loc == LayerfsLoc.INITRD:
168 | layer_conf_path = get_layer_conf_path(ctxt)
169 | assert layer_conf_path is not None
170 | with open(layer_conf_path, 'w') as fp:
171 | fp.write(
172 | f"LAYERFS_PATH={new_squash_name}.squashfs\n")
173 |
174 | ctxt.add_pre_repack_hook(_pre_repack)
175 |
176 | return target
177 |
178 |
179 | @register_action()
180 | def shell(ctxt, command=None):
181 | cmd = ['bash']
182 | if command is not None:
183 | cmd.extend(['-c', command])
184 | ctxt.run(cmd, cwd=ctxt.p())
185 |
186 |
187 | def interpret_path(ctxt, path):
188 | if path.startswith('/'):
189 | return path
190 | if path.startswith('$LAYERS['):
191 | rbracket = path.find(']')
192 | if rbracket == -1 or path[rbracket + 1] != '/':
193 | raise Exception(f"could not interpret path {path!r}")
194 | index = int(path[len('$LAYERS['):rbracket])
195 | path = path[rbracket+2:]
196 | base = ctxt.edit_squashfs(
197 | get_squash_names(ctxt)[index],
198 | add_sys_mounts=index == 0)
199 | return os.path.join(base, path)
200 | return ctxt.p(path)
201 |
202 |
203 | @register_action()
204 | def cp(ctxt, source, dest):
205 | os.makedirs(interpret_path(ctxt, os.path.dirname(dest)), exist_ok=True)
206 | shutil.copy(interpret_path(ctxt, source), interpret_path(ctxt, dest))
207 |
208 |
209 | @register_action()
210 | def install_debs(ctxt, debs: List[str] = ()):
211 | rootfs = setup_rootfs(ctxt)
212 | for i, deb in enumerate(debs):
213 | deb_name = 'foo.deb'
214 | rootfs_path = f'{rootfs}/{deb_name}'
215 | with open(rootfs_path, 'x'):
216 | pass
217 | ctxt.run(['mount', '--bind', deb, rootfs_path])
218 | ctxt.run(['chroot', rootfs, 'dpkg', '-i', deb_name])
219 | ctxt.run(['umount', rootfs_path])
220 | os.unlink(rootfs_path)
221 |
222 |
223 | def rm_ro(func, path, _):
224 | """Clear readonly attribute and retry removal"""
225 | os.chmod(path, stat.S_IWRITE)
226 | func(path)
227 |
228 |
229 | def rm_f(path):
230 | if os.path.lexists(path):
231 | if os.path.isdir(path):
232 | shutil.rmtree(path, onerror=rm_ro)
233 | else:
234 | os.chmod(path, stat.S_IWRITE)
235 | os.unlink(path)
236 |
237 |
238 | @register_action()
239 | def rm(ctxt, path):
240 | rm_f(interpret_path(ctxt, path))
241 |
242 |
243 | def download_snap(ctxt, snap_name, channel):
244 | dldir = ctxt.tmpdir()
245 | ctxt.run([
246 | 'snap', 'download',
247 | '--channel=' + channel,
248 | '--target-directory=' + dldir,
249 | '--basename=dl',
250 | snap_name,
251 | ])
252 | return os.path.join(dldir, 'dl.snap')
253 |
254 |
255 | def add_snap_files(snap_name, snap_file, seed_dir, channel, classic=False):
256 | basename = f'{snap_name}_injected'
257 | info = {
258 | 'name': snap_name,
259 | 'file': f'{basename}.snap',
260 | 'channel': channel,
261 | }
262 | if classic:
263 | info['classic'] = True
264 | target_snap = f'{seed_dir}/snaps/{basename}.snap'
265 | shutil.copy(snap_file, target_snap)
266 | assert_file = os.path.splitext(snap_file)[0] + '.assert'
267 | if os.path.exists(assert_file):
268 | assert_target = f'{seed_dir}/assertions/{basename}.assert'
269 | shutil.copy(assert_file, assert_target)
270 | else:
271 | info['unasserted'] = True
272 | return info
273 |
274 |
275 | @register_action()
276 | def inject_snap(ctxt, snap, channel="stable"):
277 | rootfs = setup_rootfs(ctxt)
278 | seed_dir = f'{rootfs}/var/lib/snapd/seed'
279 | snap_mount = ctxt.add_mount('squashfs', snap, ctxt.tmpdir())
280 |
281 | snap_preseed_binary = '/snap/snapd/current/usr/lib/snapd/snap-preseed'
282 | if not os.path.isfile(snap_preseed_binary):
283 | snap_preseed_binary = '/usr/lib/snapd/snap-preseed'
284 | if not os.path.isfile(snap_preseed_binary):
285 | raise FileNotFoundError('snap-preseed not found')
286 |
287 | with open(snap_mount.p('meta/snap.yaml')) as fp:
288 | snap_meta = yaml.safe_load(fp)
289 |
290 | if snap_meta.get('type') not in ['base', 'core']:
291 | base = snap_meta.get('base', 'core')
292 | else:
293 | base = None
294 |
295 | snap_name = snap_meta['name']
296 |
297 | new_snaps = []
298 |
299 | with open(f'{seed_dir}/seed.yaml') as fp:
300 | old_seed = yaml.safe_load(fp)
301 | for old_snap in old_seed["snaps"]:
302 | if old_snap["name"] == snap_name:
303 | old_basename = os.path.splitext(old_snap['file'])[0]
304 | rm_f(f'{seed_dir}/snaps/{old_basename}.snap')
305 | rm_f(f'{seed_dir}/assertions/{old_basename}.assert')
306 | else:
307 | new_snaps.append(old_snap)
308 |
309 | new_snaps.append(
310 | add_snap_files(
311 | snap_name, snap, seed_dir, channel,
312 | snap_meta.get('confinement') == 'classic'))
313 |
314 | snap_names = {snap['name'] for snap in new_snaps}
315 | if base is not None and base not in snap_names:
316 | new_snaps.append(
317 | add_snap_files(
318 | base, download_snap(ctxt, base, 'stable'), seed_dir, 'stable'))
319 |
320 | with open(f'{seed_dir}/seed.yaml', "w") as fp:
321 | yaml.dump({"snaps": new_snaps}, fp)
322 |
323 | def _preseed_native():
324 | if '_preseed' in ctxt._cache:
325 | return
326 | with ctxt.logged('running snap-preseed...', '...preseed done'):
327 | ctxt.run([snap_preseed_binary, '--reset', rootfs])
328 | ctxt.run([snap_preseed_binary, rootfs])
329 | ctxt._cache['_preseed'] = True
330 |
331 | def _preseed_cross():
332 | if '_preseed' in ctxt._cache:
333 | return
334 | with ctxt.logged('running snap-preseed --reset...', '...done'):
335 | ctxt.run([snap_preseed_binary, '--reset', rootfs])
336 | ctxt._cache['_preseed'] = True
337 |
338 | host_arch = ctxt.run_capture(['dpkg', '--print-architecture']).stdout.strip()
339 |
340 | if ctxt.get_arch() == host_arch:
341 | ctxt.add_pre_repack_hook(_preseed_native)
342 | else:
343 | ctxt.add_pre_repack_hook(_preseed_cross)
344 |
345 |
346 | @register_action()
347 | def add_snap_from_store(ctxt, snap_name, channel="stable"):
348 | inject_snap(
349 | ctxt, snap=download_snap(ctxt, snap_name, channel), channel=channel)
350 |
351 |
352 | def cmdline_config_files(ctxt):
353 | cfgs = [
354 | 'boot/grub/grub.cfg', # grub, most arches
355 | 'isolinux/txt.cfg', # isolinux, BIOS amd64/i386 <= focal
356 | 'boot/parmfile.ubuntu', # s390x
357 | ]
358 | for path in cfgs:
359 | p = ctxt.p('new/iso/' + path)
360 | if not os.path.exists(p):
361 | continue
362 | yield p
363 |
364 |
365 | @register_action()
366 | def add_xorriso_args(ctx, xorriso_args: List[str] = ()):
367 | ctx._xorriso_extra_args.extend(xorriso_args)
368 |
369 |
370 | @register_action()
371 | def add_cmdline_arg(ctxt, arg, persist: bool = True):
372 | for path in cmdline_config_files(ctxt):
373 | with ctxt.logged(f'rewriting {path}'):
374 | with open(path) as fp:
375 | inputlines = list(fp)
376 | with open(path, 'w') as outfp:
377 | for line in inputlines:
378 | if '---' in line:
379 | if persist:
380 | line = line.rstrip() + ' ' + arg + '\n'
381 | else:
382 | before, after = line.split('---', 1)
383 | line = before.rstrip() + ' ' + arg + ' ---' + after
384 | outfp.write(line)
385 |
386 |
387 | def get_cmdline_arg(ctxt, key):
388 | for path in cmdline_config_files(ctxt):
389 | with open(path) as fp:
390 | for line in fp:
391 | if '---' in line:
392 | words = shlex.split(line)
393 | for word in words:
394 | if word.startswith(key + '='):
395 | return word[len(key) + 1:]
396 |
397 |
398 | @register_action()
399 | def edit_squashfs(ctxt, squash_name, add_sys_mounts: bool = True):
400 | ctxt.edit_squashfs(squash_name, add_sys_mounts=add_sys_mounts)
401 |
402 |
403 | @register_action()
404 | def add_autoinstall_config(ctxt, autoinstall_config):
405 | seed_dir = 'var/lib/cloud/seed/nocloud'
406 | CC_PREFIX = '#cloud-config\n'
407 |
408 | rootfs = setup_rootfs(ctxt)
409 | is_cc = False
410 | with open(autoinstall_config) as fp:
411 | first_line = fp.readline()
412 | if first_line == CC_PREFIX:
413 | is_cc = True
414 | first_line = ''
415 | config = yaml.safe_load(first_line + fp.read())
416 | if not is_cc:
417 | config = {'autoinstall': config}
418 | with open(os.path.join(rootfs, seed_dir, 'user-data'), 'w') as fp:
419 | fp.write(CC_PREFIX)
420 | yaml.dump(config, fp)
421 | add_cmdline_arg(ctxt, arg='autoinstall', persist=False)
422 |
423 |
424 | @register_action()
425 | def resign_pool(ctxt, dist=None):
426 | if dist is None:
427 | dist = ctxt.get_suite()
428 |
429 | gpgconf = ctxt.tmpfile()
430 | gpghome = ctxt.tmpdir()
431 | email = 'noone@nowhere.invalid'
432 | with open(gpgconf, 'x') as c:
433 | c.write(f"""\
434 | %no-protection
435 | Key-Type: eddsa
436 | Key-Curve: Ed25519
437 | Key-Usage: sign
438 | Name-Real: Ubuntu Custom ISO One-Time Signing Key
439 | Name-Email: {email}
440 | Expire-Date: 0
441 | """)
442 | gpgconfp = open(gpgconf)
443 | ctxt.run(
444 | ['gpg', '--home', gpghome, '--gen-key', '--batch'],
445 | stdin=gpgconfp)
446 |
447 | release = ctxt.p(f'new/iso/dists/{dist}/Release')
448 |
449 | ctxt.run([
450 | 'gpg',
451 | '--home', gpghome,
452 | '--local-user', email,
453 | '--detach-sign', '--armor', release
454 | ])
455 | os.rename(release + '.asc', release + '.gpg')
456 |
457 | new_fs = ctxt.edit_squashfs(get_squash_names(ctxt)[0])
458 | key_path = f'{new_fs}/etc/apt/trusted.gpg.d/custom-iso-key.gpg'
459 | with open(key_path, 'w') as new_key:
460 | ctxt.run(['gpg', '--home', gpghome, '--export'], stdout=new_key)
461 |
462 |
463 | @register_action()
464 | def add_debs_to_pool(ctxt, debs: List[str] = ()):
465 | from debian import deb822
466 | pool = ctxt.p('new/iso/pool/main')
467 | for deb in debs:
468 | shutil.copy(deb, pool)
469 | dist = ctxt.get_suite()
470 | arch = ctxt.get_arch()
471 | packages = ctxt.p(f'new/iso/dists/{dist}/main/binary-{arch}/Packages')
472 | cp = ctxt.run(
473 | [
474 | 'apt-ftparchive', '--md5=off', '--sha1=off',
475 | 'packages', 'pool/main',
476 | ],
477 | cwd=ctxt.p('new/iso'), stdout=subprocess.PIPE)
478 | with open(packages, 'wb') as new_packages:
479 | new_packages.write(cp.stdout)
480 | with gzip.open(packages + '.gz', 'wb') as new_packages:
481 | new_packages.write(cp.stdout)
482 | release = ctxt.p(f'new/iso/dists/{dist}/Release')
483 | with open(release) as o:
484 | old = deb822.Deb822(o)
485 | for p in release, release + '.gpg':
486 | rm_f(p)
487 | cp = ctxt.run(
488 | [
489 | 'apt-ftparchive', '--md5=off', '--sha1=off', '--sha512=off',
490 | 'release', f'dists/{dist}',
491 | ],
492 | cwd=ctxt.p('new/iso'), stdout=subprocess.PIPE)
493 | # The uncompressed Packages file has to be around when
494 | # apt-ftparchive release is ctxt.run, but it can be deleted now.
495 | os.unlink(packages)
496 | new = deb822.Deb822(cp.stdout)
497 | for k in old:
498 | if k in new:
499 | old[k] = new[k]
500 | with open(release, 'wb') as new_release:
501 | old.dump(new_release)
502 |
503 | resign_pool(ctxt, dist=dist)
504 |
505 |
506 | def cache_for_dir(ctxt, dir):
507 | import apt_pkg
508 | from apt import Cache
509 | for key in apt_pkg.config.list():
510 | apt_pkg.config.clear(key)
511 | apt_pkg.config["Dir"] = dir
512 | apt_pkg.init_config()
513 | apt_pkg.config["APT::Architecture"] = ctxt.get_arch()
514 | apt_pkg.config["APT::Architectures"] = ctxt.get_arch()
515 | apt_pkg.init_system()
516 | return Cache()
517 |
518 |
519 | def download_missing_pool_debs(ctxt, cache):
520 | tdir = ctxt.tmpdir()
521 | pool_debs = set()
522 | for dirpath, dirnames, filenames in os.walk(ctxt.p('new/iso/pool')):
523 | for fname in filenames:
524 | if fname.endswith('.deb'):
525 | pool_debs.add(fname)
526 | debs = []
527 | for p in cache.get_changes():
528 | fname = os.path.basename(p.candidate.filename)
529 | if fname not in pool_debs:
530 | debs.append(p.candidate.fetch_binary(tdir))
531 | return debs
532 |
533 |
534 | @register_action()
535 | def add_packages_to_pool(ctxt, packages: List[str]):
536 | from apt.progress.text import AcquireProgress
537 | fs = ctxt.mount_squash(get_squash_names(ctxt)[0])
538 | overlay = ctxt.add_overlay(fs, ctxt.tmpdir())
539 | cache = cache_for_dir(ctxt, overlay.p())
540 | with ctxt.logged(
541 | '** updating apt lists... **',
542 | '** updating apt lists done **'):
543 | cache.update(AcquireProgress())
544 | cache.open()
545 | for p in packages:
546 | with ctxt.logged(f'marking {p} for installation'):
547 | if "=" in p:
548 | package_name, package_version = p.split("=")
549 | package = cache[package_name]
550 | package.candidate = package.versions.get(package_version)
551 | package.mark_install()
552 | else:
553 | cache[p].mark_install()
554 | debs = download_missing_pool_debs(ctxt, cache)
555 | add_debs_to_pool(ctxt, debs=debs)
556 |
557 |
558 | def add_to_pipeline(prev_proc, cmds, env=None, **kw):
559 | if env is not None:
560 | base_env = os.environ.copy()
561 | base_env.update(env)
562 | env = base_env
563 | if prev_proc is not None:
564 | stdin = prev_proc.stdout
565 | else:
566 | stdin = None
567 | proc = subprocess.Popen(
568 | cmds, stdout=kw.pop('stdout', subprocess.PIPE),
569 | stdin=stdin, env=env, **kw)
570 | if stdin is not None:
571 | stdin.close()
572 | return proc
573 |
574 |
575 | def pack_for_initrd(dir, compress, outfile):
576 | find = add_to_pipeline(None, ['find', '.'], cwd=dir)
577 | sort = add_to_pipeline(find, ['sort'], env={'LC_ALL': 'C'})
578 | cpio = add_to_pipeline(
579 | sort, ['cpio', '-R', '0:0', '-o', '-H', 'newc'], cwd=dir)
580 | if compress:
581 | compress = add_to_pipeline(cpio, ['gzip'], stdout=outfile)
582 | else:
583 | compress = add_to_pipeline(cpio, ['cat'], stdout=outfile)
584 | compress.communicate()
585 |
586 |
587 | @register_action(cache=True)
588 | def unpack_initrd(ctxt, target='new/initrd'):
589 | target = ctxt.p(target)
590 | lower = ctxt.p('old/initrd')
591 | arch = ctxt.get_arch()
592 | if 'INITRD_PATH' in os.environ:
593 | initrd_path = os.environ['INITRD_PATH']
594 | elif arch == 's390x':
595 | initrd_path = 'boot/initrd.ubuntu'
596 | else:
597 | initrd_path = 'casper/initrd'
598 | ctxt.run(['unmkinitramfs', ctxt.p(f'new/iso/{initrd_path}'), lower])
599 | overlay = ctxt.add_overlay(lower, target)
600 |
601 | multipart_dirs = set(['early', 'cpio1'])
602 | if bool(multipart_dirs & set(os.listdir(target))):
603 | def _pre_repack_multi():
604 | if overlay.unchanged():
605 | return
606 | with ctxt.logged(f'repacking initrd to {initrd_path} ...', 'done'):
607 | with open(ctxt.p(f'new/iso/{initrd_path}'), 'wb') as out:
608 | dirs = sorted(pathlib.Path(target).iterdir())
609 | for idx, dir in enumerate(dirs):
610 | assert dir.is_dir()
611 | compress = idx == len(dirs) - 1
612 | with ctxt.logged(f'packing {dir}'):
613 | pack_for_initrd(str(dir), compress, out)
614 |
615 | ctxt.add_pre_repack_hook(_pre_repack_multi)
616 | else:
617 | def _pre_repack_single():
618 | if overlay.unchanged():
619 | return
620 | with ctxt.logged('repacking initrd...', 'done'):
621 | with open(ctxt.p(f'new/iso/{initrd_path}'), 'wb') as out:
622 | pack_for_initrd(target, True, out)
623 |
624 | ctxt.add_pre_repack_hook(_pre_repack_single)
625 |
626 | return target
627 |
628 |
629 | @register_action()
630 | def install_packages(ctxt, packages: List[str]):
631 | base = ctxt.edit_squashfs(get_squash_names(ctxt)[0])
632 | ctxt.run(['chroot', base, 'apt-get', 'update'])
633 | env = os.environ.copy()
634 | env['DEBIAN_FRONTEND'] = 'noninteractive'
635 | env['LANG'] = 'C.UTF-8'
636 | ctxt.run(['chroot', base, 'apt-get', 'install', '-y'] + packages, env=env)
637 |
638 |
639 | @register_action()
640 | def add_apt_repository(ctxt, repo):
641 | base = ctxt.edit_squashfs(get_squash_names(ctxt)[0])
642 | ctxt.run(['chroot', base, 'add-apt-repository', '-y', repo])
643 |
644 |
645 | @register_action()
646 | def replace_kernel(ctxt, flavor):
647 | meta_pkg = 'linux-' + flavor
648 | layerfs_path = get_layerfs_path(ctxt)[0]
649 | squash_names = get_squash_names(ctxt)
650 | base = ctxt.edit_squashfs(get_squash_names(ctxt)[0])
651 |
652 | # Update apt lists in the base layer.
653 | cache = cache_for_dir(ctxt, base)
654 | from apt.progress.text import AcquireProgress
655 | with ctxt.logged(
656 | '** updating apt lists... **',
657 | '** updating apt lists done **'):
658 | cache.update(AcquireProgress())
659 |
660 | if layerfs_path:
661 | # Find layers below the one that adds the kernel.
662 | below_kernel = [base]
663 | for squash_name in squash_names[1:]:
664 | squash_mount = ctxt.mount_squash(squash_name)
665 | modules_dir = squash_mount.p('usr/lib/modules')
666 | if os.path.exists(modules_dir):
667 | if os.listdir(modules_dir) != []:
668 | break
669 | below_kernel.append(squash_mount)
670 | else:
671 | raise Exception("cannot find layer that includes kernel")
672 | else:
673 | below_kernel = [base] + [
674 | ctxt.mount_squash(squash) for squash in squash_names[1:]
675 | ]
676 |
677 | # Create a new overlay to install kernel in. In a layered ISO this will be
678 | # a new layer, in an older one we pull the kernel, initrd, and modules out
679 | # of it.
680 | new_kernel_layer = ctxt.add_overlay(below_kernel)
681 | ctxt.add_sys_mounts(new_kernel_layer.p())
682 |
683 | # Add the initramfs config for the new layer.
684 | script = f'''
685 | #!/bin/sh
686 | case $1 in
687 | prereqs) exit 0;;
688 | esac
689 |
690 | echo {meta_pkg} > /run/kernel-meta-package
691 | '''
692 | if layerfs_path is None:
693 | script += '''
694 | mkdir -p $rootmnt/usr/lib/modules
695 | mount $rootmnt/cdrom/casper/extras/modules.squashfs-custom \
696 | $rootmnt/usr/lib/modules
697 | mkdir -p /run/systemd/system/usr-lib-modules.mount.d
698 | echo '[Mount]' >> /run/systemd/system/usr-lib-modules.mount.d/lazy.conf
699 | echo 'LazyUnmount=yes' >> /run/systemd/system/usr-lib-modules.mount.d/lazy.conf
700 | '''
701 |
702 | new_kernel_layer.write(
703 | 'etc/initramfs-tools/scripts/init-bottom/live-server',
704 | script)
705 | os.chmod(
706 | new_kernel_layer.p(
707 | 'etc/initramfs-tools/scripts/init-bottom/live-server'),
708 | 0o755)
709 | new_kernel_layer.write(
710 | 'etc/initramfs-tools/conf.d/casperize.conf',
711 | 'export CASPER_GENERATE_UUID=1\n')
712 | if layerfs_path is not None:
713 | new_kernel_layer.write(
714 | 'etc/initramfs-tools/conf.d/default-layer.conf',
715 | f'LAYERFS_PATH={squash_name}.squashfs\n')
716 |
717 | # Add any missing packages to the pool.
718 | cache = cache_for_dir(ctxt, new_kernel_layer.p())
719 | cache[meta_pkg].mark_install()
720 | debs = download_missing_pool_debs(ctxt, cache)
721 | add_debs_to_pool(ctxt, debs=debs)
722 |
723 | # Set up new layer to get packages from pool (the changes to the
724 | # apt config and status will just be deleted from the layer later)
725 | ctxt.add_mount(
726 | None, ctxt.p('new/iso'), new_kernel_layer.p('mnt'), options='bind')
727 | os_release = new_kernel_layer.p('etc/os-release')
728 | codename = ctxt.run(
729 | ['bash', '-c', f'source {os_release}; echo $VERSION_CODENAME'],
730 | stdout=subprocess.PIPE, encoding='utf-8').stdout.strip()
731 | new_kernel_layer.write(
732 | 'etc/apt/sources.list',
733 | f'deb [check-date=no] file:///mnt {codename} main restricted\n',
734 | )
735 | ctxt.run(['chroot', new_kernel_layer.p(), 'apt-get', 'update'])
736 |
737 | # Install the new kernel.
738 | env = os.environ.copy()
739 | env['DEBIAN_FRONTEND'] = 'noninteractive'
740 | env['LANG'] = 'C.UTF-8'
741 | ctxt.run(
742 | ['chroot', new_kernel_layer.p(), 'apt-get', 'install', '-y', meta_pkg],
743 | env=env)
744 |
745 | # Fish the kernel and initrd out and put them in the right place
746 | # on the ISO.
747 | [old_kernel] = glob.glob(ctxt.p('old/iso/casper/vmlinu?'))
748 | [kernel] = glob.glob(new_kernel_layer.p('boot/vmlinu?-*'))
749 | [initrd] = glob.glob(new_kernel_layer.p('boot/initrd.img-*'))
750 | ctxt.run([
751 | 'mv', kernel,
752 | ctxt.p('new/iso/casper/' + os.path.basename(old_kernel))])
753 | ctxt.run(['mv', initrd, ctxt.p('new/iso/casper/initrd')])
754 |
755 | # Copy the uuid out of the new initrd.
756 | initrd_dir = ctxt.tmpdir()
757 | ctxt.run(['unmkinitramfs', ctxt.p('new/iso/casper/initrd'), initrd_dir])
758 | uuid_conf = get_uuid_conf_path(ctxt)
759 | assert uuid_conf is not None
760 | ctxt.run(['mv', uuid_conf, ctxt.p('new/iso/.disk/casper-uuid-custom')])
761 |
762 | if layerfs_path is not None:
763 | new_squash_name = ctxt.p(f'new/iso/casper/{squash_name}.squashfs')
764 |
765 | def _repack():
766 | # Remove the changes to the apt config and status.
767 | ctxt.run(['rm', '-rf', f'{new_kernel_layer.upperdir}/var/lib/apt'])
768 | ctxt.run(['rm', '-rf', f'{new_kernel_layer.upperdir}/etc/apt'])
769 | ctxt.run(['rm', new_squash_name])
770 | # Build the new squashfs!
771 | ctxt.run(['mksquashfs', new_kernel_layer.upperdir, new_squash_name])
772 |
773 | ctxt.add_pre_repack_hook(_repack)
774 | else:
775 | ctxt.run([
776 | 'mksquashfs',
777 | new_kernel_layer.p('lib/modules'),
778 | ctxt.p('new/iso/casper/extras/modules.squashfs-custom'),
779 | ])
780 |
781 |
782 | @register_action()
783 | def python(ctxt, cmd=None):
784 | ns = globals().copy()
785 | ns['ctxt'] = ctxt
786 | if cmd:
787 | exec(cmd, ns, ns)
788 | else:
789 | code.interact(local=ns)
790 |
791 |
792 | @register_action()
793 | def mount_all_squashfses(ctxt):
794 | casper_dir = pathlib.Path(ctxt.p('new/iso/casper'))
795 | for squash in casper_dir.glob('*.squashfs'):
796 | ctxt.mount_squash(squash.stem)
797 |
798 |
799 | @register_action()
800 | def mount_all_layers(ctxt, target='mounts'):
801 | casper_dir = pathlib.Path(ctxt.p('new/iso/casper'))
802 |
803 | for squash in casper_dir.glob('*.squashfs'):
804 | squash_names = get_layer_part_names(squash.stem)
805 | lowers = [ctxt.mount_squash(name) for name in squash_names]
806 | ctxt.add_overlay(lowers, ctxt.p(f'{target}/{squash.stem}'))
807 |
--------------------------------------------------------------------------------
/livefs_edit/cli.py:
--------------------------------------------------------------------------------
1 | # Copyright 2021 Canonical Ltd.
2 | #
3 | # SPDX-License-Identifier: GPL-3.0
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License version 3, as
7 | # published by the Free Software Foundation.
8 | #
9 | # This program is distributed in the hope that it will be useful, but
10 | # WITHOUT ANY WARRANTY; without even the implied warranties of
11 | # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12 | # PURPOSE. See the GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see
16 | # .
17 |
18 | import inspect
19 | import typing
20 |
21 |
22 | def _conv(ann, v):
23 | if ann is inspect._empty:
24 | return v
25 | if ann is bool:
26 | return v.lower() in ["on", "yes", "true"]
27 | return v
28 |
29 |
30 | class ArgException(Exception):
31 | pass
32 |
33 |
34 | def args_for_func(func, raw_args):
35 | sig = inspect.Signature.from_callable(func)
36 | sig = sig.replace(parameters=list(sig.parameters.values())[1:])
37 | params = sig.parameters
38 | param_list = list(params.values())
39 | kw = {}
40 | if param_list and param_list[-1].annotation == typing.List[str]:
41 | last_arg_name = param_list[-1].name
42 | else:
43 | last_arg_name = None
44 | for i, a in enumerate(raw_args):
45 | if i >= len(param_list):
46 | if last_arg_name is None:
47 | raise ArgException("too many arguments")
48 | kw.setdefault(last_arg_name, []).append(a)
49 | else:
50 | p = param_list[i]
51 | if p.name == last_arg_name:
52 | kw[p.name] = [a]
53 | continue
54 | if p.name in kw:
55 | raise ArgException(f"multiple values for {p.name}")
56 | kw[p.name] = _conv(p.annotation, a)
57 | return kw
58 |
59 |
60 | def parse(actions, raw_args):
61 | calls = []
62 |
63 | func = None
64 | func_args = []
65 |
66 | def dispatch():
67 | if func is None:
68 | if func_args:
69 | 1/0
70 | else:
71 | try:
72 | kw = args_for_func(func, func_args)
73 | except ArgException as e:
74 | e.args = (func.__name__.replace('_', '-') + ": " + str(e),)
75 | raise
76 | calls.append((func, kw))
77 | func_args[:] = []
78 |
79 | for a in raw_args:
80 | if a.startswith('--'):
81 | dispatch()
82 | a = a[2:]
83 | try:
84 | func = actions[a]
85 | except KeyError:
86 | raise ArgException(f"unknown action {a!r}")
87 | elif func is None:
88 | raise ArgException(f"no action specified for {a!r}")
89 | else:
90 | func_args.append(a)
91 |
92 | dispatch()
93 |
94 | return calls
95 |
--------------------------------------------------------------------------------
/livefs_edit/context.py:
--------------------------------------------------------------------------------
1 | # Copyright 2021 Canonical Ltd.
2 | #
3 | # SPDX-License-Identifier: GPL-3.0
4 | #
5 | # This program is free software: you can redistribute it and/or modify
6 | # it under the terms of the GNU General Public License version 3, as
7 | # published by the Free Software Foundation.
8 | #
9 | # This program is distributed in the hope that it will be useful, but
10 | # WITHOUT ANY WARRANTY; without even the implied warranties of
11 | # MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
12 | # PURPOSE. See the GNU General Public License for more details.
13 | #
14 | # You should have received a copy of the GNU General Public License
15 | # along with this program. If not, see
16 | # .
17 |
18 | import contextlib
19 | import glob
20 | import json
21 | import os
22 | import shlex
23 | import shutil
24 | import subprocess
25 | import tempfile
26 |
27 |
28 | class _MountBase:
29 |
30 | def p(self, *args):
31 | for a in args:
32 | if a.startswith('/'):
33 | raise Exception('no absolute paths here please')
34 | return os.path.join(self.mountpoint, *args)
35 |
36 | def write(self, path, content):
37 | with open(self.p(path), 'w') as fp:
38 | fp.write(content)
39 |
40 |
41 | class Mountpoint(_MountBase):
42 | def __init__(self, *, device, mountpoint):
43 | self.device = device
44 | self.mountpoint = mountpoint
45 |
46 |
47 | class OverlayMountpoint(_MountBase):
48 | def __init__(self, *, lowers, upperdir, mountpoint):
49 | self.lowers = lowers
50 | self.upperdir = upperdir
51 | self.mountpoint = mountpoint
52 |
53 | def unchanged(self):
54 | return os.listdir(self.upperdir) == []
55 |
56 |
57 | class EditContext:
58 |
59 | def __init__(self, source_path, *, debug=False):
60 | self.source_path = source_path
61 | self.debug = debug
62 | self._source_overlay = None
63 | self.dir = tempfile.mkdtemp()
64 | os.mkdir(self.p('.tmp'))
65 | self._cache = {}
66 | self._indent = ''
67 | self._pre_repack_hooks = []
68 | self._loops = []
69 | self._mounts = []
70 | self._squash_mounts = {}
71 | self._xorriso_extra_args = []
72 |
73 | def run(self, cmd, check=True, **kw):
74 | if self.debug:
75 | msg = []
76 | for arg in cmd:
77 | arg = shlex.quote(str(arg))
78 | arg = arg.replace(self.dir, '${BASE}')
79 | msg.append(arg)
80 | msg = ' '.join(msg)
81 | self.log(f"running with check={check}, kw={kw}\n{self._indent} {msg}")
82 | cp = subprocess.run(cmd, check=check, **kw)
83 | if self.debug:
84 | msg = f"exit code {cp.returncode}"
85 | if cp.stdout is not None:
86 | msg += f" {len(cp.stdout)} bytes of output"
87 | if cp.stderr is not None:
88 | msg += f" {len(cp.stderr)} bytes of error"
89 | self.log(msg)
90 | return cp
91 |
92 | def run_capture(self, cmd, **kw):
93 | return self.run(
94 | cmd, encoding='utf-8', stdout=subprocess.PIPE, stderr=subprocess.PIPE,
95 | **kw)
96 |
97 | def log(self, msg):
98 | print(self._indent + msg)
99 |
100 | @contextlib.contextmanager
101 | def logged(self, msg, done_msg=None):
102 | self.log(msg)
103 | self._indent += ' '
104 | try:
105 | yield
106 | finally:
107 | self._indent = self._indent[:-2]
108 | if done_msg is not None:
109 | self.log(done_msg)
110 |
111 | def tmpdir(self):
112 | d = tempfile.mkdtemp(dir=self.p('.tmp'))
113 | os.chmod(d, 0o755)
114 | return d
115 |
116 | def tmpfile(self):
117 | return tempfile.mktemp(dir=self.p('.tmp'))
118 |
119 | def p(self, *args):
120 | for a in args:
121 | if a.startswith('/'):
122 | raise Exception('no absolute paths here please')
123 | return os.path.join(self.dir, *args)
124 |
125 | def add_loop(self, file):
126 | cp = self.run_capture(['losetup', '--show', '--find', '--partscan', file])
127 | dev = cp.stdout.strip()
128 | self._loops.append(dev)
129 | self.run(['udevadm', 'settle'])
130 | self.log(f'set up loop device {dev} backing {file}')
131 | return dev
132 |
133 | def add_mount(self, typ, src, mountpoint, *, options=None):
134 | cmd = ['mount']
135 | if typ is not None:
136 | cmd.extend(['-t', typ])
137 | cmd.append(src)
138 | if options:
139 | cmd.extend(['-o', options])
140 | if mountpoint is None:
141 | mountpoint = self.tmpdir()
142 | cmd.append(mountpoint)
143 | if not os.path.isdir(mountpoint):
144 | os.makedirs(mountpoint)
145 | self.run_capture(cmd)
146 | self._mounts.append(mountpoint)
147 | return Mountpoint(device=src, mountpoint=mountpoint)
148 |
149 | def umount(self, mountpoint):
150 | self._mounts.remove(mountpoint)
151 | self.run(['umount', mountpoint])
152 |
153 | def get_sysfs_mounts(self):
154 | cp = self.run_capture(
155 | ['findmnt', '--submounts', '/sys', '--json', '--list'])
156 | return json.loads(cp.stdout)['filesystems']
157 |
158 | def add_sys_mounts(self, mountpoint):
159 | mnts = []
160 | for typ, relpath in [
161 | ('devtmpfs', 'dev'),
162 | ('devpts', 'dev/pts'),
163 | ('proc', 'proc'),
164 | ]:
165 | mnts.append(self.add_mount(typ, typ, f'{mountpoint}/{relpath}'))
166 | ro_targets = []
167 | for fs in self.get_sysfs_mounts():
168 | relpath = fs['target'].lstrip('/')
169 | target = f'{mountpoint}/{relpath}'
170 | options = fs['options'].split(',')
171 | if 'ro' in options:
172 | ro_targets.append(target)
173 | options.remove('ro')
174 | options = ','.join(options)
175 | mnts.append(self.add_mount(
176 | fs['fstype'], fs['fstype'], target,
177 | options=options))
178 | for ro_target in ro_targets:
179 | self.run(['mount', '-o', 'remount,ro', ro_target])
180 | resolv_conf = f'{mountpoint}/etc/resolv.conf'
181 | os.rename(resolv_conf, resolv_conf + '.tmp')
182 | shutil.copy('/etc/resolv.conf', resolv_conf)
183 |
184 | def _pre_repack():
185 | for mnt in reversed(mnts):
186 | self.umount(mnt.p())
187 | os.rename(resolv_conf + '.tmp', resolv_conf)
188 |
189 | self.add_pre_repack_hook(_pre_repack)
190 |
191 | def add_overlay(self, lowers, mountpoint=None):
192 | if not isinstance(lowers, list):
193 | lowers = [lowers]
194 | upperdir = self.tmpdir()
195 | workdir = self.tmpdir()
196 |
197 | def lowerdir_for(lower):
198 | if isinstance(lower, str):
199 | return lower
200 | if isinstance(lower, Mountpoint):
201 | return lower.p()
202 | if isinstance(lower, OverlayMountpoint):
203 | return lowerdir_for(lower.lowers + [lower.upperdir])
204 | if isinstance(lower, list):
205 | return ':'.join(reversed([lowerdir_for(ll) for ll in lower]))
206 | raise Exception(f'lowerdir_for({lower!r})')
207 |
208 | lowerdir = lowerdir_for(lowers)
209 | options = f'lowerdir={lowerdir},upperdir={upperdir},workdir={workdir}'
210 | return OverlayMountpoint(
211 | lowers=lowers,
212 | mountpoint=self.add_mount(
213 | 'overlay', 'overlay', mountpoint, options=options).p(),
214 | upperdir=upperdir)
215 |
216 | def add_pre_repack_hook(self, hook):
217 | self._pre_repack_hooks.append(hook)
218 |
219 | def mount_squash(self, name):
220 | target = self.p('old/' + name)
221 | squash = self.p(f'old/iso/casper/{name}.squashfs')
222 | if name in self._squash_mounts:
223 | return self._squash_mounts[name]
224 | else:
225 | self._squash_mounts[name] = m = self.add_mount(
226 | 'squashfs', squash, target, options='ro')
227 | return m
228 |
229 | def get_arch(self):
230 | # Is this really the best way??
231 | with open(self.p('new/iso/.disk/info')) as fp:
232 | return fp.read().strip().split()[-2]
233 |
234 | def get_suite(self):
235 | from deb822 import Deb822
236 | paths = glob.glob(self.p('old/iso/dists/*/Release'))
237 | with open(paths[0]) as fp:
238 | release = Deb822(fp)
239 | return release['Suite']
240 |
241 | def edit_squashfs(self, name, *, add_sys_mounts=True):
242 | if name and name.endswith('.squashfs'):
243 | name = name[:-len('.squashfs')]
244 | lower = self.mount_squash(name)
245 | reltarget = f'new/{name}'
246 | target = self.p(reltarget)
247 | if os.path.exists(target):
248 | return target
249 | overlay = self.add_overlay(lower, target)
250 | self.log(f"squashfs {name!r} now mounted at {reltarget!r}")
251 | new_squash = self.p(f'new/iso/casper/{name}.squashfs')
252 |
253 | def _pre_repack():
254 | try:
255 | os.unlink(f'{overlay.upperdir}/etc/resolv.conf')
256 | os.rmdir(f'{overlay.upperdir}/etc')
257 | except OSError:
258 | pass
259 | if overlay.unchanged():
260 | self.log(f"no changes found in squashfs {name!r}")
261 | return
262 | with self.logged(f"repacking squashfs {name!r}"):
263 | os.unlink(new_squash)
264 | self.run(['mksquashfs', target, new_squash])
265 |
266 | self.add_pre_repack_hook(_pre_repack)
267 |
268 | if add_sys_mounts:
269 | self.add_sys_mounts(target)
270 |
271 | return target
272 |
273 | def teardown(self):
274 | for mount in reversed(self._mounts):
275 | self.run(['mount', '--make-rprivate', mount])
276 | try:
277 | self.run(['umount', '-R', mount])
278 | except subprocess.CalledProcessError:
279 | self.run(['umount', '-l', mount])
280 | shutil.rmtree(self.dir)
281 | for loop in reversed(self._loops):
282 | self.run(['losetup', '--detach', loop])
283 |
284 | def find_livefs(self, device):
285 | for dev in glob.glob(f'{device}*'):
286 | try:
287 | try_mount = self.add_mount(None, dev, None, options='ro')
288 | except subprocess.CalledProcessError:
289 | continue
290 | try:
291 | if os.path.exists(try_mount.p('.disk/info')):
292 | return dev
293 | finally:
294 | self.umount(try_mount.p())
295 | else:
296 | raise Exception("could not find live filesystem")
297 |
298 | def mount_source(self):
299 | source_loop = self.add_loop(self.source_path)
300 | live_dev = self.find_livefs(source_loop)
301 | source_mount = self.add_mount(
302 | None, live_dev, self.p('old/iso'), options='ro')
303 | cp = self.run_capture(['findmnt', '-no', 'fstype', source_mount.p()])
304 | self.source_fstype = cp.stdout.strip()
305 | self.log(
306 | f'found live {self.source_fstype} filesystem on {live_dev}')
307 | self._source_overlay = self.add_overlay(
308 | source_mount, self.p('new/iso'))
309 |
310 | def repack(self, destpath):
311 | with self.logged("running repack hooks"):
312 | for hook in reversed(self._pre_repack_hooks):
313 | hook()
314 | if self._source_overlay.unchanged():
315 | self.log("no changes!")
316 | return False
317 | if self.source_fstype == 'iso9660':
318 | self.repack_iso(destpath)
319 | else:
320 | self.repack_generic(destpath)
321 | return True
322 |
323 | def repack_iso(self, destpath):
324 | cp = self.run_capture([
325 | 'xorriso',
326 | '-indev', self.source_path,
327 | '-report_el_torito', 'as_mkisofs',
328 | ])
329 | opts = shlex.split(cp.stdout)
330 | with self.logged("recreating ISO"):
331 | cmd = ['xorriso', '-as', 'mkisofs'] + opts + \
332 | ['-o', destpath, '-V', 'Ubuntu custom', self.p('new/iso')] + \
333 | self._xorriso_extra_args
334 | self.log("running: " + ' '.join(map(shlex.quote, cmd)))
335 | self.run(cmd)
336 |
337 | def repack_generic(self, destpath):
338 | with self.logged(f"copying {self.source_path} to {destpath}"):
339 | self.run(['cp', self.source_path, destpath])
340 | destloop = self.add_loop(destpath)
341 | dest_dev = self.find_livefs(destloop)
342 | dest_mount = self.add_mount(None, dest_dev, None)
343 | with self.logged("copying live filesystem"):
344 | self.run(
345 | ['rsync', '-axXvHAS', self.p('new/iso/'), '.'],
346 | cwd=dest_mount.p())
347 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [build-system]
2 | requires = [
3 | "setuptools>=42",
4 | "wheel"
5 | ]
6 | build-backend = "setuptools.build_meta"
7 |
--------------------------------------------------------------------------------
/setup.cfg:
--------------------------------------------------------------------------------
1 | [metadata]
2 | name = livefs-edit
3 | version = 0.0.4
4 | author = Michael Hudson-Doyle
5 | author_email = michael.hudson@ubuntu.com
6 | description = Tools for modifying Ubuntu Live ISOs
7 | long_description = file: README.md
8 | long_description_content_type = text/markdown
9 | url = https://github.com/mwhudson/livefs-editor
10 | project_urls =
11 | Bug Tracker = https://github.com/mwhudson/livefs-editor/issues
12 | classifiers =
13 | License :: OSI Approved :: GNU General Public License v3 (GPLv3)
14 | Programming Language :: Python :: 3
15 | Operating System :: POSIX :: Linux
16 |
17 | [options]
18 | packages = find:
19 | python_requires = >=3.6
20 | install_requires =
21 | PyYAML
22 |
23 | [options.entry_points]
24 | console_scripts =
25 | livefs-edit = livefs_edit:__main__.main
26 |
27 |
--------------------------------------------------------------------------------