source: ogLive-Builder-Git/mkoglive.py @ 48528a4

build-browserdeps-vadimfilebeat-installerimprove-versionlgromero-testsmainpull-from-cloning-engine
Last change on this file since 48528a4 was e60695f, checked in by Natalia Serrano <natalia.serrano@…>, 7 months ago

refs #773 write a sysctl.conf

  • Property mode set to 100755
File size: 6.9 KB
Line 
1#!/usr/bin/python3
2
3import sys
4import os
5import logging
6import subprocess
7import glob
8import stat
9import shutil
10import argparse
11
12curdir = os.path.dirname (__file__)
13sys.path.insert (0, curdir)
14from boottools import utils, apt, btog
15
16os.chdir (curdir)
17
18def _logging (lvl='INFO', logfile='/tmp/boot-tools_installation.log'):
19    numeric_level = getattr (logging, lvl.upper(), None)
20    if numeric_level is None:
21        numeric_level = getattr (logging, 'INFO')
22
23    logging.basicConfig (
24        format='%(levelname)s %(asctime)s (%(funcName)s) %(message)s',
25        level=numeric_level,
26        handlers = [
27            logging.FileHandler (logfile),
28            logging.StreamHandler (sys.stdout),
29        ],
30    )
31    return logging.getLogger ('boottools')
32
33def _mount_rootfs (btrootfsimg, btrootfsmnt):
34    try: utils.mount (btrootfsimg, btrootfsmnt, opts=['-o', 'loop,offset=32256'])
35    except:
36        logger.error ('mount failed')
37        sys.exit (1)
38
39def _get_pxepkg():
40    pxepkg = None
41    cache = apt.cache_search (['gpxe', 'ipxe'])
42    if cache['gpxe']: pxepkg = 'gpxe'
43    if cache['ipxe']: pxepkg = 'ipxe'
44    if pxepkg is None:
45        logger.error ('neither gpxe nor ipxe found in apt cache')
46        sys.exit (1)
47    logger.info (f'PXE package is "{pxepkg}"')
48    return pxepkg
49
50def _mkrootfs (btrootfsimg, btrootfsmnt, btrootfsimglabel, btvirtualdisksize, bttargetdir, osarch):
51    logger.info ('Stage 1.1 - create, partition and format the rootfs')
52    rc = subprocess.run (f'file "{btrootfsimg}" |grep -q "partition 1 *: ID=0x83"', shell=True).returncode
53    if (rc):   ## 'file|grep' failed
54        try: btog.mkrootfs (btrootfsimg, btrootfsimglabel, btrootfsmnt, btvirtualdisksize, bttargetdir, osarch)
55        except Exception as e:
56            logger.error (str (e))
57            sys.exit (1)
58
59def _debootstrap (btrootfsimg, btrootfsmnt, osarch, oscodename, oshttp):
60    logger.info ('Stage 1.2 - debootstrap system')
61    _mount_rootfs (btrootfsimg, btrootfsmnt)
62    try: os.stat (os.path.join (btrootfsmnt, 'etc'))
63    except:
64        logger.debug (f'stat failed, calling btog.debootstrap()')
65        try: btog.debootstrap (btrootfsimg, btrootfsmnt, osarch, oscodename, oshttp)
66        except Exception as e:
67            utils.umount (btrootfsmnt)
68            logger.error (str (e))
69            sys.exit (1)
70    utils.umount (btrootfsmnt)
71
72def _initramfs_version (gitrelease, osrelease, curdir):
73    utils.run (['sed', '-i', f'1 s/$/ {gitrelease} ({osrelease})/', f'{curdir}/includes/etc/initramfs-tools/scripts/VERSION.txt'])
74
75def _copy_og_files (btrootfsimg, btrootfsmnt, osdistrib, oscodename):
76    _mount_rootfs (btrootfsimg, btrootfsmnt)
77    builder   = '/tmp/opengnsys/oglive_builder'
78    og_shared = '/tmp/opengnsys/shared'
79    og_engine = '/tmp/opengnsys/engine'
80    btog.copy_og_files (builder, og_shared, og_engine, btrootfsmnt, osdistrib, oscodename)
81    utils.umount (btrootfsmnt)
82
83def _chroot_tasks (cfgfile, curdir, osrelease, osarch):
84    logger.debug (f'running \'schroot --chroot IMGogclient -- {curdir}/chroot-tasks.py --osrelease "{osrelease}" --osarch "{osarch}"\'')
85    stdout, _ = utils.run (['schroot', '--chroot', 'IMGogclient', '--', f'{curdir}/chroot-tasks.py', '--osrelease', osrelease, '--osarch', osarch, '--config', cfgfile])
86    ## this leaves initrd.img-6.8.0-31-generic and vmlinuz-6.8.0-31-generic in /tmp
87
88def _ssh_stuff (btrootfsimg, btrootfsmnt):
89    _mount_rootfs (btrootfsimg, btrootfsmnt)
90    btog.sysctl (btrootfsmnt)
91    btog.ssh_server (btrootfsmnt)
92    btog.ssh_client (btrootfsmnt)
93    utils.umount (btrootfsmnt)
94    ## the end result is:
95    ## - there's a new key pair in the VM (or docker container), in /root/.ssh
96    ## - there's another new key pair in the rootfs, in /var/lib/tftpboot/ogclient/ogclientmount/root/.ssh
97    ## - the two pubkeys (one of each pair) end up being authorised in the rootfs, in /var/lib/tftpboot/ogclient/ogclientmount/root/.ssh/authorized_keys
98
99def _mkinitrd_squashfs_isofs (bttargetdir, osrelease, btrootfsimg, btrootfsmnt, pxepkg, isolinux_tpl, nameisoclient):
100    logger.info ('Stage 4.1 - Put initrd in place')
101    _mount_rootfs (btrootfsimg, btrootfsmnt)
102    btog.move_initrd (bttargetdir, osrelease)
103
104    logger.info ('Stage 4.2 - make squash filesystem')
105    btog.mksquashfs (bttargetdir, btrootfsmnt)
106    utils.umount (btrootfsmnt)
107
108    logger.info ('Stage 4.3 - make iso filesystem')
109    btog.mkisofs (pxepkg, isolinux_tpl, bttargetdir, nameisoclient)
110
111def _main (cfgfile, config, type_client):
112    isolinux_tpl     = config['General'].get ('isolinux_template')
113    btrootfsimglabel = config['General'].get ('rootfs_image_label')
114
115    logger.info ('OpenGnsys CLIENT installation begins')
116
117    fd = open (f'{curdir}/gitrelease', 'r')     ## per the Dockerfile
118    gitrelease = fd.readline().strip()
119    fd.close()
120
121    osdistrib, oscodename, osrelease, osarch, oshttp = btog.GetOsInfo (type_client)
122    if osdistrib is None:
123        logger.error ('GetOsInfo() failed')
124        sys.exit (1)
125    bttargetdir, btrootfsimg, btrootfsmnt, btvirtualdisksize = btog.GetVar (osarch)
126    logger.info (':'.join ([osdistrib, oscodename, osrelease, osarch, oshttp]))
127
128    ## this is convenient in case the previous run failed and we want to run this program again
129    try: utils.umount (btrootfsmnt)
130    except: pass
131
132    logger.info ('STAGE 1 - create and bootstrap rootfs')
133    _mkrootfs (btrootfsimg, btrootfsmnt, btrootfsimglabel, btvirtualdisksize, bttargetdir, osarch)
134    _debootstrap (btrootfsimg, btrootfsmnt, osarch, oscodename, oshttp)
135
136    logger.info ('STAGE 2 - copy files to the rootfs')
137    _initramfs_version (gitrelease, osrelease, curdir)
138    _copy_og_files (btrootfsimg, btrootfsmnt, osdistrib, oscodename)
139
140    logger.info ('STAGE 3 - perform tasks within the chroot')
141    _chroot_tasks (cfgfile, curdir, osrelease, osarch)
142
143    _ssh_stuff (btrootfsimg, btrootfsmnt)
144
145    logger.info ('STAGE 4 - generate distribution files')
146    pxepkg = _get_pxepkg()
147    nameisoclient  = '-'.join (['ogLive', oscodename, osrelease, osarch, gitrelease])
148    _mkinitrd_squashfs_isofs (bttargetdir, osrelease, btrootfsimg, btrootfsmnt, pxepkg, isolinux_tpl, nameisoclient)
149
150    logger.info ('OpenGnsys installation finished')
151
152
153if __name__ == '__main__':
154    if os.getuid():
155        print ('ERROR: this program must run under root privileges!!', file=sys.stderr)
156        sys.exit (1)
157
158    parser = argparse.ArgumentParser()
159    parser.add_argument ('--loglevel', help='Log level',                  action='store')
160    parser.add_argument ('--codename', help='OS codename',                action='store')
161    parser.add_argument ('--config',   help='Path to configuration file', action='store')
162    args = parser.parse_args()
163
164    cfgfile = args.config or 'mkoglive.cfg'
165    config = utils.read_config (cfgfile)
166    if config is None:
167        print ('ERROR: no configuration found', file=sys.stderr)
168        sys.exit (1)
169    cfg_loglevel = config['General'].get ('logging_level')
170
171    logger = _logging (args.loglevel or cfg_loglevel)
172
173    _main (cfgfile, config, args.codename)
Note: See TracBrowser for help on using the repository browser.