Browse Source

Initial commit.

master
Anthony G. Basile 7 years ago
commit
8885d6a5b9
30 changed files with 2445 additions and 0 deletions
  1. +5
    -0
      .gitignore
  2. +339
    -0
      LICENSE
  3. +7
    -0
      MANIFEST.in
  4. +84
    -0
      README
  5. +16
    -0
      clean-worldconf
  6. +97
    -0
      grs/Constants.py
  7. +122
    -0
      grs/Daemon.py
  8. +50
    -0
      grs/Execute.py
  9. +200
    -0
      grs/Interpret.py
  10. +102
    -0
      grs/Kernel.py
  11. +46
    -0
      grs/Log.py
  12. +120
    -0
      grs/MountDirectories.py
  13. +93
    -0
      grs/Populate.py
  14. +28
    -0
      grs/RunScript.py
  15. +72
    -0
      grs/Seed.py
  16. +37
    -0
      grs/Synchronize.py
  17. +54
    -0
      grs/TarIt.py
  18. +119
    -0
      grs/WorldConf.py
  19. +15
    -0
      grs/__init__.py
  20. +72
    -0
      grsrun
  21. +200
    -0
      grsup
  22. +11
    -0
      install-worldconf
  23. +22
    -0
      setup.py
  24. +37
    -0
      tests/test-constants.py
  25. +91
    -0
      tests/test-daemon.py
  26. +47
    -0
      tests/test-log.py
  27. +56
    -0
      tests/test-mountdirectories.py
  28. +23
    -0
      tests/test-tarit.py
  29. +138
    -0
      utils/make-worldconf
  30. +142
    -0
      utils/most-dependant

+ 5
- 0
.gitignore View File

@ -0,0 +1,5 @@
__pycache__
build/
*.conf
*.pyc
*.swp

+ 339
- 0
LICENSE View File

@ -0,0 +1,339 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Lesser General Public License instead.) You can apply it to
your programs, too.
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
this service 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.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute 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 and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
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
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the 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 a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, 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.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE 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.
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
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 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 General Public License for more details.
You should have received a copy of the GNU General Public License along
with this program; if not, write to the Free Software Foundation, Inc.,
51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License.

+ 7
- 0
MANIFEST.in View File

@ -0,0 +1,7 @@
include LICENSE
include README
include grsrun
include grsup
include install-worldconf
include systems.conf
include grs/*

+ 84
- 0
README View File

@ -0,0 +1,84 @@
What is this?
The Gentoo Reference System (GRS) Suite is a set of utilities for producing and
maintaining identical Gentoo systems from a series of configuration files housed
on a central git repository. As a 'from source' distribution, Gentoo allows
a large degree of customization. The space of all possible packages and USE flags
is vast, not to speak of more radical choices such as different kernels (eg. Gentoo
on FreeBSD), different C Standard Libraries (eg. glibc, uClibc or musl) and different
providers of core userland utilities (eg. busybox vs. coreutils). In contrast
to other distributions where each instance of an installed system is nearly identical
to another, the large array of choice in Gentoo means that any two systems are
unlikely to be sufficiently similar that executables or libraries from one will
"just work" on the other, even if the architecture and other hardware factors are
the same; assuming, of course, there is no conscious effort to build identical
Gentoo systems. This is where the Gentoo Release System (GRS) suite comes in.
It does precisely this, namely, it provides an automated method for repeatedly
and predicably generating identical Gentoo systems.
GRS is designed to work roughly as follows: Periodic release tarballs are generated
which are "polished". For example, releases can provide preconfigured display
managers, windowing systems, user accounts and home directories. Installation
should be as simple as unpacking the release tarball on pre-formated partitions
with minimal or no further configuration. There is no need to build any packages
or a kernel and everything is ready to go out of the box. A release tarball can
be downloaded from some server or alternatively can be built locally. While may
not be identical because they were build at different times, after updating, both
approaches should yield identical systems.
Updating a GRS system can proceed by either building packages localy, or downloading
prebuilt binpkgs. As long as one does not deviate from the GRS defined set of USE
flags, maskings and other configuration parameters, both approaches should yield
identical systems. A GRS system is always a Gentoo system, so at any time, one can
elect to part ways from GRS and venture out on one's own! The GRS suite provides a
utilities to make sure that configurations in /etc/portage are properly in a
manner consistant with GRS, but emerge and other portage utilities will always work.
Even if one does deviate from the GRS defined parameters, it should be possible to
return to strict GRS using the GRS utilities, provided one has not deviated too far.
GRS is provided by app-portage/grs. The same package is installed on either a
server responsible for building the release tarballs and binpkgs, or on an actual
GRS system. On the server, a daemon called grsrun will either do a release run,
in which case it builds the release tarballs, or it will do an update run where
it either builds or updates a bunch of extra binpkgs. For example, for GRS =
desktop-amd64-uclibc-hardened, the release run builds a little under 900 packages,x
while the update builds/updates about 5700 packages. he first update run after a
new release is very time consuimgin becuase some 5700 new packages must be built,
but subsequent update runs need only build packages which were bumped since the last
update run.
On the client, a utility called grsup acts as a wrapper to emerge. grsup will both
manage the configuration files in /etc/portage as well as either builds or download
the binpkg from a PORTAGE_BINHOST. After the initial installation of a GRS system,
one need only run grsup to update it up to date. While releases tarballs will be
pushed out periodically, these are not used to update an existing GRS system, only
to start new one. Rather, one GRS release should smoothly update to the next; in
other words, each GRS release is equivalent to the previous release plus any updates
since. The only reason to push out a new release tarball is to avoid having to
subsequently push out a download a large number of updates for each new installation.
CAVEAT: This is work in progress. A few of the above point are marginally working
or implemented. This warning will disappear after this whole project moves past
being experimental.
Features:
* The GRS suite does not hard code any steps for the release or update runs.
Rather, a build script on the git repo describes the steps for building each
particular GRS system. This makes GRS runs highly flexible. One need only
transcribe the steps one would manually take in a chroot in build the system
into the build script, and grsrun will automatically repeat them.
* It is possible to script a GRS system to do the equivalent of catalyst runs.
[TODO: there is still one more build script directive required here, pivot_chroot.]
* A GRS system acts as a "tinderbox-lite" in that build failures are reported.
So as a GRS system evolves over time, as package are bumped, any breakages that
are introduced will be caught and reported.
Authors:
* Anthony G. Basile <blueness@gentoo.org.>

+ 16
- 0
clean-worldconf View File

@ -0,0 +1,16 @@
#!/usr/bin/env python
import os
from grs import CONST
from grs import WorldConf
def main():
WorldConf.clean()
try:
os.remove(CONST.PORTAGE_DIRTYFILE)
except (FileNotFoundError, IsADirectoryError):
pass
if __name__ == "__main__":
main()

+ 97
- 0
grs/Constants.py View File

@ -0,0 +1,97 @@
#!/use/bin/env python
import os
import sys
import configparser
from copy import deepcopy
CONFIG = '/etc/grs/systems.conf'
class Constants():
""" doc here
more doc
"""
def __init__(self, configfile = CONFIG):
if not os.path.isfile(configfile):
sys.stderr.write('Configuration file %s not found\n' % configfile)
sys.exit(1)
self.config = configparser.ConfigParser(delimiters = ':', comment_prefixes = '#')
self.config.read(configfile)
self.names = list(self.config.sections())
server = 'http://distfiles.gentoo.org/'
stagedir = 'gentoo/releases/amd64/autobuilds/current-stage3-amd64-uclibc-hardened/'
stagefile = 'stage3-amd64-uclibc-hardened-20150510.tar.bz2'
default_stage_uri = server + stagedir + stagefile
space = {
'nameserver' : '8.8.8.8',
'repo_uri' : 'git://tweedledum.dyc.edu/grs',
'stage_uri' : default_stage_uri,
'libdir' : '/var/lib/grs/%s',
'logfile' : '/var/log/grs/%s.log',
'tmpdir' : '/var/tmp/grs/%s',
'workdir' : '/var/tmp/grs/%s/work',
'package' : '/var/tmp/grs/%s/packages',
'kernelroot' : '/var/tmp/grs/%s/kernel',
'portage_configroot' : '/var/tmp/grs/%s/system',
'pidfile' : '/run/grs-%s.pid'
}
for key in space:
self.__dict__[key+'s'] = []
for section in self.config.sections():
overrides = dict(self.config[section].items())
for key in space:
if key in overrides:
value = overrides[key]
else:
try:
value = space[key] % section
except TypeError:
value = space[key]
self.__dict__[key+'s'].append(value)
def __setattr__(self, key, value):
if not key in self.__dict__:
self.__dict__[key] = value
else:
pass
def __getattr__(self, key, value = None):
if key in self.__dict__:
return deepcopy(self.__dict__[key])
def __delattr__(self, key):
if key in self.__dict__:
pass
CONST = Constants()
CONST.PACKAGE_NAME = "Gentoo Reference System"
CONST.PACKAGE_VERSION = 0.0
CONST.PACKAGE_DESCRIPTION = "Update a GRS by cloning a predefined system."
CONST.BUG_REPORTS = 'http://bugs.gentoo.org'
# The are defaults in case objects are instantiated without namespaces
# but they should not be used under normal working condidtions.
CONST.LIBDIR = '/var/lib/grs'
CONST.LOGFILE = '/var/log/grs.log'
CONST.TMPDIR = '/var/tmp/grs'
CONST.WORKDIR = '/var/tmp/grs/work'
CONST.PACKAGE = '/var/tmp/grs/package'
CONST.KERNELROOT = '/var/tmp/grs/kernel'
CONST.PORTAGE_CONFIGROOT = '/var/tmp/grs/system'
CONST.PIDFILE = '/run/grs.pid'
CONST.PORTAGE_CONFIGDIR = '/etc/portage'
CONST.PORTAGE_DIRTYFILE = '/etc/portage/.grs_dirty'
CONST.WORLD_CONFIG = '/etc/grs/world.conf'

+ 122
- 0
grs/Daemon.py View File

@ -0,0 +1,122 @@
#!/usr/bin/env python
import atexit
import os
import signal
import sys
import time
class Daemon:
""" doc here
more doc
"""
def __init__(self, pidfile, **kwargs):
self.pidfile = pidfile
for k in kwargs:
self.__dict__[k] = kwargs[k]
def daemonize(self):
""" doc here
more doc
"""
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #1 failed: %s\n' % err)
sys.exit(1)
os.chdir('/')
os.setsid()
os.umask(0o22)
try:
pid = os.fork()
if pid > 0:
sys.exit(0)
except OSError as err:
sys.stderr.write('fork #2 failed %s\n' % err)
sys.exit(1)
# Close stdin, and redirect both stdout and stderr to grs-daemon-<pid>.err
si = open(os.devnull, 'r')
os.dup2(si.fileno(), sys.stdin.fileno())
os.makedirs('/var/log/grs', mode=0o755, exist_ok=True)
se = open('/var/log/grs/grs-daemon-%d.err' % os.getpid(), 'a+')
sys.stdout.flush()
os.dup2(se.fileno(), sys.stdout.fileno())
sys.stderr.flush()
os.dup2(se.fileno(), sys.stderr.fileno())
atexit.register(self.delpid)
with open(self.pidfile,'w') as pf:
pf.write('%d\n' % os.getpid())
def delpid(self):
os.remove(self.pidfile)
def start(self):
try:
with open(self.pidfile, 'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid:
if not os.path.exists('/proc/%d' % pid):
sys.stderr.write('unlinking stale pid file %s\n' % self.pidfile)
os.unlink(self.pidfile)
else:
sys.stderr.write('process running with pid = %d\n' % pid)
return
self.daemonize()
self.run()
def stop(self):
try:
with open(self.pidfile,'r') as pf:
pid = int(pf.read().strip())
except IOError:
pid = None
if pid and not os.path.exists('/proc/%d' % pid):
sys.stderr.write('process not running\n')
sys.stderr.write('unlinking stale pid file %s\n' % self.pidfile)
os.unlink(self.pidfile)
return
if not pid:
sys.stderr.write('process not running\n')
return # not an error in a restart
try:
for i in range(10):
os.kill(pid, signal.SIGTERM)
time.sleep(0.2)
while True:
os.kill(pid, signal.SIGKILL)
time.sleep(0.2)
except ProcessLookupError as err:
try:
os.remove(self.pidfile)
except IOError as err:
sys.stderr.write('%s\n' % err)
except OSError as err:
sys.stderr.write('%s\n' %err)
return
def restart(self):
self.stop()
self.start()
def run(self):
pass

+ 50
- 0
grs/Execute.py View File

@ -0,0 +1,50 @@
#!/usr/bin/env python
import os
import signal
import shlex
import subprocess
from grs.Constants import CONST
class Execute():
""" doc here
more doc
"""
def __init__(self, cmd, timeout = 1, extra_env = {}, failok = False, logfile = CONST.LOGFILE):
""" doc here
more doc
"""
def signalexit():
pid = os.getpid()
f.write('SENDING SIGTERM to pid = %d\n' % pid)
f.close()
os.kill(pid, signal.SIGTERM)
f = open(logfile, 'a')
args = shlex.split(cmd)
extra_env = dict(os.environ, **extra_env)
try:
proc = subprocess.Popen(args, stdout=f, stderr=f, env=extra_env)
except FileNotFoundError:
f.write('Illegal cmd %s\n' % cmd)
signalexit()
try:
proc.wait(timeout)
timed_out = False
except subprocess.TimeoutExpired:
proc.kill()
timed_out = True
rc = proc.returncode
if rc != 0:
f.write('EXIT CODE: %d\n' % rc)
if not failok:
signalexit()
if timed_out:
f.write('TIMEOUT ERROR: %s\n' % cmd)
f.close()

+ 200
- 0
grs/Interpret.py View File

@ -0,0 +1,200 @@
#!/usr/bin/env python
import os
import re
import signal
import sys
from grs.Constants import CONST
from grs.Daemon import Daemon
from grs.Log import Log
from grs.Kernel import Kernel
from grs.MountDirectories import MountDirectories
from grs.Populate import Populate
from grs.RunScript import RunScript
from grs.Synchronize import Synchronize
from grs.Seed import Seed
from grs.TarIt import TarIt
class Interpret(Daemon):
""" doc here
more doc
"""
def run(self):
""" doc here
more doc
"""
def handler(signum, frame):
""" On SIGTERM, propagate the signal to all processes in the cgroup/subcgroup
except yourself. If a process won't terminate nicely, then kill it.
Finally unmount all the mounted filesystems. Hopefully this will work
since there should be no more open files on those filesystems.
"""
mypid = os.getpid()
while True:
with open(os.path.join(self.subcgroupdir, 'tasks'), 'r') as f:
lines = f.readlines()
if len(lines) <= 1:
break
for p in lines:
pid = int(p.strip())
if mypid == pid:
continue
try:
os.kill(pid, signal.SIGTERM)
os.kill(pid, signal.SIGKILL)
except ProcessLookupError:
pass
try:
md.umount_all()
except NameError:
pass
sys.exit(signum + 128)
signal.signal(signal.SIGINT, handler)
signal.signal(signal.SIGTERM, handler)
def smartlog(l, obj, has_obj = True):
if (has_obj and not obj) or (not has_obj and obj):
lo.log('Bad command: %s' % l)
return True
if self.mock_run:
lo.log(l)
return True
return False
def stampit(progress):
open(progress, 'w').close()
nameserver = CONST.nameservers[self.run_number]
repo_uri = CONST.repo_uris[self.run_number]
stage_uri = CONST.stage_uris[self.run_number]
name = CONST.names[self.run_number]
libdir = CONST.libdirs[self.run_number]
logfile = CONST.logfiles[self.run_number]
tmpdir = CONST.tmpdirs[self.run_number]
workdir = CONST.workdirs[self.run_number]
package = CONST.packages[self.run_number]
kernelroot = CONST.kernelroots[self.run_number]
portage_configroot = CONST.portage_configroots[self.run_number]
lo = Log(logfile)
sy = Synchronize(repo_uri, name, libdir, logfile)
se = Seed(stage_uri, tmpdir, portage_configroot, package, logfile)
md = MountDirectories(portage_configroot, package, logfile)
po = Populate(nameserver, libdir, workdir, portage_configroot, logfile)
ru = RunScript(libdir, portage_configroot, logfile)
ke = Kernel(libdir, portage_configroot, kernelroot, package, logfile)
bi = TarIt(name, portage_configroot, logfile)
os.makedirs(tmpdir, mode=0o755, exist_ok=True)
lo.rotate_logs()
md.umount_all()
# Both sync() + seed() are not scripted steps.
# sync() is done unconditionally for an update run.
progress = os.path.join(tmpdir, '.completed_sync')
if not os.path.exists(progress) or self.update_run:
sy.sync()
stampit(progress)
# seed() is never done for an update run
progress = os.path.join(tmpdir, '.completed_seed')
if not os.path.exists(progress) and not self.update_run:
se.seed()
stampit(progress)
build_script = os.path.join(libdir, 'build')
try:
with open(build_script, 'r') as s:
line_number = 0
for l in s.readlines():
line_number += 1
# For a release run, execute every line of the build script.
# For an update run, exexute only lines with a leading +.
ignore_stamp = False
m = re.search('^(\+)(.*)$', l)
if m:
# There is a leading +, so remove it and skip if doing an update run
ignore_stamp = self.update_run
l = m.group(2)
else:
# There is no leading +, so skip if this is an update run
if self.update_run:
continue
progress = os.path.join(tmpdir, '.completed_%02d' % line_number)
if os.path.exists(progress) and not ignore_stamp:
continue
try:
m = re.search('(\S+)\s+(\S+)', l)
verb = m.group(1)
obj = m.group(2)
except AttributeError:
verb = l.strip()
obj = None
if verb == '':
stampit(progress)
continue
if verb == 'log':
if smartlog(l, obj):
stampit(progress)
continue
if obj == 'stamp':
lo.log('='*80)
else:
lo.log(obj)
elif verb == 'mount':
if smartlog(l, obj, False):
stampit(progress)
continue
md.mount_all()
elif verb == 'unmount':
if smartlog(l, obj, False):
stampit(progress)
continue
md.umount_all()
elif verb == 'populate':
if smartlog(l, obj):
stampit(progress)
continue
po.populate(cycle=int(obj))
elif verb == 'runscript':
if smartlog(l, obj):
stampit(progress)
continue
ru.runscript(obj)
elif verb == 'clean':
if smartlog(l, obj, False):
stampit(progress)
continue
po.clean()
elif verb == 'kernel':
if smartlog(l, obj, False):
stampit(progress)
continue
ke.kernel()
elif verb == 'tarit':
if smartlog(l, obj, False):
stampit(progress)
continue
bi.tarit()
elif verb == 'hashit':
if smartlog(l, obj, False):
stampit(progress)
continue
bi.hashit()
else:
lo.log('Bad command: %s' % l)
stampit(progress)
except FileNotFoundError:
lo.log('Failed to open build script: %s' % build_script)

+ 102
- 0
grs/Kernel.py View File

@ -0,0 +1,102 @@
#!/usr/bin/env python
import os
import re
import shutil
from grs.Constants import CONST
from grs.Execute import Execute
class Kernel():
def __init__(self, libdir = CONST.LIBDIR, portage_configroot = CONST.PORTAGE_CONFIGROOT, kernelroot = CONST.KERNELROOT, package = CONST.PACKAGE, logfile = CONST.LOGFILE):
self.libdir = libdir
self.portage_configroot = portage_configroot
self.kernelroot = kernelroot
self.package = package
self.logfile = logfile
self.kernel_config = os.path.join(self.libdir, 'scripts/kernel-config')
def parse_kernel_config(self):
with open(self.kernel_config, 'r') as f:
for i in range(3):
line = f.readline()
m = re.search('^#\s+(\S+)\s+(\S+).+$', line)
gentoo_version = m.group(2)
try:
m = re.search('(\S+?)-(\S+?)-(\S+)', gentoo_version)
vanilla_version = m.group(1)
flavor = m.group(2)
revision = m.group(3)
pkg_name = flavor + '-sources-' + vanilla_version + '-' + revision
except AttributeError:
m = re.search('(\S+?)-(\S+)', gentoo_version)
vanilla_version = m.group(1)
flavor = m.group(2)
pkg_name = flavor + '-sources-' + vanilla_version
pkg_name = '=sys-kernel/' + pkg_name
return (gentoo_version, pkg_name)
def kernel(self):
(gentoo_version, pkg_name) = self.parse_kernel_config()
kernel_source = os.path.join(self.kernelroot, 'usr/src/linux')
image_dir = os.path.join(self.kernelroot, gentoo_version)
boot_dir = os.path.join(image_dir, 'boot')
modprobe_dir = os.path.join(image_dir, 'etc/modprobe.d')
modules_dir = os.path.join(image_dir, 'lib/modules')
# Remove any old image directory and create a boot directory
# wich genkernel assumes is present.
shutil.rmtree(image_dir)
os.makedirs(boot_dir, mode=0o755, exist_ok=True)
cmd = 'emerge --nodeps -1n %s' % pkg_name
emerge_env = { 'USE' : 'symlink', 'ROOT' : self.kernelroot, 'ACCEPT_KEYWORDS' : '**' }
Execute(cmd, timeout=600, extra_env=emerge_env, logfile=self.logfile)
# Build and install the image outside the portage configroot so
# we can both rsync it in *and* tarball it for downloads.
# TODO: add more options (eg splash and firmware), which can be
# specified vi the kernel line in the build script.
cmd = 'genkernel '
cmd += '--logfile=/dev/null '
cmd += '--no-save-config '
cmd += '--makeopts=-j9 '
cmd += '--no-firmware '
cmd += '--symlink '
cmd += '--no-mountboot '
cmd += '--kernel-config=%s ' % self.kernel_config
cmd += '--kerneldir=%s ' % kernel_source
cmd += '--bootdir=%s ' % boot_dir
cmd += '--module-prefix=%s ' % image_dir
cmd += '--modprobedir=%s ' % modprobe_dir
cmd += 'all'
Execute(cmd, timeout=None, logfile=self.logfile)
for dirpath, dirnames, filenames in os.walk(modules_dir):
for filename in filenames:
if filename.endswith('.ko'):
module = os.path.join(dirpath, filename)
cmd = 'objcopy -v --strip-unneeded %s' % module
Execute(cmd)
# Copy the newly compiled kernel image and modules to portage configroot
cmd = 'rsync -a %s/ %s' % (image_dir, self.portage_configroot)
Execute(cmd, timeout=60, logfile=self.logfile)
# Tar up the kernel image and modules and place them in package/linux-images
linux_images = os.path.join(self.package, 'linux-images')
os.makedirs(linux_images, mode=0o755, exist_ok=True)
tarball_name = 'linux-image-%s.tar.xz' % gentoo_version
tarball_path = os.path.join(linux_images, tarball_name)
cwd = os.getcwd()
os.chdir(image_dir)
os.unlink(tarball_path)
cmd = 'tar -Jcf %s .' % tarball_path
Execute(cmd, timeout=600, logfile=self.logfile)
os.chdir(cwd)

+ 46
- 0
grs/Log.py View File

@ -0,0 +1,46 @@
#!/usr/bin/env python
import datetime
import glob
import os
import re
import shutil
from grs.Constants import CONST
class Log():
def __init__(self, logfile = CONST.LOGFILE):
self.logfile = logfile
try:
os.makedirs(os.path.dirname(self.logfile))
except FileExistsError:
pass
open(self.logfile, 'a').close()
def log(self, msg, stamped = True):
if stamped:
current_time = datetime.datetime.now(datetime.timezone.utc)
unix_timestamp = current_time.timestamp()
msg = '[%f] %s' % (unix_timestamp, msg)
with open(self.logfile, 'a') as f:
f.write('%s\n' % msg)
def rotate_logs(self):
logs = glob.glob('%s.*' % self.logfile)
indexed_log = {}
for l in logs:
m = re.search('^.+\.(\d+)$', l)
indexed_log[int(m.group(1))] = l
count = list(indexed_log.keys())
count.sort()
count.reverse()
for c in count:
current_log = indexed_log[c]
m = re.search('^(.+)\.\d+$', current_log)
next_log = '%s.%d' % (m.group(1), c+1)
shutil.move(current_log, next_log)
if os.path.isfile(self.logfile):
shutil.move(self.logfile, '%s.0' % self.logfile)
open('%s' % self.logfile, 'a').close()

+ 120
- 0
grs/MountDirectories.py View File

@ -0,0 +1,120 @@
#!/usr/bin/env python
import os
from copy import deepcopy
from grs.Constants import CONST
from grs.Execute import Execute
class MountDirectories():
""" doc here
more doc
"""
def __init__(self, portage_configroot = CONST.PORTAGE_CONFIGROOT, package = CONST.PACKAGE, logfile = CONST.LOGFILE):
""" doc here
more doc
"""
# The order is respected
self.directories = [
'dev',
'dev/pts',
{ 'dev/shm' : ( 'tmpfs', 'shm' ) },
'proc',
'sys',
'usr/portage',
[ package, 'usr/portage/packages' ]
]
# Once initiated, we'll only work with one portage_configroot
self.portage_configroot = portage_configroot
self.package = package
self.logfile = logfile
# We need to umount in the reverse order
self.rev_directories = deepcopy(self.directories)
self.rev_directories.reverse()
def ismounted(self, mountpoint):
# Obtain all the current mountpoints. os.path.ismount() fails for for bind mounts,
# so we obtain them all ourselves
mountpoints = []
for line in open('/proc/mounts', 'r').readlines():
mountpoints.append(line.split()[1])
# Let's make sure mountoint is canonical real path, no sym links,
# since that's what /proc/mounts reports.
mountpoint = os.path.realpath(mountpoint)
return mountpoint in mountpoints
def are_mounted(self):
""" doc here
more doc
"""
some_mounted = False
all_mounted = True
for mount in self.directories:
if isinstance(mount, str):
target_directory = mount
elif isinstance(mount, list):
target_directory = mount[1]
elif isinstance(mount, dict):
tmp = list(mount.keys())
target_directory = tmp[0]
target_directory = os.path.join(self.portage_configroot, target_directory)
if self.ismounted(target_directory):
some_mounted = True
else:
all_mounted = False
return some_mounted, all_mounted
def mount_all(self):
""" doc here
more doc
"""
# If any our mounted, let's first unmount all, then mount all
some_mounted, all_mounted = self.are_mounted()
if some_mounted:
self.umount_all()
for mount in self.directories:
if isinstance(mount, str):
# Here source_directory is assumed to exist relative to /
source_directory = mount
target_directory = mount
elif isinstance(mount, list):
# Here source_directory is assumet to be an abspath
# and we create it if it doesn't exist
source_directory = mount[0]
if not os.path.isdir(source_directory):
os.makedirs(source_directory)
target_directory = mount[1]
elif isinstance(mount, dict):
tmp = list(mount.values())
tmp = tmp[0]
vfstype = tmp[0]
vfsname = tmp[1]
tmp = list(mount.keys())
target_directory = tmp[0]
target_directory = os.path.join(self.portage_configroot, target_directory)
if not os.path.isdir(target_directory):
os.makedirs(target_directory)
if isinstance(mount, str):
cmd = 'mount --bind /%s %s' % (source_directory, target_directory)
elif isinstance(mount, list):
cmd = 'mount --bind %s %s' % (source_directory, target_directory)
elif isinstance(mount, dict):
cmd = 'mount -t %s %s %s' % (vfstype, vfsname, target_directory)
Execute(cmd, timeout=60, logfile=self.logfile)
def umount_all(self):
for mount in self.rev_directories:
if isinstance(mount, str):
target_directory = mount
elif isinstance(mount, list):
target_directory = mount[1]
elif isinstance(mount, dict):
tmp = list(mount.keys())
target_directory = tmp[0]
target_directory = os.path.join(self.portage_configroot, target_directory)
if self.ismounted(target_directory):
cmd = 'umount --force %s' % target_directory
Execute(cmd, timeout=60, logfile=self.logfile)

+ 93
- 0
grs/Populate.py View File

@ -0,0 +1,93 @@
#!/usr/bin/env python
import os
import re
import shutil
from grs.Constants import CONST
from grs.Execute import Execute
class Populate():
""" doc here
more doc
"""
def __init__(self, nameserver, libdir = CONST.LIBDIR, workdir = CONST.WORKDIR, portage_configroot = CONST.PORTAGE_CONFIGROOT, logfile = CONST.LOGFILE):
self.nameserver = nameserver
self.libdir = libdir
self.workdir = workdir
self.portage_configroot = portage_configroot
self.logfile = logfile
self.etc = os.path.join(self.portage_configroot, 'etc')
self.resolv_conf = os.path.join(self.etc, 'resolv.conf')
def populate(self, cycle = True):
cmd = 'rsync -av --delete --exclude=\'.git*\' %s/core/ %s' % (self.libdir, self.workdir)
Execute(cmd, timeout=60, logfile = self.logfile)
# Select the cycle
if cycle: self.select_cycle(cycle)
# Copy from /tmp/grs-work to /tmp/system
cmd = 'rsync -av %s/ %s' % (self.workdir, self.portage_configroot)
Execute(cmd, timeout=60, logfile = self. logfile)
# Add any extra files
try:
os.makedirs(self.etc)
except FileExistsError:
pass
with open(self.resolv_conf, 'w') as f:
f.write('nameserver %s' % self.nameserver)
def select_cycle(self, cycle):
cycled_files = {}
for dirpath, dirnames, filenames in os.walk(self.workdir):
for f in filenames:
m = re.search('^(.+)\.CYCLE\.(\d+)', f)
if m:
filename = m.group(1)
cycle_no = int(m.group(2))
cycled_files.setdefault(cycle_no, [])
cycled_files[cycle_no].append([dirpath, filename])
if type(cycle) is bool:
cycle_no = max(cycled_files)
else:
cycle_no = cycle
for c in cycled_files:
for f in cycled_files[c]:
dirpath = f[0]
filename = f[1]
new_file = os.path.join(dirpath, filename)
old_file = "%s.CYCLE.%d" % (new_file, c)
if os.path.isfile(old_file):
if c == cycle_no:
os.rename(old_file, new_file)
else:
os.remove(old_file)
def clean_subdirs(self, dirpath):
path = os.path.join(self.portage_configroot, dirpath)
try:
uid = os.stat(path).st_uid
gid = os.stat(path).st_gid
mode = os.stat(path).st_mode
shutil.rmtree(path)
os.mkdir(path)
os.chown(path, uid, gid)
os.chmod(path, mode)
except FileNotFoundError:
pass
def clean(self):
self.clean_subdirs('tmp')
self.clean_subdirs('var/tmp')
self.clean_subdirs('var/log')
try:
os.unlink(self.resolv_conf)
except FileNotFoundError:
pass

+ 28
- 0
grs/RunScript.py View File

@ -0,0 +1,28 @@
#!/usr/bin/env python
import os
import shutil
from grs.Constants import CONST
from grs.Execute import Execute
class RunScript():
""" doc here
more doc
"""
def __init__(self, libdir = CONST.LIBDIR, portage_configroot = CONST.PORTAGE_CONFIGROOT, logfile = CONST.LOGFILE):
""" doc here
more doc
"""
self.libdir = libdir
self.portage_configroot = portage_configroot
self.logfile = logfile
def runscript(self, script_name):
script_org = os.path.join(self.libdir, 'scripts/%s' % script_name)
script_dst = os.path.join(self.portage_configroot, 'tmp/script.sh')
shutil.copy(script_org, script_dst)
os.chmod(script_dst, 0o0755)
cmd = 'chroot %s /tmp/script.sh' % self.portage_configroot
Execute(cmd, timeout=None, logfile=self.logfile)
os.unlink(script_dst)

+ 72
- 0
grs/Seed.py View File

@ -0,0 +1,72 @@
#!/usr/bin/env python
import glob
import os
import re
import shutil
import urllib.request
from grs.Constants import CONST
from grs.Execute import Execute
class Seed():
""" doc here
more doc
"""
def __init__(self, stage_uri, tmpdir = CONST.TMPDIR, portage_configroot = \
CONST.PORTAGE_CONFIGROOT, package = CONST.PACKAGE, logfile = CONST.LOGFILE):
""" doc here
more doc
"""
self.stage_uri = stage_uri
self.portage_configroot = portage_configroot
self.package = package
filename = os.path.basename(stage_uri)
self.filepath = os.path.join(tmpdir, filename)
self.logfile = logfile
def seed(self):
""" doc here
more doc
"""
for directory in [self.portage_configroot, self.package]:
# Rotate any previous directories out of the way
dirs = glob.glob('%s.*' % directory)
indexed_dir = {}
for d in dirs:
m = re.search('^.+\.(\d+)$', d)
indexed_dir[int(m.group(1))] = d
count = list(indexed_dir.keys())
count.sort()
count.reverse()
for c in count:
current_dir = indexed_dir[c]
m = re.search('^(.+)\.\d+$', current_dir)
next_dir = '%s.%d' % (m.group(1), c+1)
shutil.move(current_dir, next_dir)
# If there is a directory, then move it to %s.0
if os.path.isdir(directory):
shutil.move(directory, '%s.0' % directory)
# Now that all prevous directory are out of the way,
# create a new empty directory
os.makedirs(directory)
# Download a stage tarball if we don't have one
if not os.path.isfile(self.filepath):
try:
request = urllib.request.urlopen(self.stage_uri)
with open(self.filepath, 'wb') as f:
shutil.copyfileobj(request, f)
except: #any exception will do here
pid = os.getpid()
with open(self.logfile, 'r') as f:
f.write('SENDING SIGTERM to pid = %d\n' % pid)
f.close()
os.kill(pid, signal.SIGTERM)
# Because python's tarfile sucks
cmd = 'tar --xattrs -xf %s -C %s' % (self.filepath, self.portage_configroot)
Execute(cmd, timeout=120, logfile=self.logfile)
#os.unlink(self.filepath)

+ 37
- 0
grs/Synchronize.py View File

@ -0,0 +1,37 @@
#!/usr/bin/env python
import os
from grs.Constants import CONST
from grs.Execute import Execute
class Synchronize():
""" doc here
more doc
"""
def __init__(self, remote_repo, branch, libdir = CONST.LIBDIR, logfile = CONST.LOGFILE):
self.remote_repo = remote_repo
self.branch = branch
self.local_repo = libdir
self.logfile = logfile
def sync(self):
if self.isgitdir():
cmd = 'git -C %s reset HEAD --hard' % self.local_repo
Execute(cmd, timeout=60, logfile=self.logfile)
cmd = 'git -C %s clean -f -x -d' % self.local_repo
Execute(cmd, timeout=60, logfile=self.logfile)
cmd = 'git -C %s pull' % self.local_repo
Execute(cmd, timeout=60, logfile=self.logfile)
cmd = 'git -C %s checkout %s' % (self.local_repo, self.branch)
Execute(cmd, timeout=60, logfile=self.logfile)
else:
cmd = 'git clone %s %s' % (self.remote_repo, self.local_repo)
Execute(cmd, timeout=60, logfile=self.logfile)
cmd = 'git -C %s checkout %s' % (self.local_repo, self.branch)
Execute(cmd, timeout=60, logfile=self.logfile)
def isgitdir(self):
git_configdir = os.path.join(self.local_repo, '.git')
git_configfile = os.path.join(git_configdir, 'config')
return os.path.isdir(git_configdir) and os.path.isfile(git_configfile)

+ 54
- 0
grs/TarIt.py View File

@ -0,0 +1,54 @@
#!/usr/bin/env python
import os
from datetime import datetime
from grs.Constants import CONST
from grs.Execute import Execute
class TarIt():
def __init__(self, name, portage_configroot = CONST.PORTAGE_CONFIGROOT, logfile = CONST.LOGFILE):
self.portage_configroot = portage_configroot
self.logfile = logfile
year = str(datetime.now().year).zfill(4)
month = str(datetime.now().month).zfill(2)
day = str(datetime.now().day).zfill(2)
self.tarball_name = '%s-%s%s%s.tar.xz' % (name, year, month, day)
self.digest_name = '%s.DIGESTS' % self.tarball_name
def tarit(self):
cwd = os.getcwd()
os.chdir(self.portage_configroot)
tarball_path = os.path.join('..', self.tarball_name)
xattr_opts = '--xattrs --xattrs-include=security.capability --xattrs-include=user.pax.flags'
cmd = 'tar %s -Jcf %s .' % (xattr_opts, tarball_path)
Execute(cmd, timeout=None, logfile=self.logfile)
os.chdir(cwd)
def hashit(self):
cwd = os.getcwd()
os.chdir(os.path.join(self.portage_configroot, '..'))
# Note: this first cmd clobbers the contents
cmd = 'echo "# MD5 HASH"'
Execute(cmd, logfile=self.digest_name)
cmd = 'md5sum %s' % self.tarball_name
Execute(cmd, timeout=60, logfile=self.digest_name)
cmd = 'echo "# SHA1 HASH"'
Execute(cmd, logfile=self.digest_name)
cmd = 'sha1sum %s' % self.tarball_name
Execute(cmd, timeout=60, logfile=self.digest_name)
cmd = 'echo "# SHA512 HASH"'
Execute(cmd, logfile=self.digest_name)
cmd = 'sha512sum %s' % self.tarball_name
Execute(cmd, timeout=60, logfile=self.digest_name)
cmd = 'echo "# WHIRLPOOL HASH"'
Execute(cmd, logfile=self.digest_name)
cmd = 'whirlpooldeep %s' % self.tarball_name
Execute(cmd, timeout=60, logfile=self.digest_name)
os.chdir(cwd)

+ 119
- 0
grs/WorldConf.py View File

@ -0,0 +1,119 @@
#!/usr/bin/env python
import configparser
import copy
import os
import portage
import re
from grs.Constants import CONST
class WorldConf():
""" doc here
more doc
"""
@staticmethod
def conf2file(config, s, portage_dir):
""" doc here
more doc
"""
try:
for (f, v) in config[s].items():
# a '+' at the beginging means append to the file
undecorated_f = re.sub('^\+', '', f)
filepath = os.path.join(portage_dir, undecorated_f)
dirpath = os.path.dirname(filepath)
os.makedirs(dirpath, mode=0o755, exist_ok=True)
if f == undecorated_f or not os.path.exists(filepath):
with open(filepath, 'w') as g:
g.write('%s\n' % v)
else:
with open(filepath, 'r+') as g:
for l in g.readlines():
if v == l.strip():
break
else:
g.write('%s\n' % v)
except KeyError:
pass
@staticmethod
def install():
""" doc here
more doc
"""
config = configparser.RawConfigParser(delimiters=':', allow_no_value=True, comment_prefixes=None)
config.read(CONST.WORLD_CONFIG)
for s in config.sections():
WorldConf.conf2file(config, s, portage_dir=CONST.PORTAGE_CONFIGDIR)
@staticmethod
def clean():
""" doc here
more doc
"""
portdb = portage.db[portage.root]["porttree"].dbapi
vardb = portage.db[portage.root]["vartree"].dbapi
uninstalled = portdb.cp_all()
for p in vardb.cp_all():
try:
uninstalled.remove(p)
except ValueError:
# These packages are installed on the local system
# but not in the portage tree anymore.
print(p)
slot_atoms = []
for p in uninstalled:
cpv = portdb.cp_list(p)[0]
slotvar = portdb.aux_get(cpv, ['SLOT'])[0]
try:
m = re.search('(.+?)\/(.+)', slotvar)
slot = m.group(1)
except AttributeError:
slot = slotvar
slot_atoms.append(re.sub('[/:]', '_', '%s:%s' % (p, slot)))
env_slot_atoms = []
for dirpath, dirnames, filenames in os.walk(CONST.PORTAGE_CONFIGDIR):
# Only look at select files and directories.
# TODO: This needs to be expanded as we come up
# with a central class to deal with the internal
# structure of /etc/portage.
skip = True
for p in ['env', 'package.accept_keywords', 'package.use']:
if os.path.basename(dirpath) == p:
skip = False
if skip:
continue
for f in filenames:
fpath = os.path.realpath(os.path.join(dirpath, f))
if f in slot_atoms:
os.remove(fpath)
if os.path.basename(dirpath) == 'env':
env_slot_atoms.append(f)
continue
fpath = os.path.join(CONST.PORTAGE_CONFIGDIR, 'package.env')
update = False
with open(fpath, 'r') as g:
lines = g.readlines()
mylines = copy.deepcopy(lines)
for l in lines:
for slot_atom in env_slot_atoms:
if re.search(re.escape(slot_atom), l):
try:
mylines.remove(l)
update = True
except ValueError:
pass
if update:
with open(fpath, 'w') as g:
g.writelines(mylines)

+ 15
- 0
grs/__init__.py View File

@ -0,0 +1,15 @@
#!/use/bin/env python
from grs.TarIt import TarIt
from grs.Constants import CONST
from grs.Daemon import Daemon
from grs.Execute import Execute
from grs.Interpret import Interpret
from grs.Log import Log
from grs.Kernel import Kernel
from grs.MountDirectories import MountDirectories
from grs.Populate import Populate
from grs.RunScript import RunScript
from grs.Synchronize import Synchronize
from grs.Seed import Seed
from grs.WorldConf import WorldConf

+ 72
- 0
grsrun View File

@ -0,0 +1,72 @@
#!/usr/bin/env python
import os
import re
import signal
import sys
import time
from grs import CONST
from grs import Execute
from grs import Interpret
from getopt import getopt, GetoptError
def usage(rc=1):
usage = """
usage: grsrun [-m|-u|-h]
flags: -m Mock run. Don't really execute.
: -u Update run.
: -h print this help file
"""
print(usage)
sys.exit(rc)
def main():
try: