source: ogLive-Builder-Git/mkoglive.py @ 149d3ff

filebeat-installerimprove-versionmainpull-from-cloning-engine
Last change on this file since 149d3ff was fe39c2d, checked in by Natalia Serrano <natalia.serrano@…>, 6 months ago

refs #953 do this change in a higher-level place, and use an underscore

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