curtin-0.1.0~bzr126/LICENSE 0000644 0000000 0000000 00000103330 12321566163 013321 0 ustar 0000000 0000000 GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU Affero General Public License is a free, copyleft license for
software and other kinds of works, specifically designed to ensure
cooperation with the community in the case of network server software.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
our General Public Licenses are intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
Developers that use our General Public Licenses protect your rights
with two steps: (1) assert copyright on the software, and (2) offer
you this License which gives you legal permission to copy, distribute
and/or modify the software.
A secondary benefit of defending all users' freedom is that
improvements made in alternate versions of the program, if they
receive widespread use, become available for other developers to
incorporate. Many developers of free software are heartened and
encouraged by the resulting cooperation. However, in the case of
software used on network servers, this result may fail to come about.
The GNU General Public License permits making a modified version and
letting the public access it on a server without ever releasing its
source code to the public.
The GNU Affero General Public License is designed specifically to
ensure that, in such cases, the modified source code becomes available
to the community. It requires the operator of a network server to
provide the source code of the modified version running there to the
users of that server. Therefore, public use of a modified version, on
a publicly accessible server, gives the public access to the source
code of the modified version.
An older license, called the Affero General Public License and
published by Affero, was designed to accomplish similar goals. This is
a different license, not a version of the Affero GPL, but Affero has
released a new version of the Affero GPL which permits relicensing under
this license.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU Affero General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Remote Network Interaction; Use with the GNU General Public License.
Notwithstanding any other provision of this License, if you modify the
Program, your modified version must prominently offer all users
interacting with it remotely through a computer network (if your version
supports such interaction) an opportunity to receive the Corresponding
Source of your version by providing access to the Corresponding Source
from a network server at no charge, through some standard or customary
means of facilitating copying of software. This Corresponding Source
shall include the Corresponding Source for any work covered by version 3
of the GNU General Public License that is incorporated pursuant to the
following paragraph.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the work with which it is combined will remain governed by version
3 of the GNU General Public License.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU Affero General Public License from time to time. Such new versions
will be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU Affero General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU Affero General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU Affero General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
Copyright (C)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see .
Also add information on how to contact you by electronic and paper mail.
If your software can interact with users remotely through a computer
network, you should also make sure that it provides a way for users to
get its source. For example, if your program is a web application, its
interface could display a "Source" link that leads users to an archive
of the code. There are many ways you could offer source, and different
solutions will be better for different programs; see section 13 for the
specific requirements.
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU AGPL, see
.
curtin-0.1.0~bzr126/Makefile 0000644 0000000 0000000 00000000435 12321566163 013756 0 ustar 0000000 0000000 TOP := $(abspath $(dir $(lastword $(MAKEFILE_LIST))))
CWD := $(shell pwd)
build:
check: pep8 pyflakes test
pep8:
@$(CWD)/tools/run-pep8
pyflakes:
@$(CWD)/tools/run-pyflakes
test:
nosetests $(noseopts) tests/
nosetests3 $(noseopts) tests
.PHONY: all test pyflakes pep8 build
curtin-0.1.0~bzr126/README 0000644 0000000 0000000 00000000243 12321566163 013173 0 ustar 0000000 0000000 This is 'curtin', the curt installer. It is blunt, brief, snappish, snippety
and unceremonious.
Its goal is to install an operating system as quick as possible.
curtin-0.1.0~bzr126/bin/ 0000755 0000000 0000000 00000000000 12321566163 013064 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/curtin/ 0000755 0000000 0000000 00000000000 12321566163 013620 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/debian/ 0000755 0000000 0000000 00000000000 12321566163 013536 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/doc/ 0000755 0000000 0000000 00000000000 12321566163 013061 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/examples/ 0000755 0000000 0000000 00000000000 12321566163 014132 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/helpers/ 0000755 0000000 0000000 00000000000 12321566163 013756 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/setup.py 0000644 0000000 0000000 00000001205 12321566163 014024 0 ustar 0000000 0000000 VERSION = '0.1.0'
from distutils.core import setup
from glob import glob
import os
def is_f(p):
return os.path.isfile(p)
setup(
name="curtin",
description='The curtin installer',
version=VERSION,
author='Scott Moser',
author_email='scott.moser@canonical.com',
license="AGPL",
url='http://launchpad.net/curtin/',
packages=['curtin', 'curtin.commands', 'curtin.block', 'curtin.net'],
scripts=glob('bin/*'),
data_files=[
('/usr/share/doc/curtin',
[f for f in glob('doc/*') if is_f(f)]),
('/usr/lib/curtin/helpers',
[f for f in glob('helpers/*') if is_f(f)])
]
)
curtin-0.1.0~bzr126/tests/ 0000755 0000000 0000000 00000000000 12321566163 013456 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/tools/ 0000755 0000000 0000000 00000000000 12321566163 013454 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/bin/curtin 0000755 0000000 0000000 00000002665 12321566163 014327 0 ustar 0000000 0000000 #!/usr/bin/python
# Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import os
import sys
def call_entry_point(name):
(istr, dot, ent) = name.rpartition('.')
try:
__import__(istr)
except ImportError:
# if that import failed, check dirname(__file__/..)
# to support ./bin/curtin with modules in .
_tdir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(_tdir)
try:
__import__(istr)
except ImportError:
sys.stderr.write("Unable to find %s\n" % name)
sys.exit(2)
sys.exit(getattr(sys.modules[istr], ent)())
if __name__ == '__main__':
call_entry_point("curtin.commands.main.main")
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/__init__.py 0000644 0000000 0000000 00000001423 12321566163 015731 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/block/ 0000755 0000000 0000000 00000000000 12321566163 014712 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/curtin/commands/ 0000755 0000000 0000000 00000000000 12321566163 015421 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/curtin/config.py 0000644 0000000 0000000 00000005757 12321566163 015455 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import yaml
ARCHIVE_HEADER = "#curtin-config-archive"
ARCHIVE_TYPE = "text/curtin-config-archive"
CONFIG_HEADER = "#curtin-config"
CONFIG_TYPE = "text/curtin-config"
try:
# python2
_STRING_TYPES = (str, basestring, unicode)
except NameError:
# python3
_STRING_TYPES = (str,)
def merge_config_fp(cfgin, fp):
merge_config_str(cfgin, fp.read())
def merge_config_str(cfgin, cfgstr):
cfg2 = yaml.safe_load(cfgstr)
if not isinstance(cfg2, dict):
raise TypeError("Failed reading config. not a dictionary: %s" % cfgstr)
merge_config(cfgin, cfg2)
def merge_config(cfg, cfg2):
# merge cfg2 over the top of cfg
for k, v in cfg2.items():
if isinstance(v, dict) and isinstance(cfg.get(k, None), dict):
merge_config(cfg[k], v)
else:
cfg[k] = v
def merge_cmdarg(cfg, cmdarg, delim="/"):
merge_config(cfg, cmdarg2cfg(cmdarg, delim))
def cmdarg2cfg(cmdarg, delim="/"):
if '=' not in cmdarg:
raise ValueError('no "=" in "%s"' % cmdarg)
key, val = cmdarg.split("=", 2)
cfg = {}
cur = cfg
items = key.split(delim)
for item in items[:-1]:
cur[item] = {}
cur = cur[item]
cur[items[-1]] = val
return cfg
def load_config_archive(content):
archive = yaml.load(content)
config = {}
for part in archive:
if isinstance(part, (str,)):
if part.startswith(ARCHIVE_HEADER):
merge_config(config, load_config_archive(part))
elif part.startswith(CONFIG_HEADER):
merge_config_str(config, part)
elif isinstance(part, dict) and isinstance(part.get('content'), str):
payload = part.get('content')
if (part.get('type') == ARCHIVE_TYPE or
payload.startswith(ARCHIVE_HEADER)):
merge_config(config, load_config_archive(payload))
elif (part.get('type') == CONFIG_TYPE or
payload.startswith(CONFIG_HEADER)):
merge_config_str(config, payload)
return config
def load_config(cfg_file):
with open(cfg_file, "r") as fp:
content = fp.read()
if not content.startswith(ARCHIVE_HEADER):
return yaml.safe_load(content)
else:
return load_config_archive(content)
curtin-0.1.0~bzr126/curtin/futil.py 0000644 0000000 0000000 00000004415 12321566163 015321 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import grp
import pwd
import os
from .util import write_file
def chownbyid(fname, uid=None, gid=None):
if uid in [None, -1] and gid in [None, -1]:
return
os.chown(fname, uid, gid)
def decode_perms(perm, default=0o644):
try:
if perm is None:
return default
if isinstance(perm, (int, float)):
# Just 'downcast' it (if a float)
return int(perm)
else:
# Force to string and try octal conversion
return int(str(perm), 8)
except (TypeError, ValueError):
return default
def chownbyname(fname, user=None, group=None):
uid = -1
gid = -1
try:
if user:
uid = pwd.getpwnam(user).pw_uid
if group:
gid = grp.getgrnam(group).gr_gid
except KeyError as e:
raise OSError("Unknown user or group: %s" % (e))
chownbyid(fname, uid, gid)
def extract_usergroup(ug_pair):
if not ug_pair:
return (None, None)
ug_parted = ug_pair.split(':', 1)
u = ug_parted[0].strip()
if len(ug_parted) == 2:
g = ug_parted[1].strip()
else:
g = None
if not u or u == "-1" or u.lower() == "none":
u = None
if not g or g == "-1" or g.lower() == "none":
g = None
return (u, g)
def write_finfo(path, content, owner="-1:-1", perms="0644"):
(u, g) = extract_usergroup(owner)
omode = "w"
if isinstance(content, bytes):
omode = "wb"
write_file(path, content, mode=decode_perms(perms), omode=omode)
chownbyname(path, u, g)
curtin-0.1.0~bzr126/curtin/log.py 0000644 0000000 0000000 00000003766 12321566163 014767 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import logging
class NullHandler(logging.Handler):
def emit(self, record):
pass
def basicConfig(**kwargs):
# basically like logging.basicConfig but only output for our logger
if kwargs.get('filename'):
handler = logging.FileHandler(filename=kwargs['filename'],
mode=kwargs.get('filemode', 'a'))
elif kwargs.get('stream'):
handler = logging.StreamHandler(stream=kwargs['stream'])
else:
handler = NullHandler()
if 'verbosity' in kwargs:
level = ((logging.ERROR, logging.INFO, logging.DEBUG)
[min(kwargs['verbosity'], 2)])
else:
level = kwargs.get('level', logging.NOTSET)
handler.setFormatter(logging.Formatter(fmt=kwargs.get('format'),
datefmt=kwargs.get('datefmt')))
handler.setLevel(level)
logging.getLogger().setLevel(level)
logger = _getLogger()
for h in list(logger.handlers):
logger.removeHandler(h)
logger.setLevel(level)
logger.addHandler(handler)
def _getLogger(name='curtin'):
return logging.getLogger(name)
if not logging.getLogger().handlers:
logging.getLogger().addHandler(NullHandler())
LOG = _getLogger()
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/net/ 0000755 0000000 0000000 00000000000 12321566163 014406 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/curtin/pack.py 0000644 0000000 0000000 00000013574 12321566163 015122 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import errno
import os
import shutil
import tempfile
from . import util
CALL_ENTRY_POINT_PY = """
def call_entry_point(name):
import os, sys
(istr, dot, ent) = name.rpartition('.')
try:
__import__(istr)
except ImportError as e:
# if that import failed, check dirname(__file__/..)
# to support ./bin/curtin with modules in .
_tdir = os.path.abspath(os.path.join(os.path.dirname(__file__), ".."))
sys.path.append(_tdir)
try:
__import__(istr)
except ImportError as e:
sys.stderr.write("Unable to find %s\\n" % name)
sys.exit(2)
sys.exit(getattr(sys.modules[istr], ent)())
"""
MAIN_FOOTER = """
if __name__ == '__main__':
call_entry_point("%s")
"""
def write_exe_wrapper(entrypoint, path=None, interpreter="/usr/bin/python",
mode=0o755):
content = '\n'.join((
"#! %s" % interpreter,
CALL_ENTRY_POINT_PY,
MAIN_FOOTER % entrypoint,
))
if path is not None:
with open(path, "w") as fp:
fp.write(content)
if mode is not None:
os.chmod(path, mode)
else:
return content
def pack(fdout=None, command=None, paths=None, copy_files=None,
add_files=None):
# write to 'fdout' a self extracting file to execute 'command'
# if fdout is None, return content that would be written to fdout.
# add_files is a list of (archive_path, file_content) tuples.
# copy_files is a list of (archive_path, file_path) tuples.
if paths is None:
paths = util.get_paths()
if add_files is None:
add_files = []
if copy_files is None:
copy_files = []
tmpd = None
try:
tmpd = tempfile.mkdtemp()
exdir = os.path.join(tmpd, 'curtin')
os.mkdir(exdir)
bindir = os.path.join(exdir, 'bin')
os.mkdir(bindir)
def not_dot_py(input_d, flist):
# include .py files and directories other than __pycache__
return [f for f in flist if not
(f.endswith(".py") or
(f != "__pycache__" and
os.path.isdir(os.path.join(input_d, f))))]
shutil.copytree(paths['helpers'], os.path.join(exdir, "helpers"))
shutil.copytree(paths['lib'], os.path.join(exdir, "curtin"),
ignore=not_dot_py)
write_exe_wrapper(entrypoint='curtin.commands.main.main',
path=os.path.join(bindir, 'curtin'))
for archpath, filepath in copy_files:
target = os.path.abspath(os.path.join(exdir, archpath))
if not target.startswith(exdir + os.path.sep):
raise ValueError("'%s' resulted in path outside archive" %
archpath)
try:
os.mkdir(os.path.dirname(target))
except OSError as e:
if e.errno == errno.EEXIST:
pass
if os.path.isfile(filepath):
shutil.copy(filepath, target)
else:
shutil.copytree(filepath, target)
for archpath, content in add_files:
target = os.path.abspath(os.path.join(exdir, archpath))
if not target.startswith(exdir + os.path.sep):
raise ValueError("'%s' resulted in path outside archive" %
archpath)
try:
os.mkdir(os.path.dirname(target))
except OSError as e:
if e.errno == errno.EEXIST:
pass
with open(target, "w") as fp:
fp.write(content)
archcmd = os.path.join(paths['helpers'], 'shell-archive')
archout = None
args = [archcmd]
if fdout is not None:
archout = os.path.join(tmpd, 'output')
args.append("--output=%s" % archout)
args.extend(["--bin-path=_pwd_/bin", "--python-path=_pwd_", exdir,
"curtin", "--"])
if command is not None:
args.extend(command)
(out, _err) = util.subp(args, capture=True)
if fdout is None:
if isinstance(out, bytes):
out = out.decode()
return out
else:
with open(archout, "r") as fp:
while True:
buf = fp.read(4096)
fdout.write(buf)
if len(buf) != 4096:
break
finally:
if tmpd:
shutil.rmtree(tmpd)
def pack_install(fdout=None, configs=None, paths=None,
add_files=None, copy_files=None, args=None):
if configs is None:
configs = []
if add_files is None:
add_files = []
if args is None:
args = []
command = ["curtin", "install"]
my_files = []
for n, config in enumerate(configs):
apath = "configs/config-%03d.cfg" % n
my_files.append((apath, config),)
command.append("--config=%s" % apath)
command += args
return pack(fdout=fdout, command=command, paths=paths,
add_files=add_files + my_files, copy_files=copy_files)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/util.py 0000644 0000000 0000000 00000032234 12321566163 015153 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import errno
import os
import shutil
import subprocess
import sys
import tempfile
import time
from .log import LOG
from . import config
_INSTALLED_HELPERS_PATH = "/usr/lib/curtin/helpers"
_INSTALLED_MAIN = "/usr/bin/curtin"
def subp(args, data=None, rcs=None, env=None, capture=False, shell=False,
logstring=False):
if rcs is None:
rcs = [0]
try:
if not logstring:
LOG.debug(("Running command %s with allowed return codes %s"
" (shell=%s, capture=%s)"), args, rcs, shell, capture)
else:
LOG.debug(("Running hidden command to protect sensitive "
"input/output logstring: %s"), logstring)
if not capture:
stdout = None
stderr = None
else:
stdout = subprocess.PIPE
stderr = subprocess.PIPE
stdin = subprocess.PIPE
sp = subprocess.Popen(args, stdout=stdout,
stderr=stderr, stdin=stdin,
env=env, shell=shell)
(out, err) = sp.communicate(data)
if isinstance(out, bytes):
out = out.decode()
if isinstance(err, bytes):
err = err.decode()
except OSError as e:
raise ProcessExecutionError(cmd=args, reason=e)
rc = sp.returncode # pylint: disable=E1101
if rc not in rcs:
raise ProcessExecutionError(stdout=out, stderr=err,
exit_code=rc,
cmd=args)
# Just ensure blank instead of none?? (iff capturing)
if not out and capture:
out = ''
if not err and capture:
err = ''
return (out, err)
def load_command_environment(env=os.environ, strict=False):
mapping = {'scratch': 'WORKING_DIR', 'fstab': 'OUTPUT_FSTAB',
'interfaces': 'OUTPUT_INTERFACES', 'config': 'CONFIG',
'target': 'TARGET_MOUNT_POINT'}
if strict:
missing = [k for k in mapping if k not in env]
if len(missing):
raise KeyError("missing environment vars: %s" % missing)
return {k: env.get(v) for k, v in mapping.items()}
def load_command_config(args, state):
if hasattr(args, 'config') and args.config is not None:
cfg_file = args.config
else:
cfg_file = state.get('config', {})
if not cfg_file:
LOG.debug("config file was none!")
cfg = {}
else:
cfg = config.load_config(cfg_file)
return cfg
class BadUsage(Exception):
pass
class ProcessExecutionError(IOError):
MESSAGE_TMPL = ('%(description)s\n'
'Command: %(cmd)s\n'
'Exit code: %(exit_code)s\n'
'Reason: %(reason)s\n'
'Stdout: %(stdout)r\n'
'Stderr: %(stderr)r')
def __init__(self, stdout=None, stderr=None,
exit_code=None, cmd=None,
description=None, reason=None):
if not cmd:
self.cmd = '-'
else:
self.cmd = cmd
if not description:
self.description = 'Unexpected error while running command.'
else:
self.description = description
if not isinstance(exit_code, int):
self.exit_code = '-'
else:
self.exit_code = exit_code
if not stderr:
self.stderr = ''
else:
self.stderr = stderr
if not stdout:
self.stdout = ''
else:
self.stdout = stdout
if reason:
self.reason = reason
else:
self.reason = '-'
message = self.MESSAGE_TMPL % {
'description': self.description,
'cmd': self.cmd,
'exit_code': self.exit_code,
'stdout': self.stdout,
'stderr': self.stderr,
'reason': self.reason,
}
IOError.__init__(self, message)
class LogTimer(object):
def __init__(self, logfunc, msg):
self.logfunc = logfunc
self.msg = msg
def __enter__(self):
self.start = time.time()
return self
def __exit__(self, etype, value, trace):
self.logfunc("%s took %0.3f seconds" %
(self.msg, time.time() - self.start))
def is_mounted(target, src=None, opts=None):
# return whether or not src is mounted on target
mounts = ""
with open("/proc/mounts", "r") as fp:
mounts = fp.read()
for line in mounts.splitlines():
if line.split()[1] == os.path.abspath(target):
return True
return False
def do_mount(src, target, opts=None):
# mount src at target with opts and return True
# if already mounted, return False
if opts is None:
opts = []
if isinstance(opts, str):
opts = [opts]
if is_mounted(target, src, opts):
return False
ensure_dir(target)
cmd = ['mount'] + opts + [src, target]
subp(cmd)
return True
def do_umount(mountpoint):
if not is_mounted(mountpoint):
return False
subp(['umount', mountpoint])
return True
def ensure_dir(path, mode=None):
try:
os.makedirs(path)
except OSError as e:
if e.errno != errno.EEXIST:
raise
if mode is not None:
os.chmod(path, mode)
def write_file(filename, content, mode=0o644, omode="w"):
ensure_dir(os.path.dirname(filename))
with open(filename, omode) as fp:
fp.write(content)
os.chmod(filename, mode)
def load_file(path, mode="r"):
with open(path, mode) as fp:
return fp.read()
def disable_daemons_in_root(target):
contents = "\n".join(
['#!/bin/sh',
'# see invoke-rc.d for exit codes. 101 is "do not run"',
'while true; do',
' case "$1" in',
' -*) shift;;',
' makedev|x11-common) exit 0;;',
' *) exit 101;;',
' esac',
'done',
''])
fpath = os.path.join(target, "usr/sbin/policy-rc.d")
if os.path.isfile(fpath):
return False
write_file(fpath, mode=0o755, content=contents)
return True
def undisable_daemons_in_root(target):
try:
os.unlink(os.path.join(target, "usr/sbin/policy-rc.d"))
except OSError as e:
if e.errno != errno.ENOENT:
raise
return False
return True
class ChrootableTarget(object):
def __init__(self, target, allow_daemons=False, sys_resolvconf=True):
self.target = target
self.mounts = ["/dev", "/proc", "/sys"]
self.umounts = []
self.disabled_daemons = False
self.allow_daemons = allow_daemons
self.sys_resolvconf = sys_resolvconf
self.rconf_d = None
def __enter__(self):
for p in self.mounts:
tpath = os.path.join(self.target, p[1:])
if do_mount(p, tpath, opts='--bind'):
self.umounts.append(tpath)
if not self.allow_daemons:
self.disabled_daemons = disable_daemons_in_root(self.target)
rconf = os.path.join(self.target, "etc", "resolv.conf")
if (self.sys_resolvconf and
os.path.islink(rconf) or os.path.isfile(rconf)):
rtd = None
try:
rtd = tempfile.mkdtemp(dir=os.path.dirname(rconf))
tmp = os.path.join(rtd, "resolv.conf")
os.rename(rconf, tmp)
self.rconf_d = rtd
shutil.copy("/etc/resolv.conf", rconf)
except:
if rtd:
shutil.rmtree(rtd)
self.rconf_d = None
raise
return self
def __exit__(self, etype, value, trace):
if self.disabled_daemons:
undisable_daemons_in_root(self.target)
for p in reversed(self.umounts):
do_umount(p)
rconf = os.path.join(self.target, "etc", "resolv.conf")
if self.sys_resolvconf and self.rconf_d:
os.rename(os.path.join(self.rconf_d, "resolv.conf"), rconf)
shutil.rmtree(self.rconf_d)
class RunInChroot(ChrootableTarget):
def __call__(self, args, **kwargs):
return subp(['chroot', self.target] + args, **kwargs)
def which(program):
# Return path of program for execution if found in path
def is_exe(fpath):
return os.path.isfile(fpath) and os.access(fpath, os.X_OK)
_fpath, _ = os.path.split(program)
if _fpath:
if is_exe(program):
return program
else:
for path in os.environ["PATH"].split(os.pathsep):
path = path.strip('"')
exe_file = os.path.join(path, program)
if is_exe(exe_file):
return exe_file
return None
def get_paths(curtin_exe=None, lib=None, helpers=None):
# return a dictionary with paths for 'curtin_exe', 'helpers' and 'lib'
# that represent where 'curtin' executable lives, where the 'curtin' module
# directory is (containing __init__.py) and where the 'helpers' directory.
mydir = os.path.realpath(os.path.dirname(__file__))
tld = os.path.realpath(mydir + os.path.sep + "..")
if curtin_exe is None:
if os.path.isfile(os.path.join(tld, "bin", "curtin")):
curtin_exe = os.path.join(tld, "bin", "curtin")
if (curtin_exe is None and
(os.path.basename(sys.argv[0]).startswith("curtin") and
os.path.isfile(sys.argv[0]))):
curtin_exe = os.path.realpath(sys.argv[0])
if curtin_exe is None:
found = which('curtin')
if found:
curtin_exe = found
if (curtin_exe is None and os.path.exists(_INSTALLED_MAIN)):
curtin_exe = _INSTALLED_MAIN
cfile = "common" # a file in 'helpers'
if (helpers is None and
os.path.isfile(os.path.join(tld, "helpers", cfile))):
helpers = os.path.join(tld, "helpers")
if (helpers is None and
os.path.isfile(os.path.join(_INSTALLED_HELPERS_PATH, cfile))):
helpers = _INSTALLED_HELPERS_PATH
return({'curtin_exe': curtin_exe, 'lib': mydir, 'helpers': helpers})
def get_architecture(target=None):
chroot = []
if target is not None:
chroot = ['chroot', target]
out, _ = subp(chroot + ['dpkg', '--print-architecture'],
capture=True)
return out.strip()
def has_pkg_available(pkg, target=None):
chroot = []
if target is not None:
chroot = ['chroot', target]
out, _ = subp(chroot + ['apt-cache', 'pkgnames'], capture=True)
for item in out.splitlines():
if pkg == item.strip():
return True
return False
def has_pkg_installed(pkg, target=None):
chroot = []
if target is not None:
chroot = ['chroot', target]
try:
out, _ = subp(chroot + ['dpkg-query', '--show', '--showformat',
'${db:Status-Abbrev}', pkg],
capture=True)
return out.rstrip() == "ii"
except ProcessExecutionError:
return False
def install_packages(pkglist, aptopts=None, target=None, env=None):
emd = []
apt_inst_cmd = ['apt-get', 'install', '--quiet', '--assume-yes',
'--option=Dpkg::options::=--force-unsafe-io']
if aptopts is None:
aptopts = []
apt_inst_cmd.extend(aptopts)
for ptok in os.environ["PATH"].split(os.pathsep):
if target is None:
fpath = os.path.join(ptok, 'eatmydata')
else:
fpath = os.path.join(target, ptok, 'eatmydata')
if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
emd = ['eatmydata']
break
if isinstance(pkglist, str):
pkglist = [pkglist]
if env is None:
env = os.environ.copy()
env['DEBIAN_FRONTEND'] = 'noninteractive'
marker = "/tmp/curtin.aptupdate"
marker_text = ' '.join(pkglist) + "\n"
apt_update = ['apt-get', 'update', '--quiet']
if target is not None and target != "/":
with RunInChroot(target) as inchroot:
marker = os.path.join(target, marker)
if not os.path.exists(marker):
inchroot(apt_update)
with open(marker, "w") as fp:
fp.write(marker_text)
return inchroot(emd + apt_inst_cmd + list(pkglist), env=env)
else:
if not os.path.exists(marker):
subp(apt_update)
with open(marker, "w") as fp:
fp.write(marker_text)
return subp(emd + apt_inst_cmd + list(pkglist), env=env)
def is_uefi_bootable():
return os.path.exists('/sys/firmware/efi') is True
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/block/__init__.py 0000644 0000000 0000000 00000012333 12321566163 017025 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import errno
import os
import stat
import shlex
from curtin import util
def get_dev_name_entry(devname):
bname = os.path.basename(devname)
return (bname, "/dev/" + bname)
def is_valid_device(devname):
devent = get_dev_name_entry(devname)[1]
try:
return stat.S_ISBLK(os.stat(devent).st_mode)
except OSError as e:
if e.errno != errno.ENOENT:
raise
return False
def _lsblock_pairs_to_dict(lines, key="NAME"):
ret = {}
for line in lines.splitlines():
toks = shlex.split(line)
cur = {}
for tok in toks:
k, v = tok.split("=", 1)
cur[k] = v
cur['device_path'] = get_dev_name_entry(cur['NAME'])[1]
ret[cur['NAME']] = cur
return ret
def _lsblock(args=None):
# lsblk --help | sed -n '/Available/,/^$/p' |
# sed -e 1d -e '$d' -e 's,^[ ]\+,,' -e 's, .*,,' | sort
keys = ['ALIGNMENT', 'DISC-ALN', 'DISC-GRAN', 'DISC-MAX', 'DISC-ZERO',
'FSTYPE', 'GROUP', 'KNAME', 'LABEL', 'LOG-SEC', 'MAJ:MIN',
'MIN-IO', 'MODE', 'MODEL', 'MOUNTPOINT', 'NAME', 'OPT-IO', 'OWNER',
'PHY-SEC', 'RM', 'RO', 'ROTA', 'RQ-SIZE', 'SCHED', 'SIZE', 'STATE',
'TYPE', 'UUID']
if args is None:
args = []
# in order to avoid a very odd error with '-o' and all output fields above
# we just drop one. doesn't really matter which one.
keys.remove('SCHED')
basecmd = ['lsblk', '--noheadings', '--bytes', '--pairs',
'--out=' + ','.join(keys)]
(out, _err) = util.subp(basecmd + list(args), capture=True)
return _lsblock_pairs_to_dict(out)
def get_unused_blockdev_info():
# return a list of unused block devices. These are devices that
# do not have anything mounted on them.
# get a list of top level block devices, then iterate over it to get
# devices dependent on those. If the lsblk call for that specific
# call has nothing 'MOUNTED", then this is an unused block device
bdinfo = _lsblock(['--nodeps'])
unused = {}
for devname, data in bdinfo.items():
cur = _lsblock([data['device_path']])
mountpoints = [x for x in cur if cur[x].get('MOUNTPOINT')]
if len(mountpoints) == 0:
unused[devname] = data
return unused
def get_devices_for_mp(mountpoint):
# return a list of devices (full paths) used by the provided mountpoint
bdinfo = _lsblock()
found = set()
for devname, data in bdinfo.items():
if data['MOUNTPOINT'] == mountpoint:
found.add(data['device_path'])
if found:
return list(found)
# for some reason, on some systems, lsblk does not list mountpoint
# for devices that are mounted. This happens on /dev/vdc1 during a run
# using tools/launch.
with open("/proc/mounts", "r") as fp:
for line in fp:
try:
(dev, mp, vfs, opts, freq, passno) = line.split(None, 5)
if mp == mountpoint:
return [os.path.realpath(dev)]
except ValueError:
continue
return []
def get_installable_blockdevs():
good = []
unused = get_unused_blockdev_info()
for devname, data in unused.iteritems():
if data.get('RO') == "0" and data.get('TYPE') == "disk":
good.append(devname)
return good
def get_blockdev_for_partition(devpath):
# convert an entry in /dev/ to parent disk and partition number
# if devpath is a block device and not a partition, return (devpath, None)
# input of /dev/vdb or /dev/disk/by-label/foo
# rpath is hopefully a real-ish path in /dev (vda, sdb..)
rpath = os.path.realpath(devpath)
bname = os.path.basename(rpath)
syspath = "/sys/class/block/%s" % bname
if not os.path.exists(syspath):
raise ValueError("%s had no syspath (%s)" % (devpath, syspath))
ptpath = os.path.join(syspath, "partition")
if not os.path.exists(ptpath):
return (rpath, None)
ptnum = util.load_file(ptpath).rstrip()
# for a partition, real syspath is something like:
# /sys/devices/pci0000:00/0000:00:04.0/virtio1/block/vda/vda1
rsyspath = os.path.realpath(syspath)
disksyspath = os.path.dirname(rsyspath)
diskmajmin = util.load_file(os.path.join(disksyspath, "dev")).rstrip()
diskdevpath = os.path.realpath("/dev/block/%s" % diskmajmin)
# diskdevpath has something like 253:0
# and udev has put links in /dev/block/253:0 to the device name in /dev/
return (diskdevpath, ptnum)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/__init__.py 0000644 0000000 0000000 00000002036 12321566163 017533 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
def populate_one_subcmd(parser, options_dict, handler):
for ent in options_dict:
args = ent[0]
if not isinstance(args, (list, tuple)):
args = (args,)
parser.add_argument(*args, **ent[1])
parser.set_defaults(func=handler)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/block_meta.py 0000644 0000000 0000000 00000007002 12321566163 020072 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
from collections import OrderedDict
from curtin import block
from curtin import util
from curtin.log import LOG
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('-D', '--devices'),
{'help': 'which devices to operate on', 'action': 'append',
'metavar': 'DEVICE', 'default': None, }),
('--fstype', {'help': 'root filesystem type',
'choices': ['ext4', 'ext3'], 'default': 'ext4'}),
('mode', {'help': 'meta-mode to use', 'choices': ['raid0', 'simple']}),
)
)
def block_meta(args):
# main entry point for the block-meta command.
if args.mode == "simple":
meta_simple(args)
else:
raise NotImplementedError("mode=%s is not implemenbed" % args.mode)
def logtime(msg, func, *args, **kwargs):
with util.LogTimer(LOG.debug, msg):
return func(*args, **kwargs)
def meta_simple(args):
state = util.load_command_environment()
cfg = util.load_command_config(args, state)
devices = args.devices
if devices is None:
devices = cfg.get('block-meta', {}).get('devices', [])
# Remove duplicates but maintain ordering.
devices = list(OrderedDict.fromkeys(devices))
if len(devices) == 0:
devices = block.get_installable_blockdevs()
LOG.warn("simple mode, no devices given. unused list: %s", devices)
if len(devices) > 1:
if args.devices is not None:
LOG.warn("simple mode but multiple devices given. "
"using first found")
available = [f for f in devices
if block.is_valid_device(f)]
target = sorted(available)[0]
LOG.warn("mode is 'simple'. multiple devices given. using '%s' "
"(first available)", target)
else:
target = devices[0]
if not block.is_valid_device(target):
raise Exception("target device '%s' is not a valid device" % target)
(devname, devnode) = block.get_dev_name_entry(target)
LOG.info("installing in simple mode to '%s'", devname)
# helper partition will forcibly set up partition there
if util.is_uefi_bootable():
logtime(
"partition --format uefi %s" % devnode,
util.subp, ("partition", "--format", "uefi", devnode))
else:
logtime(
"partition %s" % devnode,
util.subp, ("partition", devnode))
rootdev = devnode + "1"
cmd = ['mkfs.%s' % args.fstype, '-q', '-L', 'cloudimg-rootfs', rootdev]
logtime(' '.join(cmd), util.subp, cmd)
util.subp(['mount', rootdev, state['target']])
with open(state['fstab'], "w") as fp:
fp.write("LABEL=%s / %s defaults 0 0\n" % ('cloudimg-rootfs', 'ext4'))
return 0
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, block_meta)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/curthooks.py 0000644 0000000 0000000 00000031721 12321566163 020020 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import glob
import os
import platform
import re
import sys
import shutil
from curtin import config
from curtin import block
from curtin import futil
from curtin.log import LOG
from curtin import util
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('-t', '--target'),
{'help': 'operate on target. default is env[TARGET_MOUNT_POINT]',
'action': 'store', 'metavar': 'TARGET', 'default': None}),
(('-c', '--config'),
{'help': 'operate on config. default is env[CONFIG]',
'action': 'store', 'metavar': 'CONFIG', 'default': None}),
)
)
KERNEL_MAPPING = {
'precise': {
'3.2.0': '',
'3.5.0': '-lts-quantal',
'3.8.0': '-lts-raring',
'3.11.0': '-lts-saucy',
'3.13.0': '-lts-trusty',
},
'trusty': {
'3.13.0': '',
},
}
def write_files(cfg, target):
# this takes 'write_files' entry in config and writes files in the target
# config entry example:
# f1:
# path: /file1
# content: !!binary |
# f0VMRgIBAQAAAAAAAAAAAAIAPgABAAAAwARAAAAAAABAAAAAAAAAAJAVAAAAAAA
# f2: {path: /file2, content: "foobar", permissions: '0666'}
if 'write_files' not in cfg:
return
for (key, info) in cfg.get('write_files').items():
if not info.get('path'):
LOG.warn("Warning, write_files[%s] had no 'path' entry", key)
continue
futil.write_finfo(path=target + os.path.sep + info['path'],
content=info.get('content', ''),
owner=info.get('owner', "-1:-1"),
perms=info.get('permissions',
info.get('perms', "0644")))
def apt_config(cfg, target):
# cfg['apt_proxy']
proxy_cfg_path = os.path.sep.join(
[target, '/etc/apt/apt.conf.d/90curtin-aptproxy'])
if cfg.get('apt_proxy'):
util.write_file(
proxy_cfg_path,
content='Acquire::HTTP::Proxy "%s";\n' % cfg['apt_proxy'])
else:
if os.path.isfile(proxy_cfg_path):
os.path.unlink(proxy_cfg_path)
# cfg['apt_mirrors']
# apt_mirrors:
# ubuntu_archive: http://local.archive/ubuntu
# ubuntu_security: http://local.archive/ubuntu
sources_list = os.path.sep.join([target, '/etc/apt/sources.list'])
if (isinstance(cfg.get('apt_mirrors'), dict) and
os.path.isfile(sources_list)):
repls = [
('ubuntu_archive', r'http://\S*[.]*archive.ubuntu.com/\S*'),
('ubuntu_security', r'http://security.ubuntu.com/\S*'),
]
content = None
for name, regex in repls:
mirror = cfg['apt_mirrors'].get(name)
if not mirror:
continue
if content is None:
with open(sources_list) as fp:
content = fp.read()
util.write_file(sources_list + ".dist", content)
content = re.sub(regex, mirror + " ", content)
if content is not None:
util.write_file(sources_list, content)
def disable_overlayroot(cfg, target):
# cloud images come with overlayroot, but installed systems need disabled
disable = cfg.get('disable_overlayroot', True)
local_conf = os.path.sep.join([target, 'etc/overlayroot.local.conf'])
if disable and os.path.exists(local_conf):
LOG.debug("renaming %s to %s", local_conf, local_conf + ".old")
shutil.move(local_conf, local_conf + ".old")
def clean_cloud_init(target):
flist = glob.glob(
os.path.sep.join([target, "/etc/cloud/cloud.cfg.d/*dpkg*"]))
LOG.debug("cleaning cloud-init config from: %s" % flist)
for dpkg_cfg in flist:
os.unlink(dpkg_cfg)
def install_kernel(cfg, target):
kernel_cfg = cfg.get('kernel', {'package': None,
'fallback-package': None,
'mapping': {}})
with util.RunInChroot(target) as in_chroot:
if kernel_cfg is not None:
kernel_package = kernel_cfg.get('package')
kernel_fallback = kernel_cfg.get('fallback-package')
else:
kernel_package = None
kernel_fallback = None
if kernel_package:
util.install_packages([kernel_package], target=target)
return
_, _, kernel, _, _ = os.uname()
out, _ = in_chroot(['lsb_release', '--codename', '--short'],
capture=True)
version, _, flavor = kernel.split('-', 2)
config.merge_config(kernel_cfg['mapping'], KERNEL_MAPPING)
try:
map_suffix = kernel_cfg['mapping'][out.strip()][version]
except KeyError:
LOG.warn("Couldn't detect kernel package to install for %s."
% kernel)
if kernel_fallback is not None:
util.install_packages([kernel_fallback])
return
package = "linux-{flavor}{map_suffix}".format(
flavor=flavor, map_suffix=map_suffix)
out, _ = in_chroot(['apt-cache', 'search', package], capture=True)
if (len(out.strip()) > 0 and
not util.has_pkg_installed(package, target)):
util.install_packages([package], target=target)
else:
LOG.warn("Tried to install kernel %s but package not found."
% package)
if kernel_fallback is not None:
util.install_packages([kernel_fallback], target=target)
def apply_debconf_selections(cfg, target):
# debconf_selections:
# set1: |
# cloud-init cloud-init/datasources multiselect MAAS
# set2: pkg pkg/value string bar
selsets = cfg.get('debconf_selections')
if not selsets:
LOG.debug("debconf_selections was not set in config")
return
# for each entry in selections, chroot and apply them.
# keep a running total of packages we've seen.
pkgs_cfgd = set()
for key, content in selsets.items():
LOG.debug("setting for %s, %s" % (key, content))
util.subp(['chroot', target, 'debconf-set-selections'],
data=content.encode())
for line in content.splitlines():
if line.startswith("#"):
continue
pkg = re.sub(r"[:\s].*", "", line)
pkgs_cfgd.add(pkg)
pkgs_installed = get_installed_packages(target)
LOG.debug("pkgs_cfgd: %s" % pkgs_cfgd)
LOG.debug("pkgs_installed: %s" % pkgs_installed)
need_reconfig = pkgs_cfgd.intersection(pkgs_installed)
if len(need_reconfig) == 0:
LOG.debug("no need for reconfig")
return
# For any packages that are already installed, but have preseed data
# we populate the debconf database, but the filesystem configuration
# would be preferred on a subsequent dpkg-reconfigure.
# so, what we have to do is "know" information about certain packages
# to unconfigure them.
unhandled = []
to_config = []
for pkg in need_reconfig:
if pkg in CONFIG_CLEANERS:
LOG.debug("unconfiguring %s" % pkg)
CONFIG_CLEANERS[pkg](target)
to_config.append(pkg)
else:
unhandled.append(pkg)
if len(unhandled):
LOG.warn("The following packages were installed and preseeded, "
"but cannot be unconfigured: %s", unhandled)
util.subp(['chroot', target, 'dpkg-reconfigure',
'--frontend=noninteractive'] +
list(to_config), data=None)
def get_installed_packages(target=None):
cmd = []
if target is not None:
cmd = ['chroot', target]
cmd.extend(['dpkg-query', '--list'])
(out, _err) = util.subp(cmd, capture=True)
if isinstance(out, bytes):
out = out.decode()
pkgs_inst = set()
for line in out.splitlines():
try:
(state, pkg, other) = line.split(None, 2)
except ValueError:
continue
if state.startswith("hi") or state.startswith("ii"):
pkgs_inst.add(re.sub(":.*", "", pkg))
return pkgs_inst
def setup_grub(cfg, target):
grubcfg = cfg.get('grub', {})
# copy legacy top level name
if 'grub_install_devices' in cfg and 'install_devices' not in grubcfg:
grubcfg['install_devices'] = cfg['grub_install_devices']
if 'install_devices' in grubcfg:
instdevs = grubcfg.get('install_devices')
if isinstance(instdevs, str):
instdevs = [instdevs]
if instdevs is None:
LOG.debug("grub installation disabled by config")
else:
devs = block.get_devices_for_mp(target)
blockdevs = set()
for maybepart in devs:
(blockdev, part) = block.get_blockdev_for_partition(maybepart)
blockdevs.add(blockdev)
instdevs = list(blockdevs)
# UEFI requires grub-efi-{arch}. If a signed version of that package
# exists then it will be installed.
if util.is_uefi_bootable():
arch = util.get_architecture()
pkgs = ['grub-efi-%s' % arch]
# Architecture might support a signed UEFI loader
uefi_pkg_signed = 'grub-efi-%s-signed' % arch
if util.has_pkg_available(uefi_pkg_signed):
pkgs.append(uefi_pkg_signed)
# AMD64 has shim-signed for SecureBoot support
if arch == "amd64":
pkgs.append("shim-signed")
# Install the UEFI packages needed for the architecture
util.install_packages(pkgs, target=target)
env = os.environ.copy()
replace_default = grubcfg.get('replace_linux_default', True)
if str(replace_default).lower() in ("0", "false"):
env['REPLACE_GRUB_LINUX_DEFAULT'] = "0"
else:
env['REPLACE_GRUB_LINUX_DEFAULT'] = "1"
instdevs = [block.get_dev_name_entry(i)[1] for i in instdevs]
LOG.debug("installing grub to %s [replace_default=%s]",
instdevs, replace_default)
with util.ChrootableTarget(target):
args = ['install-grub']
if util.is_uefi_bootable():
args.append("--uefi")
args.append(target)
util.subp(args + instdevs, env=env)
def update_initramfs(target):
with util.RunInChroot(target) as in_chroot:
in_chroot(['update-initramfs', '-u'])
def copy_fstab(fstab, target):
if not fstab:
LOG.warn("fstab variable not in state, not copying fstab")
return
shutil.copy(fstab, os.path.sep.join([target, 'etc/fstab']))
def copy_interfaces(interfaces, target):
if not interfaces:
LOG.warn("no interfaces file to copy!")
return
eni = os.path.sep.join([target, 'etc/network/interfaces'])
shutil.copy(interfaces, eni)
def restore_dist_interfaces(cfg, target):
# cloud images have a link of /etc/network/interfaces into /run
eni = os.path.sep.join([target, 'etc/network/interfaces'])
if not cfg.get('restore_dist_interfaces', True):
return
rp = os.path.realpath(eni)
if (os.path.exists(eni + ".dist") and
(rp.startswith("/run") or rp.startswith(target + "/run"))):
LOG.debug("restoring dist interfaces, existing link pointed to /run")
shutil.move(eni, eni + ".old")
shutil.move(eni + ".dist", eni)
def curthooks(args):
state = util.load_command_environment()
if args.target is not None:
target = args.target
else:
target = state['target']
if target is None:
sys.stderr.write("Unable to find target. "
"Use --target or set TARGET_MOUNT_POINT\n")
sys.exit(2)
cfg = util.load_command_config(args, state)
write_files(cfg, target)
apt_config(cfg, target)
disable_overlayroot(cfg, target)
install_kernel(cfg, target)
apply_debconf_selections(cfg, target)
restore_dist_interfaces(cfg, target)
copy_interfaces(state.get('interfaces'), target)
copy_fstab(state.get('fstab'), target)
# As a rule, ARMv7 systems don't use grub. This may change some
# day, but for now, assume no. They do require the initramfs
# to be updated, and this also triggers boot loader setup via
# flash-kernel.
machine = platform.machine()
if machine.startswith('armv7'):
update_initramfs(target)
else:
setup_grub(cfg, target)
sys.exit(0)
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, curthooks)
CONFIG_CLEANERS = {
'cloud-init': clean_cloud_init,
}
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/extract.py 0000644 0000000 0000000 00000006314 12321566163 017451 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import os
import curtin.config
from curtin.log import LOG
import curtin.util
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('-t', '--target'),
{'help': ('target directory to extract to (root) '
'[default TARGET_MOUNT_POINT]'),
'action': 'store', 'default': os.environ.get('TARGET_MOUNT_POINT')}),
(('sources',),
{'help': 'the sources to install [default read from CONFIG]',
'nargs': '*'}),
)
)
def extract_root_tgz_url(source, target):
curtin.util.subp(args=['sh', '-c',
('wget "$1" --progress=dot:mega -O - |'
'tar -C "$2" -Sxpzf - --numeric-owner'),
'--', source, target])
def extract_root_tgz_file(source, target):
curtin.util.subp(args=['tar', '-C', target, '-Sxpzf', source,
'--numeric-owner'])
def copy_to_target(source, target):
if source.startswith("cp://"):
source = source[5:]
source = os.path.abspath(source)
curtin.util.subp(args=['sh', '-c',
('mkdir -p "$2" && cd "$2" && '
'rsync -aXHAS --one-file-system "$1/" .'),
'--', source, target])
def extract(args):
if not args.target:
raise ValueError("Target must be defined or set in environment")
cfgfile = os.environ.get('CONFIG')
cfg = {}
sources = args.sources
target = args.target
if not sources:
if cfgfile:
cfg = curtin.config.load_config(cfgfile)
if not cfg.get('sources'):
raise ValueError("'sources' must be on cmdline or in config")
sources = cfg.get('sources')
if isinstance(sources, dict):
sources = [sources[k] for k in sorted(sources.keys())]
LOG.debug("Installing sources: %s to target at %s" % (sources, target))
for source in sources:
if source.startswith("cp://"):
copy_to_target(source, target)
elif os.path.isfile(source):
extract_root_tgz_file(source, target)
elif source.startswith("file://"):
extract_root_tgz_file(source[len("file://"):], target)
elif source.startswith("http://") or source.startswith("https://"):
extract_root_tgz_url(source, target)
else:
raise TypeError("do not know how to extract '%s'", source)
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, extract)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/hook.py 0000644 0000000 0000000 00000003030 12321566163 016727 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import os
import curtin.config
from curtin.log import LOG
import curtin.util
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('target',),
{'help': 'finalize the provided directory [default TARGET_MOUNT_POINT]',
'action': 'store', 'default': os.environ.get('TARGET_MOUNT_POINT'),
'nargs': '?'}),
)
)
def hook(args):
if not args.target:
raise ValueError("Target must be provided or set in environment")
LOG.debug("Finalizing %s" % args.target)
target_hook = os.path.join(args.target, "/opt/curtin/finalize")
if os.path.exists(target_hook):
LOG.debug("running %s" % target_hook)
curtin.util.subp(target_hook)
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, hook)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/in_target.py 0000644 0000000 0000000 00000004370 12321566163 017753 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import os
import pty
import subprocess
import sys
from curtin import util
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('-a', '--allow-daemons'),
{'help': 'do not disable daemons via invoke-rc.d',
'action': 'store_true', 'default': False, }),
(('-i', '--interactive'),
{'help': 'use command invoked interactively',
'action': 'store_true', 'default': False}),
(('-t', '--target'),
{'help': 'chroot to target. default is env[TARGET_MOUNT_POINT]',
'action': 'store', 'metavar': 'TARGET',
'default': os.environ.get('TARGET_MOUNT_POINT')}),
('command_args',
{'help': 'run a command chrooted in the target', 'nargs': '*'}),
)
)
def in_target_main(args):
if args.target is not None:
target = args.target
else:
state = util.load_command_environment()
target = state['target']
if args.target is None:
sys.stderr.write("Unable to find target. "
"Use --target or set TARGET_MOUNT_POINT\n")
sys.exit(2)
interactive = sys.stdin.isatty()
exit = 0
cmd = ['chroot', target] + args.command_args
with util.ChrootableTarget(target, allow_daemons=args.allow_daemons):
if interactive:
pty.spawn(cmd)
else:
sp = subprocess.Popen(cmd)
sp.wait()
exit = sp.returncode
sys.exit(exit)
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, in_target_main)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/install.py 0000644 0000000 0000000 00000022015 12321566163 017441 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import argparse
import json
import os
import re
import shlex
import shutil
import tempfile
from curtin import config
from curtin.log import LOG
from curtin import util
from . import populate_one_subcmd
CONFIG_BUILTIN = {
'sources': {},
'stages': ['early', 'partitioning', 'network', 'extract', 'curthooks',
'hook', 'late'],
'extract_commands': {'builtin': ['curtin', 'extract']},
'hook_commands': {'builtin': ['curtin', 'hook']},
'partitioning_commands': {'builtin': ['curtin', 'block-meta', 'simple']},
'curthooks_commands': {'builtin': ['curtin', 'curthooks']},
'late_commands': {'builtin': []},
'network_commands': {'builtin': ['curtin', 'net-meta', 'auto']},
}
class MyAppend(argparse.Action):
def __call__(self, parser, namespace, values, option_string=None):
if getattr(namespace, self.dest, None) is None:
setattr(namespace, self.dest, [])
getattr(namespace, self.dest).append((option_string, values,))
class WorkingDir(object):
def __init__(self, config):
top_d = tempfile.mkdtemp()
state_d = os.path.join(top_d, 'state')
target_d = os.path.join(top_d, 'target')
scratch_d = os.path.join(top_d, 'scratch')
for p in (state_d, target_d, scratch_d):
os.mkdir(p)
interfaces_f = os.path.join(state_d, 'interfaces')
config_f = os.path.join(state_d, 'config')
fstab_f = os.path.join(state_d, 'fstab')
with open(config_f, "w") as fp:
json.dump(config, fp)
# just touch these files to make sure they exist
for f in (interfaces_f, config_f, fstab_f):
with open(f, "ab") as fp:
pass
self.scratch = scratch_d
self.target = target_d
self.top = top_d
self.interfaces = interfaces_f
self.fstab = fstab_f
self.config = config
self.config_file = config_f
def env(self):
return ({'WORKING_DIR': self.scratch, 'OUTPUT_FSTAB': self.fstab,
'OUTPUT_INTERFACES': self.interfaces,
'TARGET_MOUNT_POINT': self.target,
'CONFIG': self.config_file})
class Stage(object):
def __init__(self, name, commands, env):
self.name = name
self.commands = commands
self.env = env
def run(self):
for cmdname in sorted(self.commands.keys()):
cmd = self.commands[cmdname]
if not cmd:
continue
shell = not isinstance(cmd, list)
with util.LogTimer(LOG.debug, cmdname):
try:
util.subp(cmd, shell=shell, env=self.env)
except util.ProcessExecutionError:
LOG.warn("%s command failed", cmdname)
raise
def apply_power_state(pstate):
# power_state:
# delay: 5
# mode: poweroff
# message: Bye Bye
cmd = load_power_state(pstate)
if not cmd:
return
LOG.info("powering off with %s", cmd)
fid = os.fork()
if fid == 0:
try:
util.subp(cmd)
os._exit(0)
except:
LOG.warn("%s returned non-zero" % cmd)
os._exit(1)
return
def load_power_state(pstate):
# returns a command to reboot the system if power_state should.
if pstate is None:
return None
if not isinstance(pstate, dict):
raise TypeError("power_state is not a dict.")
opt_map = {'halt': '-H', 'poweroff': '-P', 'reboot': '-r'}
mode = pstate.get("mode")
if mode not in opt_map:
raise TypeError("power_state[mode] required, must be one of: %s." %
','.join(opt_map.keys()))
delay = pstate.get("delay", "5")
if delay == "now":
delay = "0"
elif re.match(r"\+[0-9]+", str(delay)):
delay = "%sm" % delay[1:]
else:
delay = str(delay)
args = ["shutdown", opt_map[mode], "now"]
if pstate.get("message"):
args.append(pstate.get("message"))
shcmd = ('sleep "$1" && shift; '
'[ -f /run/block-curtin-poweroff ] && exit 0; '
'exec "$@"')
return (['sh', '-c', shcmd, 'curtin-poweroff', delay] + args)
def apply_kexec(kexec, target):
# load kexec kernel from target dir, similar to /etc/init.d/kexec-load
# kexec:
# mode: on
grubcfg = "boot/grub/grub.cfg"
target_grubcfg = os.path.join(target, grubcfg)
if kexec is None or kexec.get("mode") != "on":
return False
if not isinstance(kexec, dict):
raise TypeError("kexec is not a dict.")
if not util.which('kexec'):
util.install_packages('kexec-tools')
if not os.path.isfile(target_grubcfg):
raise ValueError("%s does not exist in target" % grubcfg)
with open(target_grubcfg, "r") as fp:
default = 0
menu_lines = []
# get the default grub boot entry number and menu entry line numbers
for line_num, line in enumerate(fp, 1):
if re.search(r"\bset default=\"[0-9]+\"\b", " %s " % line):
default = int(re.sub(r"[^0-9]", '', line))
if re.search(r"\bmenuentry\b", " %s " % line):
menu_lines.append(line_num)
if not menu_lines:
LOG.error("grub config file does not have a menuentry\n")
return False
# get the begin and end line numbers for default menuentry section,
# using end of file if it's the last menuentry section
begin = menu_lines[default]
if begin != menu_lines[-1]:
end = menu_lines[default + 1] - 1
else:
end = line_num
fp.seek(0)
lines = fp.readlines()
kernel = append = initrd = ""
for i in range(begin, end):
if 'linux' in lines[i].split():
split_line = shlex.split(lines[i])
kernel = os.path.join(target, split_line[1])
append = "--append=" + ' '.join(split_line[2:])
if 'initrd' in lines[i].split():
split_line = shlex.split(lines[i])
initrd = "--initrd=" + os.path.join(target, split_line[1])
if not kernel:
LOG.error("grub config file does not have a kernel\n")
return False
LOG.debug("kexec -l %s %s %s" % (kernel, append, initrd))
util.subp(args=['kexec', '-l', kernel, append, initrd])
return True
def cmd_install(args):
cfg = CONFIG_BUILTIN
for (flag, val) in args.cfgopts:
if flag in ('-c', '--config'):
config.merge_config_fp(cfg, val)
elif flag in ('--set'):
config.merge_cmdarg(cfg, val)
for source in args.source:
cfg['sources']["%02d_cmdline" % len(cfg['sources'])] = source
LOG.debug("merged config: %s" % cfg)
if not len(cfg.get('sources', [])):
raise util.BadUsage("no sources provided to install")
if cfg.get('http_proxy'):
os.environ['http_proxy'] = cfg['http_proxy']
try:
workingd = WorkingDir(cfg)
LOG.debug(workingd.env())
env = os.environ.copy()
env.update(workingd.env())
for name in cfg.get('stages'):
commands_name = '%s_commands' % name
with util.LogTimer(LOG.debug, 'stage_%s' % name):
stage = Stage(name, cfg.get(commands_name, {}), env)
stage.run()
if apply_kexec(cfg.get('kexec'), workingd.target):
cfg['power_state'] = {'mode': 'reboot', 'delay': 'now',
'message': "'rebooting with kexec'"}
finally:
for d in ('sys', 'dev', 'proc'):
util.do_umount(os.path.join(workingd.target, d))
util.do_umount(workingd.target)
shutil.rmtree(workingd.top)
apply_power_state(cfg.get('power_state'))
LOG.info("Finished installation")
print("Installation finished")
CMD_ARGUMENTS = (
((('-c', '--config'),
{'help': 'read configuration from cfg', 'action': MyAppend,
'metavar': 'FILE', 'type': argparse.FileType("rb"),
'dest': 'cfgopts', 'default': []}),
('--set', {'help': 'define a config variable', 'action': MyAppend,
'metavar': 'key=val', 'dest': 'cfgopts'}),
('source', {'help': 'what to install', 'nargs': '*'}),
)
)
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, cmd_install)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/main.py 0000644 0000000 0000000 00000006355 12321566163 016730 0 ustar 0000000 0000000 #!/usr/bin/python
# Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import argparse
import os
import sys
import traceback
from curtin import log
from curtin import util
SUB_COMMAND_MODULES = ['block-meta', 'curthooks', 'extract', 'hook',
'in-target', 'install', 'net-meta', 'pack']
def add_subcmd(subparser, subcmd):
modname = subcmd.replace("-", "_")
subcmd_full = "curtin.commands.%s" % modname
__import__(subcmd_full)
try:
popfunc = getattr(sys.modules[subcmd_full], 'POPULATE_SUBCMD')
except AttributeError:
raise AttributeError("No 'POPULATE_SUBCMD' in %s" % subcmd_full)
popfunc(subparser.add_parser(subcmd))
def main(args=None):
if args is None:
args = sys.argv
parser = argparse.ArgumentParser()
stacktrace = (os.environ.get('CURTIN_STACKTRACE', "0").lower()
not in ("0", "false", ""))
try:
verbosity = int(os.environ.get('CURTIN_VERBOSITY', "0"))
except ValueError:
verbosity = 1
parser.add_argument('--showtrace', action='store_true', default=stacktrace)
parser.add_argument('--verbose', '-v', action='count', default=verbosity)
parser.add_argument('--log-file', default=sys.stderr,
type=argparse.FileType('w'))
subps = parser.add_subparsers(dest="subcmd")
for subcmd in SUB_COMMAND_MODULES:
add_subcmd(subps, subcmd)
args = parser.parse_args(sys.argv[1:])
# if user gave cmdline arguments, then lets set environ so subsequent
# curtin calls get stacktraces.
if args.showtrace and not stacktrace:
os.environ['CURTIN_STACKTRACE'] = "1"
if args.verbose and not verbosity:
os.environ['CURTIN_VERBOSITY'] = str(args.verbose)
if not getattr(args, 'func', None):
# http://bugs.python.org/issue16308
parser.print_help()
sys.exit(1)
log.basicConfig(stream=args.log_file, verbosity=args.verbose)
paths = util.get_paths()
if paths['helpers'] is None or paths['curtin_exe'] is None:
raise OSError("Unable to find helpers or 'curtin' exe to add to path")
path = os.environ['PATH'].split(':')
for cand in (paths['helpers'], os.path.dirname(paths['curtin_exe'])):
if cand not in [os.path.abspath(d) for d in path]:
path.insert(0, cand)
os.environ['PATH'] = ':'.join(path)
try:
sys.exit(args.func(args))
except Exception as e:
if args.showtrace:
traceback.print_exc()
sys.stderr.write("%s\n" % e)
sys.exit(3)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/net_meta.py 0000644 0000000 0000000 00000010511 12321566163 017565 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import argparse
import os
import sys
from curtin import net
from . import populate_one_subcmd
DEVNAME_ALIASES = ['connected', 'configured', 'netboot']
def network_device(value):
if value in DEVNAME_ALIASES:
return value
if (value.startswith('eth') or
(value.startswith('en') and len(value) == 3)):
return value
raise argparse.ArgumentTypeError("%s does not look like a netdev name")
def resolve_alias(alias):
if alias == "connected":
alldevs = net.get_devicelist()
return [d for d in alldevs if
net.is_physical(d) and net.is_up(d)]
elif alias == "configured":
alldevs = net.get_devicelist()
return [d for d in alldevs if
net.is_physical(d) and net.is_up(d) and net.is_connected(d)]
elif alias == "netboot":
# should read /proc/cmdline here for BOOTIF
raise NotImplemented("netboot alias not implemented")
else:
raise ValueError("'%s' is not an alias: %s", alias, DEVNAME_ALIASES)
def interfaces_basic_dhcp(devices):
content = '\n'.join(
[("# This file describes the network interfaces available on "
"your system"),
"# and how to activate them. For more information see interfaces(5).",
"",
"# The loopback network interface",
"auto lo",
"iface lo inet loopback",
])
for d in devices:
content += '\n'.join(("", "", "auto %s" % d,
"iface %s inet dhcp" % d,))
content += "\n"
return content
def net_meta(args):
# curtin net-meta --devices connected dhcp
# curtin net-meta --devices configured dhcp
# curtin net-meta --devices netboot dhcp
eni = "etc/network/interfaces"
if args.mode == "auto":
if not args.devices:
args.devices = ["connected"]
t_eni = None
if args.target:
t_eni = os.path.sep.join((args.target, eni,))
if not os.path.isfile(t_eni):
t_eni = None
if t_eni:
args.mode = "copy"
else:
args.mode = "dhcp"
devices = []
if args.devices:
for dev in args.devices:
if dev in DEVNAME_ALIASES:
devices += resolve_alias(dev)
else:
devices.append(dev)
if args.mode == "copy":
if not args.target:
raise argparse.ArgumentTypeError("mode 'copy' requires --target")
t_eni = os.path.sep.join((args.target, "etc/network/interfaces",))
with open(t_eni, "r") as fp:
content = fp.read()
elif args.mode == "dhcp":
content = interfaces_basic_dhcp(devices)
if args.output == "-":
sys.stdout.write(content)
else:
with open(args.output, "w") as fp:
fp.write(content)
CMD_ARGUMENTS = (
((('-D', '--devices'),
{'help': 'which devices to operate on', 'action': 'append',
'metavar': 'DEVICE', 'type': network_device}),
(('-o', '--output'),
{'help': 'file to write to. defaults to env["OUTPUT_INTERFACES"] or "-"',
'metavar': 'IFILE', 'action': 'store',
'default': os.environ.get('OUTPUT_INTERFACES', "-")}),
(('-t', '--target'),
{'help': 'operate on target. default is env[TARGET_MOUNT_POINT]',
'action': 'store', 'metavar': 'TARGET',
'default': os.environ.get('TARGET_MOUNT_POINT')}),
('mode', {'help': 'meta-mode to use',
'choices': ['dhcp', 'copy', 'auto']})
)
)
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, net_meta)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/commands/pack.py 0000644 0000000 0000000 00000003571 12321566163 016717 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import sys
from curtin import pack
from . import populate_one_subcmd
CMD_ARGUMENTS = (
((('-o', '--output'),
{'help': 'where to write the archive to', 'action': 'store',
'metavar': 'FILE', 'default': "-", }),
(('-a', '--add'),
{'help': 'include FILE_PATH in archive at ARCHIVE_PATH',
'action': 'append', 'metavar': 'ARCHIVE_PATH:FILE_PATH',
'default': []}),
('command_args',
{'help': 'command to run after extracting', 'nargs': '*'}),
)
)
def pack_main(args):
if args.output == "-":
fdout = sys.stdout
else:
fdout = open(args.output, "w")
delim = ":"
addl = []
for tok in args.add:
if delim not in tok:
raise ValueError("'--add' argument '%s' did not have a '%s'",
(tok, delim))
(archpath, filepath) = tok.split(":", 1)
addl.append((archpath, filepath),)
pack.pack(fdout, command=args.command_args, copy_files=addl)
if args.output != "-":
fdout.close()
def POPULATE_SUBCMD(parser):
populate_one_subcmd(parser, CMD_ARGUMENTS, pack_main)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/curtin/net/__init__.py 0000644 0000000 0000000 00000005736 12321566163 016532 0 ustar 0000000 0000000 # Copyright (C) 2013 Canonical Ltd.
#
# Author: Scott Moser
#
# Curtin is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the
# Free Software Foundation, either version 3 of the License, or (at your
# option) any later version.
#
# Curtin is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
# FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for
# more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Curtin. If not, see .
import errno
import os
from curtin.log import LOG
SYS_CLASS_NET = "/sys/class/net/"
def sys_dev_path(devname, path=""):
return SYS_CLASS_NET + devname + "/" + path
def read_sys_net(devname, path, translate=None, enoent=None, keyerror=None):
try:
contents = ""
with open(sys_dev_path(devname, path), "r") as fp:
contents = fp.read().strip()
if translate is None:
return contents
try:
return translate.get(contents)
except KeyError:
LOG.debug("found unexpected value '%s' in '%s/%s'", contents,
devname, path)
if keyerror is not None:
return keyerror
raise
except OSError as e:
if e.errno == errno.ENOENT and enoent is not None:
return enoent
raise
def is_up(devname):
# The linux kernel says to consider devices in 'unknown'
# operstate as up for the purposes of network configuration. See
# Documentation/networking/operstates.txt in the kernel source.
translate = {'up': True, 'unknown': True, 'down': False}
return read_sys_net(devname, "operstate", enoent=False, keyerror=False,
translate=translate)
def is_wireless(devname):
return os.path.exists(sys_dev_path(devname, "wireless"))
def is_connected(devname):
# is_connected isn't really as simple as that. 2 is
# 'physically connected'. 3 is 'not connected'. but a wlan interface will
# always show 3.
try:
iflink = read_sys_net(devname, "iflink", enoent=False)
if iflink == "2":
return True
if not is_wireless(devname):
return False
LOG.debug("'%s' is wireless, basing 'connected' on carrier", devname)
return read_sys_net(devname, "carrier", enoent=False, keyerror=False,
translate={'0': False, '1': True})
except IOError as e:
if e.errno == errno.EINVAL:
return False
raise
def is_physical(devname):
return os.path.exists(sys_dev_path(devname, "device"))
def is_present(devname):
return os.path.exists(sys_dev_path(devname))
def get_devicelist():
return os.listdir(SYS_CLASS_NET)
# vi: ts=4 expandtab syntax=python
curtin-0.1.0~bzr126/debian/changelog.trunk 0000644 0000000 0000000 00000000224 12321566163 016550 0 ustar 0000000 0000000 curtin (0.1.0~bzrREVNO-0ubuntu1) UNRELEASED; urgency=low
* Initial release
-- Scott Moser Mon, 29 Jul 2013 16:12:09 -0400
curtin-0.1.0~bzr126/debian/compat 0000644 0000000 0000000 00000000002 12321566163 014734 0 ustar 0000000 0000000 7
curtin-0.1.0~bzr126/debian/control 0000644 0000000 0000000 00000003556 12321566163 015152 0 ustar 0000000 0000000 Source: curtin
Section: admin
Priority: extra
Standards-Version: 3.9.4
Maintainer: Ubuntu Developers
Build-Depends: debhelper (>= 7),
pep8,
pyflakes,
python-all,
python-nose,
python-setuptools,
python-yaml,
python3,
python3-nose,
python3-setuptools,
python3-yaml
Homepage: http://launchpad.net/curtin
X-Python3-Version: >= 3.2
Package: curtin
Architecture: all
Priority: extra
Depends: python,
python-curtin (= ${binary:Version}),
${misc:Depends},
${python:Depends}
Description: Library and tools for the curtin installer
This package provides the curtin installer.
.
Curtin is an installer that is blunt, brief, snappish, snippety and
unceremonious.
Package: curtin-common
Architecture: all
Priority: extra
Depends: util-linux (>= 2.20.1-1ubuntu3), ${misc:Depends}, ${python:Depends}
Conflicts: curtin (<= 0.1.0~bzr54-0ubuntu1)
Description: Library and tools for curtin installer
This package contains utilities for the curtin installer.
Package: python-curtin
Section: python
Architecture: all
Priority: extra
Depends: curl | wget,
curtin-common (= ${binary:Version}),
util-linux (>= 2.20.1-1ubuntu3),
${misc:Depends},
${python:Depends}
Description: Library and tools for curtin installer
This package provides python library for use by curtin.
Package: python3-curtin
Section: python
Architecture: all
Priority: extra
Conflicts: curtin (<= 0.1.0~bzr54-0ubuntu1)
Depends: curl | wget,
curtin-common (= ${binary:Version}),
util-linux (>= 2.20.1-1ubuntu3),
${misc:Depends},
${python3:Depends}
Description: Library and tools for curtin installer
This package provides python3 library for use by curtin.
curtin-0.1.0~bzr126/debian/copyright 0000644 0000000 0000000 00000001140 12321566163 015465 0 ustar 0000000 0000000 Format: http://www.debian.org/doc/packaging-manuals/copyright-format/1.0/
Upstream-Name: curtin
Upstream-Contact: Scott Moser
Source: https://launchpad.net/curtin
Files: *
Copyright: 2013, Canonical Ltd.
License: AGPL-3
GNU AFFERO GENERAL PUBLIC LICENSE
Version 3, 19 November 2007
.
Copyright (C) 2007 Free Software Foundation, Inc.
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
.
The complete text of the AGPL version 3 can be seen in
http://www.gnu.org/licenses/agpl-3.0.html
curtin-0.1.0~bzr126/debian/curtin-common.install 0000644 0000000 0000000 00000000031 12321566163 017712 0 ustar 0000000 0000000 usr/lib/curtin/helpers/*
curtin-0.1.0~bzr126/debian/curtin.install 0000644 0000000 0000000 00000000012 12321566163 016423 0 ustar 0000000 0000000 usr/bin/*
curtin-0.1.0~bzr126/debian/python-curtin.install 0000644 0000000 0000000 00000000045 12321566163 017750 0 ustar 0000000 0000000 usr/lib/python2*/*-packages/curtin/*
curtin-0.1.0~bzr126/debian/python3-curtin.install 0000644 0000000 0000000 00000000045 12321566163 020033 0 ustar 0000000 0000000 usr/lib/python3*/*-packages/curtin/*
curtin-0.1.0~bzr126/debian/rules 0000755 0000000 0000000 00000000644 12321566163 014622 0 ustar 0000000 0000000 #!/usr/bin/make -f
PYVERS := $(shell pyversions -r)
PY3VERS := $(shell py3versions -r)
%:
dh $@ --with=python2,python3
override_dh_auto_install:
dh_auto_install
set -ex; for python in $(PY3VERS) $(PYVERS); do \
$$python setup.py build --executable=/usr/bin/python && \
$$python setup.py install --root=$(CURDIR)/debian/tmp --install-layout=deb; \
done
chmod 755 $(CURDIR)/debian/tmp/usr/lib/curtin/helpers/*
curtin-0.1.0~bzr126/debian/source/ 0000755 0000000 0000000 00000000000 12321566163 015036 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/debian/source/format 0000644 0000000 0000000 00000000014 12321566163 016244 0 ustar 0000000 0000000 3.0 (quilt)
curtin-0.1.0~bzr126/doc/Makefile 0000644 0000000 0000000 00000012674 12321566163 014533 0 ustar 0000000 0000000 # Makefile for Sphinx documentation
#
# You can set these variables from the command line.
SPHINXOPTS =
SPHINXBUILD = sphinx-build
PAPER =
BUILDDIR = _build
# Internal variables.
PAPEROPT_a4 = -D latex_paper_size=a4
PAPEROPT_letter = -D latex_paper_size=letter
ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
# the i18n builder cannot share the environment and doctrees with the others
I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) .
.PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext
help:
@echo "Please use \`make ' where is one of"
@echo " html to make standalone HTML files"
@echo " dirhtml to make HTML files named index.html in directories"
@echo " singlehtml to make a single large HTML file"
@echo " pickle to make pickle files"
@echo " json to make JSON files"
@echo " htmlhelp to make HTML files and a HTML help project"
@echo " qthelp to make HTML files and a qthelp project"
@echo " devhelp to make HTML files and a Devhelp project"
@echo " epub to make an epub"
@echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
@echo " latexpdf to make LaTeX files and run them through pdflatex"
@echo " text to make text files"
@echo " man to make manual pages"
@echo " texinfo to make Texinfo files"
@echo " info to make Texinfo files and run them through makeinfo"
@echo " gettext to make PO message catalogs"
@echo " changes to make an overview of all changed/added/deprecated items"
@echo " linkcheck to check all external links for integrity"
@echo " doctest to run all doctests embedded in the documentation (if enabled)"
clean:
-rm -rf $(BUILDDIR)/*
html:
$(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
dirhtml:
$(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
@echo
@echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
singlehtml:
$(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
@echo
@echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
pickle:
$(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
@echo
@echo "Build finished; now you can process the pickle files."
json:
$(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
@echo
@echo "Build finished; now you can process the JSON files."
htmlhelp:
$(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
@echo
@echo "Build finished; now you can run HTML Help Workshop with the" \
".hhp project file in $(BUILDDIR)/htmlhelp."
qthelp:
$(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
@echo
@echo "Build finished; now you can run "qcollectiongenerator" with the" \
".qhcp project file in $(BUILDDIR)/qthelp, like this:"
@echo "# qcollectiongenerator $(BUILDDIR)/qthelp/curtin.qhcp"
@echo "To view the help file:"
@echo "# assistant -collectionFile $(BUILDDIR)/qthelp/curtin.qhc"
devhelp:
$(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
@echo
@echo "Build finished."
@echo "To view the help file:"
@echo "# mkdir -p $$HOME/.local/share/devhelp/curtin"
@echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/curtin"
@echo "# devhelp"
epub:
$(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
@echo
@echo "Build finished. The epub file is in $(BUILDDIR)/epub."
latex:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo
@echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
@echo "Run \`make' in that directory to run these through (pdf)latex" \
"(use \`make latexpdf' here to do that automatically)."
latexpdf:
$(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
@echo "Running LaTeX files through pdflatex..."
$(MAKE) -C $(BUILDDIR)/latex all-pdf
@echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
text:
$(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
@echo
@echo "Build finished. The text files are in $(BUILDDIR)/text."
man:
$(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
@echo
@echo "Build finished. The manual pages are in $(BUILDDIR)/man."
texinfo:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo
@echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
@echo "Run \`make' in that directory to run these through makeinfo" \
"(use \`make info' here to do that automatically)."
info:
$(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
@echo "Running Texinfo files through makeinfo..."
make -C $(BUILDDIR)/texinfo info
@echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
gettext:
$(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
@echo
@echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
changes:
$(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
@echo
@echo "The overview file is in $(BUILDDIR)/changes."
linkcheck:
$(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
@echo
@echo "Link check complete; look for any errors in the above output " \
"or in $(BUILDDIR)/linkcheck/output.txt."
doctest:
$(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
@echo "Testing of doctests in the sources finished, look at the " \
"results in $(BUILDDIR)/doctest/output.txt."
curtin-0.1.0~bzr126/doc/conf.py 0000644 0000000 0000000 00000017032 12321566163 014363 0 ustar 0000000 0000000 # -*- coding: utf-8 -*-
#
# curtin documentation build configuration file, created by
# sphinx-quickstart on Thu May 30 16:03:34 2013.
#
# This file is execfile()d with the current directory set to its containing dir.
#
# Note that not all possible configuration values are present in this
# autogenerated file.
#
# All configuration values have a default; values that are commented out
# serve to show the default.
import sys, os
# If extensions (or modules to document with autodoc) are in another directory,
# add these directories to sys.path here. If the directory is relative to the
# documentation root, use os.path.abspath to make it absolute, like shown here.
#sys.path.insert(0, os.path.abspath('.'))
# -- General configuration -----------------------------------------------------
# If your documentation needs a minimal Sphinx version, state it here.
#needs_sphinx = '1.0'
# Add any Sphinx extension module names here, as strings. They can be extensions
# coming with Sphinx (named 'sphinx.ext.*') or your custom ones.
extensions = []
# Add any paths that contain templates here, relative to this directory.
templates_path = ['templates']
# The suffix of source filenames.
source_suffix = '.rst'
# The encoding of source files.
#source_encoding = 'utf-8-sig'
# The master toctree document.
master_doc = 'index'
# General information about the project.
project = u'curtin'
copyright = u'2013, Scott Moser'
# The version info for the project you're documenting, acts as replacement for
# |version| and |release|, also used in various other places throughout the
# built documents.
#
# The short X.Y version.
version = '0.3'
# The full version, including alpha/beta/rc tags.
release = '0.3'
# The language for content autogenerated by Sphinx. Refer to documentation
# for a list of supported languages.
#language = None
# There are two options for replacing |today|: either, you set today to some
# non-false value, then it is used:
#today = ''
# Else, today_fmt is used as the format for a strftime call.
#today_fmt = '%B %d, %Y'
# List of patterns, relative to source directory, that match files and
# directories to ignore when looking for source files.
exclude_patterns = ['_build']
# The reST default role (used for this markup: `text`) to use for all documents.
#default_role = None
# If true, '()' will be appended to :func: etc. cross-reference text.
#add_function_parentheses = True
# If true, the current module name will be prepended to all description
# unit titles (such as .. function::).
#add_module_names = True
# If true, sectionauthor and moduleauthor directives will be shown in the
# output. They are ignored by default.
#show_authors = False
# The name of the Pygments (syntax highlighting) style to use.
pygments_style = 'sphinx'
# A list of ignored prefixes for module index sorting.
#modindex_common_prefix = []
# -- Options for HTML output ---------------------------------------------------
# The theme to use for HTML and HTML Help pages. See the documentation for
# a list of builtin themes.
html_theme = 'default'
# Theme options are theme-specific and customize the look and feel of a theme
# further. For a list of options available for each theme, see the
# documentation.
#html_theme_options = {}
# Add any paths that contain custom themes here, relative to this directory.
#html_theme_path = []
# The name for this set of Sphinx documents. If None, it defaults to
# " v documentation".
#html_title = None
# A shorter title for the navigation bar. Default is the same as html_title.
#html_short_title = None
# The name of an image file (relative to this directory) to place at the top
# of the sidebar.
#html_logo = None
# The name of an image file (within the static path) to use as favicon of the
# docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
# pixels large.
#html_favicon = None
# Add any paths that contain custom static files (such as style sheets) here,
# relative to this directory. They are copied after the builtin static files,
# so a file named "default.css" will overwrite the builtin "default.css".
html_static_path = ['static']
# If not '', a 'Last updated on:' timestamp is inserted at every page bottom,
# using the given strftime format.
#html_last_updated_fmt = '%b %d, %Y'
# If true, SmartyPants will be used to convert quotes and dashes to
# typographically correct entities.
#html_use_smartypants = True
# Custom sidebar templates, maps document names to template names.
#html_sidebars = {}
# Additional templates that should be rendered to pages, maps page names to
# template names.
#html_additional_pages = {}
# If false, no module index is generated.
#html_domain_indices = True
# If false, no index is generated.
#html_use_index = True
# If true, the index is split into individual pages for each letter.
#html_split_index = False
# If true, links to the reST sources are added to the pages.
#html_show_sourcelink = True
# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
#html_show_sphinx = True
# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
#html_show_copyright = True
# If true, an OpenSearch description file will be output, and all pages will
# contain a tag referring to it. The value of this option must be the
# base URL from which the finished HTML is served.
#html_use_opensearch = ''
# This is the file name suffix for HTML files (e.g. ".xhtml").
#html_file_suffix = None
# Output file base name for HTML help builder.
htmlhelp_basename = 'curtindoc'
# -- Options for LaTeX output --------------------------------------------------
latex_elements = {
# The paper size ('letterpaper' or 'a4paper').
#'papersize': 'letterpaper',
# The font size ('10pt', '11pt' or '12pt').
#'pointsize': '10pt',
# Additional stuff for the LaTeX preamble.
#'preamble': '',
}
# Grouping the document tree into LaTeX files. List of tuples
# (source start file, target name, title, author, documentclass [howto/manual]).
latex_documents = [
('index', 'curtin.tex', u'curtin Documentation',
u'Scott Moser', 'manual'),
]
# The name of an image file (relative to this directory) to place at the top of
# the title page.
#latex_logo = None
# For "manual" documents, if this is true, then toplevel headings are parts,
# not chapters.
#latex_use_parts = False
# If true, show page references after internal links.
#latex_show_pagerefs = False
# If true, show URL addresses after external links.
#latex_show_urls = False
# Documents to append as an appendix to all manuals.
#latex_appendices = []
# If false, no module index is generated.
#latex_domain_indices = True
# -- Options for manual page output --------------------------------------------
# One entry per manual page. List of tuples
# (source start file, name, description, authors, manual section).
man_pages = [
('index', 'curtin', u'curtin Documentation',
[u'Scott Moser'], 1)
]
# If true, show URL addresses after external links.
#man_show_urls = False
# -- Options for Texinfo output ------------------------------------------------
# Grouping the document tree into Texinfo files. List of tuples
# (source start file, target name, title, author,
# dir menu entry, description, category)
texinfo_documents = [
('index', 'curtin', u'curtin Documentation',
u'Scott Moser', 'curtin', 'One line description of project.',
'Miscellaneous'),
]
# Documents to append as an appendix to all manuals.
#texinfo_appendices = []
# If false, no module index is generated.
#texinfo_domain_indices = True
# How to display URL addresses: 'footnote', 'no', or 'inline'.
#texinfo_show_urls = 'footnote'
curtin-0.1.0~bzr126/doc/devel/ 0000755 0000000 0000000 00000000000 12321566163 014160 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/doc/index.rst 0000644 0000000 0000000 00000001136 12321566163 014723 0 ustar 0000000 0000000 .. curtin documentation master file, created by
sphinx-quickstart on Thu May 30 16:03:34 2013.
You can adapt this file completely to your liking, but it should at least
contain the root `toctree` directive.
Welcome to curtin's documentation!
==================================
This is 'curtin', the curt installer. It is blunt, brief, snappish, snippety and unceremonious. Its goal is to install an operating system as quick as possible.
Contents:
.. toctree::
:maxdepth: 2
topics/overview
Indices and tables
==================
* :ref:`genindex`
* :ref:`modindex`
* :ref:`search`
curtin-0.1.0~bzr126/doc/topics/ 0000755 0000000 0000000 00000000000 12321566163 014362 5 ustar 0000000 0000000 curtin-0.1.0~bzr126/doc/devel/README.txt 0000644 0000000 0000000 00000004354 12321566163 015664 0 ustar 0000000 0000000 ## curtin development ##
This document describes how to use kvm and ubuntu cloud images
to develop curtin or test install configurations inside kvm.
## get some dependencies ##
sudo apt-get -qy install kvm libvirt-bin cloud-utils bzr
## get cloud image to boot (-disk1.img) and one to install (-root.tar.gz)
mkdir -p ~/download
DLDIR=$( cd ~/download && pwd )
rel="precise"
rel="raring"
burl="http://cloud-images.ubuntu.com/$rel/current/"
for f in $rel-server-cloudimg-amd64-root.tar.gz $rel-server-cloudimg-amd64-disk1.img; do
wget "$burl/$f" -O $DLDIR/$f; done
( cd $DLDIR && qemu-img convert -O qcow $rel-server-cloudimg-amd64-disk1.img $rel-server-cloudimg-amd64-disk1.qcow2)
BOOTIMG="$DLDIR/$rel-server-cloudimg-amd64-disk1.qcow2"
ROOTTGZ="$DLDIR/$rel-server-cloudimg-amd64-root.tar.gz"
## get curtin
mkdir -p ~/src
bzr init-repo ~/src/curtin
( cd ~/src/curtin && bzr branch lp:curtin trunk.dist )
( cd ~/src/curtin && bzr branch trunk.dist trunk )
## get xkvm
mkdir -p ~/bin/
wget "http://sn.im/xkvm" -O ~/bin/xkvm
chmod 755 ~/bin/xkvm
which xkvm || PATH=$HOME/bin:$PATH
## work with curtin
cd ~/src/curtin/trunk
# use 'launch' to launch a kvm instance with user data to pack
# up local curtin and run it inside instance.
./tools/launch $BOOTIMG --publish $ROOTTGZ curtin install "PUBURL/${ROOTTGZ##*/}"
## notes about 'launch' ##
* launch has --help so you can see that for some info.
* '--publish' adds a web server at ${HTTP_PORT:-9923}
and puts the files you want available there. You can reference
this url in config or cmdline with 'PUBURL'. For example
'--publish foo.img' will put 'foo.img' at PUBURL/foo.img.
* launch sets 'ubuntu' user password to 'passw0rd'
* launch runs 'kvm -curses'
kvm -curses keyboard info:
'alt-2' to go to qemu console
* launch puts serial console to 'serial.log' (look there for stuff)
* when logged in
* you can look at /var/log/cloud-init-output.log
* archive should be extracted in /curtin
* shell archive should be in /var/lib/cloud/instance/scripts/part-002
* when logged in, and archive available at
## other notes ##
* need to add '--install-deps' or something for curtin
cloud-image in 12.04 has no 'python3'
ideally 'curtin --install-deps install' would get the things it needs
curtin-0.1.0~bzr126/doc/topics/overview.rst 0000644 0000000 0000000 00000011733 12321566163 016767 0 ustar 0000000 0000000 ========
Overview
========
Curtin is intended to be a bare bones "installer". Its goal is to take data from a source, and get it onto disk as quick as possible and then boot it. The key difference from traditional package based installers is that curtin assumes the thing its installing is intelligent and will do the right thing.
Stages
------
A usage of curtin will go through the following stages:
- Install Environment boot
- Early Commands
- Partitioning
- Network Discovery and Setup
- Extraction of sources
- Hook for installed OS to customize itself
- Final Commands
Install Environment boot
~~~~~~~~~~~~~~~~~~~~~~~~
At the moment, curtin doesn't address how the system that it is running on is booted. It could be booted from a live-cd or from a pxe boot environment. It could even be booted off a disk in the system (although installation to that disk would probably break things).
Curtin's assumption is that a fairly rich linux (Ubuntu) environment is booted.
Early Commands
~~~~~~~~~~~~~~
Early commands are executed on the system, and non-zero exit status will terminate the installation process. These commands are intended to be used for things like
- module loading
- hardware setup
- environment setup for subsequent stages of curtin.
**Config Example**::
early_commands:
05_load_loop: [modprobe, loop]
99_update: apt-get update && apt-get dist-upgrade
Partitioning
~~~~~~~~~~~~
Partitioning covers setting up filesystems on the system. A series of commands are run serially in order. At the end, a fstab formated file must be populated in ``OUTPUT_FSTAB`` that contains mount information, and the filesystems are expected to be mounted at the ``TARGET_MOUNT_POINT``.
Any commands can be used to create this filesystem, but curtin contains some tools to facilitate with this process.
**Config Example**::
paritioning_commands:
10_wipe_filesystems: curtin wipe --quick --all-unused-disks
50_setup_raid: curtin disk-setup --all-disks raid0 /
**Command environment**
Partitioning commands have the following environment variables available to them:
- ``WORKING_DIR``: This is simply for some sort of inter-command state. It will be the same directory for each command run and will only be deleted at the end of all partitioning_commands.
- ``OUTPUT_FSTAB``: This is the target path for a fstab file. After all partitioning commands have been run, a file should exist, formated per fstab(5) that describes how the filesystems should be mounted.
- ``TARGET_MOUNT_POINT``:
Network Discovery and Setup
~~~~~~~~~~~~~~~~~~~~~~~~~~~
Networking is done in a similar fashion to partitioning. A series of commands, specified in the config are run. At the end of these commands, a interfaces(5) style file is expected to be written to ``OUTPUT_INTERFACES``.
Note, that as with fstab, this file is not copied verbatum to the target filesystem, but rather made availble to the OS customization stage. That stage may just copy the file verbatum, but may also parse it, and use that as input.
**Config Example**::
network_commands:
10_netconf: curtin network copy-existing
**Command environment**
Networking commands have the following environment variables available to them:
- ``WORKING_DIR``: This is simply for some sort of inter-command state. It will be the same directory for each command run and will only be deleted at the end of all network_commands.
- ``OUTPUT_INTERFACES``: This is the target path for an interfaces style file. After all commands have been run, a file should exist, formated per interfaces(5) that describes the systems network setup.
Extraction of sources
~~~~~~~~~~~~~~~~~~~~~
Sources are the things to install. Curtin prefers to install root filesystem tar files.
**Config Example**::
sources:
05_primary: http://cloud-images.ubuntu.com/releases/precise/release/ubuntu-12.04-server-cloudimg-amd64-root.tar.gz
Given the source above, curtin will essentiall do a::
wget $URL | tar -Sxvzf
Hook for installed OS to customize itself
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
After extraction of sources, the source that was extracted is then given a chance to customize itself for the system. This customization may include:
- ensuring that appropriate device drivers are loaded on first boot
- consuming the network interfaces file and applying its declarations.
- ensuring that necessary packages
**Config Example**::
config_hook: {{TARGET_MP}}/opt/curtin/config-hook
**Command environment**
- ``INTERFACES``: This is a path to the file created during networking stage
- ``FSTAB``: This is a path to the file created during partitioning stage
- ``CONFIG``: This is a path to the curtin config file. It is provided so that additional configuration could be provided through to the OS customization.
**Helpers**
Curtin provides some helpers to make the OS customization easier.
- `curtin in-target`: run the command while chrooted into the target.
Final Commands
~~~~~~~~~~~~~~
**Config Example**::
final_commands:
05_callhome_finished: wget http://example.com/i-am-done
curtin-0.1.0~bzr126/examples/basic.yaml 0000644 0000000 0000000 00000000660 12321566163 016101 0 ustar 0000000 0000000 early_commands:
98_update: apt-get update
99_upgrade: DEBIAN_FRONTEND=noninteractive apt-get dist-upgrade --assume-yes
partitioning_commands:
10_partition: curtin block-meta --device=/dev/vdc simple
network_commands:
10_network: curtin net-meta --device=eth0 dhcp
sources:
05_primary: "http://cloud-images.ubuntu.com/releases/precise/release/ubuntu-12.04-server-cloudimg-amd64-root.tar.gz"
# vi: ts=4 expandtab syntax=yaml
curtin-0.1.0~bzr126/helpers/common 0000644 0000000 0000000 00000033340 12321566163 015174 0 ustar 0000000 0000000 #!/bin/bash
TEMP_D=""
error() { echo "$@" 1>&1; }
debug() { [ ${VERBOSITY:-0} -lt "$1" ] || error "$@"; }
partition_main_usage() {
cat </dev/null 2>&1 ||
{ error "failed to zero beginning of $target"; return 1; }
out=$(dd if=/dev/zero conv=notrunc of="$target" bs=1024 \
seek=$(((size/1024)-1024)) count=1024 2>&1)
[ $? -eq 0 ] ||
{ error "failed to wipe end of $target [$size]: $out"; return 1; }
if [ -b "$target" ]; then
blockdev --rereadpt "$target"
udevadm settle
fi
}
pt_gpt() {
local target="$1" end=${2:-""} size="" s512="" ptype="L"
local start="2048" pt1size="" maxend=""
local isblk=false
getsize "$target" ||
{ error "failed to get size of $target"; return 1; }
size="$_RET"
if [ -z "$end" ]; then
end=$(($size/512))
else
end=$(($end/512))
fi
maxend=$((($size/512)-2048))
[ "$end" -gt "$maxend" ] && end="$maxend"
debug 1 "maxend=$maxend end=$end size=$size"
[ -b "$target" ] && isblk=true
sgdisk --new "15:2048:+1M" --typecode=15:ef02 \
--new "1::$end" --typecode=1:8300 "$target" ||
{ error "failed to gpt partition $target"; return 1; }
if $isblk; then
blockdev --rereadpt "$target"
udevadm settle
[ -b "${target}1" ] ||
{ error "no partition found ${target}1"; return 1; }
[ -b "${target}15" ] ||
{ error "no partition found ${target}15"; return 1; }
fi
}
pt_uefi() {
local target="$1" end=${2:-""} size="" s512="" ptype="L"
local start="2048" pt1size="" maxend=""
local isblk=false
getsize "$target" ||
{ error "failed to get size of $target"; return 1; }
size="$_RET"
if [ -z "$end" ]; then
end=$(($size/512))
else
end=$(($end/512))
fi
maxend=$((($size/512)-2048))
[ "$end" -gt "$maxend" ] && end="$maxend"
debug 1 "maxend=$maxend end=$end size=$size"
[ -b "$target" ] && isblk=true
# Part 15 is the UEFI partition, part 1 is root
sgdisk --new "15:2048:+512M" --typecode=15:ef00 "$target" \
--new "1::$end" --typecode=1:8300 "$target" ||
{ error "failed to sgdisk for uefi to $target"; return 1; }
if $isblk; then
blockdev --rereadpt "$target"
udevadm settle
[ -b "${target}1" ] ||
{ error "no partition found ${target}1"; return 1; }
[ -b "${target}15" ] ||
{ error "no partition found ${target}15"; return 1; }
fi
mkfs -t vfat -F 32 -n uefi-boot ${target}15 ||
{ error "failed to partition ${target}15 for UEFI vfat"; return 1; }
}
pt_mbr() {
local target="$1" end=${2:-""} size="" s512="" ptype="L"
local start="2048" pt1size="" maxsize="4294967296"
local isblk=false
getsize "$target" ||
{ error "failed to get size of $target"; return 1; }
size="$_RET"
if [ "$(($size/512))" -gt "$maxsize" ]; then
debug 1 "disk is larger than max for mbr (2TB)"
s512=$maxsize
else
s512=$(($size/512))
fi
if [ -n "$end" ]; then
pt1size=$(((end/512)-2048))
else
pt1size=$((s512-2048))
fi
[ -b "$target" ] && isblk=true
# interact with sfdisk in units of 512 bytes (--unit S)
# we start all partitions at 2048 of those (1M)
local sfdisk_out="" sfdisk_in="2048,$pt1size,$ptype,*" sfdisk_cmd=""
sfdisk_cmd=( sfdisk --no-reread --force --Linux --unit S "$target" )
debug 1 "sfdisking with: echo '$sfdisk_in' | ${sfdisk_cmd[*]}"
sfdisk_out=$(echo "$sfdisk_in" | "${sfdisk_cmd[@]}" 2>&1)
ret=$?
[ $ret -eq 0 ] || {
error "failed to partition $target [${sfdisk_out}]";
return 1;
}
if $isblk; then
blockdev --rereadpt "$target"
udevadm settle
[ -b "${target}1" ] ||
{ error "no partition found ${target}1"; return 1; }
fi
out=$(wipefs "--offset=$(($start*512))" "$target" 2>&1) || {
error "$out";
error "failed to wipefs first partition of $target";
return 1;
}
}
partition_main() {
local short_opts="hE:f:v"
local long_opts="help,end:,format:,verbose"
local getopt_out=$(getopt --name "${0##*/}" \
--options "${short_opts}" --long "${long_opts}" -- "$@") &&
eval set -- "${getopt_out}" ||
{ partition_main_usage 1>&2; return 1; }
local cur="" next=""
local format="mbr" target="" end=""
while [ $# -ne 0 ]; do
cur="$1"; next="$2";
case "$cur" in
-h|--help) partition_main_usage ; exit 0;;
-f|--format) format=$next; shift;;
-E|--end) end=$next; shift;;
-v|--verbose) VERBOSITY=$((${VERBOSITY}+1));;
--) shift; break;;
esac
shift;
done
[ $# -gt 1 ] && { partition_main_usage "got $# args, expected 1" 1>&2; return 1; }
[ $# -eq 0 ] && { partition_main_usage "must provide target-dev" 1>&2; return 1; }
target="$1"
if [ -n "$end" ]; then
human2bytes "$end" ||
{ error "failed to convert '$end' to bytes"; return 1; }
end="$_RET"
fi
[ "$format" = "gpt" -o "$format" = "mbr" -o "$format" = "uefi" ] ||
{ partition_main_usage "invalid format: $format" 1>&2; return 1; }
TEMP_D=$(mktemp -d "${TMPDIR:-/tmp}/${0##*/}.XXXXXX") ||
fail "failed to make tempdir"
[ -e "$target" ] || { error "$target does not exist"; return 1; }
[ -f "$target" -o -b "$target" ] ||
{ error "$target not a block device"; return 1; }
wipedev "$target" ||
{ error "wiping $target failed"; return 1; }
if [ "$format" = "mbr" ]; then
pt_mbr "$target" "$end"
elif [ "$format" = "gpt" ]; then
pt_gpt "$target" "$end"]
elif [ "$format" = "uefi" ]; then
pt_uefi "$target" "$end"
fi
trap cleanup EXIT
return 0
}
human2bytes() {
# converts size suitable for input to resize2fs to bytes
# s:512 byte sectors, K:kilobytes, M:megabytes, G:gigabytes
# none: block size of the image
local input=${1} defunit=${2:-1024}
local unit count;
case "$input" in
*s) count=${input%s}; unit=512;;
*K) count=${input%K}; unit=1024;;
*M) count=${input%M}; unit=$((1024*1024));;
*G) count=${input%G}; unit=$((1024*1024*1024));;
*) count=${input} ; unit=${defunit};;
esac
_RET=$((${count}*${unit}))
}
getsize() {
local target="$1"
if [ -b "$target" ]; then
_RET=$(blockdev --getsize64 "$target")
elif [ -f "$target" ]; then
_RET=$(stat "--format=%s" "$target")
else
return 1;
fi
}
is_md() {
case "${1##*/}" in
md[0-9]) return 0;;
esac
return 1
}
install_grub() {
local long_opts="uefi"
local getopt_out="" mp_efi=""
getopt_out=$(getopt --name "${0##*/}" \
--options "" --long "${long_opts}" -- "$@") &&
eval set -- "${getopt_out}"
local uefi=0
while [ $# -ne 0 ]; do
cur="$1"; next="$2";
case "$cur" in
--uefi) uefi=$((${uefi}+1));;
--) shift; break;;
esac
shift;
done
[ $# -lt 2 ] && { grub_install_usage "must provide mount-point and target-dev" 1>&2; return 1; }
local mp="$1"
local cmdline tmp r=""
shift
local grubdevs
grubdevs=( "$@" )
# find the mp device
mp_dev=$(awk -v MP=${mp} '$2==MP {print$1}' /proc/mounts)
r=$?
if [ $r -ne 0 -a $r -ne 1 ]; then
error "unable to determine device for mount $mp";
return 1;
fi
[ -b $mp_dev ] || { error "$mp_dev is not a block device!"; return 1; }
# set correct grub package
local grub_name="grub-pc"
local grub_target="i386-pc"
if [ "$uefi" -ge 1 ]; then
dpkg_arch=$(chroot "$mp" dpkg --print-architecture)
r=$?
if [ $r -ne 0 -a $r -ne 1 ]; then
error "failed to get dpkg architecture"
return 1;
fi
grub_name="grub-efi-$dpkg_arch"
if [ "$dpkg_arch" = "amd64" ]; then
grub_target="x86_64-efi"
fi
fi
# check that the grub package is installed
tmp=$(chroot "$mp" dpkg-query --show \
--showformat='${Status}\n' $grub_name)
r=$?
if [ $r -ne 0 -a $r -ne 1 ]; then
error "failed to check if $grub_name installed";
return 1;
fi
case "$tmp" in
install\ ok\ installed) :;;
*) debug 1 "$grub_name not installed, not doing anything";
return 0;;
esac
# check that mount point has efi partition, and that its mounted
# at /boot/efi and added to the fstab
if [ "$uefi" -ge 1 ]; then
# this assumes that the device was '/dev/xxx[0-9]' and the efi is 15.
local efi_dev="${mp_dev%[0-9]}15"
[ -b ${efi_dev} ] || { error "no UEFI partition on ${efi_dev}"; return 1; }
fslabel=$(blkid -s LABEL -o value "${efi_dev}")
fstype=$(blkid -s TYPE -o value "${efi_dev}")
[ "$fstype" = "vfat" ] || { error "${efi_dev} is not a vfat fs"; return 1; }
[ -n "$fslabel" ] || { error "no label on EFI device"; return 1; }
mp_efi=$(lsblk --nodeps -n --out "MOUNTPOINT" ${efi_dev})
[ -z "$mp_efi" ] || umount "$mp_efi"
if [ ! -e "$mp/boot/efi" ]; then
mkdir -p "$mp/boot/efi" || { error "failed to mount EFI partition"; return 1; }
mount "$efi_dev" "$mp/boot/efi" || { error "unable to mount efi part"; return 1; }
mp_efi="$mp/boot/efi"
fi
echo "LABEL=${fslabel} /boot/efi vfat defaults 0 0" >> "$mp/etc/fstab"
fi
# copy anything after '--' on cmdline to install'd cmdline
read cmdline < /proc/cmdline
local reconf="" newargs=""
tmp="${cmdline##* -- }"
if [ "$tmp" != "$cmdline" ]; then
# there was an explicit '--', so copy stuff some after it
newargs=$(set -f;
c="";
for p in ${cmdline##* -- }; do
case "$p" in
(BOOTIF=*|initrd=*|BOOT_IMAGE=*) continue;;
esac
c="$c $p";
done
echo "${c# }"
)
elif [ "${cmdline#* console=}" != "${cmdline}" ]; then
# there are 'console=' params, copy those.
newargs=$(set -f; c=""; for p in $cmdline; do
[ "${p#console}" = "$p" ] || c="$c $p"; done; echo "${c# }")
fi
if [ "${REPLACE_GRUB_LINUX_DEFAULT:-1}" != "0" ]; then
local n="GRUB_CMDLINE_LINUX_DEFAULT"
local sede="s|$n=.*|$n=\"$newargs\"|"
sed -i "$sede" "$mp/etc/default/grub" ||
{ error "failed to update /etc/default/grub"; return 1; }
grep "$n" "$mp/etc/default/grub"
reconf="dpkg-reconfigure $grub_name"
debug 1 "updating cmdline to '${newargs}'"
# LP: #1179940 . this fix was applied to raring, which
# made changes above not stick. This might not be the best
# way to handle this, but we'll do it for now.
local cicfg="etc/default/grub.d/50-cloudimg-settings.cfg"
if [ -f "$mp/$cicfg" ]; then
debug 1 "moved $cicfg out of the way"
mv "$mp/$cicfg" "$mp/$cicfg.disabled"
fi
fi
local short="" bd="" grubdev grubdevs_new=""
grubdevs_new=()
for grubdev in "${grubdevs[@]}"; do
if is_md "$grubdev"; then
short=${grubdev##*/}
for bd in "/sys/block/$short/slaves/"/*; do
[ -d "$bd" ] || continue
bd=${bd##*/}
bd="/dev/${bd%[0-9]}" # hack: part2bd
grubdevs_new[${#grubdevs_new[@]}]="$bd"
done
else
grubdevs_new[${#grubdevs_new[@]}]="$grubdev"
fi
done
grubdevs=( "${grubdevs_new[@]}" )
if [ "$uefi" -ge 1 ]; then
debug 1 "installing ${grub_name} to: /boot/efi"
chroot "$mp" env DEBIAN_FRONTEND=noninteractive sh -ec '
prober="/etc/grub.d/30_os-prober"
[ -x $prober ] && chmod -x "$prober"
dpkg-reconfigure "$1"
[ -f $prober ] && chmod +x "$prober"
grub-install --target=$2 --efi-directory=/boot/efi --bootloader-id=ubuntu --recheck || exit; done' \
-- "${grub_name}" "${grub_target}"