source: ogLive-Builder-Git/mkoglive.py @ 5ecf9f3

browserbuild-browserdeps-vadimfilebeat-installerimprove-versionlgromero-testsmainno-apt-moduleoglive-ipv6pull-from-cloning-enginepybuilder
Last change on this file since 5ecf9f3 was 5ecf9f3, checked in by Natalia Serrano <natalia.serrano@…>, 8 months ago

refs #596 simplify some variables, pass parameters to functions

  • Property mode set to 100755
File size: 7.4 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():
34    global 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    #grep "http://free.nchc.org.tw/drbl-core" /etc/apt/sources.list || echo "deb http://free.nchc.org.tw/drbl-core drbl stable" >> /etc/apt/sources.list
42    pxepkg = None
43    cache = apt.cache_search (['gpxe', 'ipxe'])
44    if cache['gpxe']: pxepkg = 'gpxe'
45    if cache['ipxe']: pxepkg = 'ipxe'
46    if pxepkg is None:
47        logger.error ('neither gpxe nor ipxe found in apt cache')
48        sys.exit (1)
49    logger.info (f'PXE package is "{pxepkg}"')
50    return pxepkg
51
52def _mkrootfs (btrootfsimg, btrootfsmnt, btrootfsimglabel, btvirtualdisksize, bttargetdir, osarch):
53    logger.info ('Stage 1.1 - create, partition and format the rootfs')
54    rc = subprocess.run (f'file "{btrootfsimg}" |grep -q "partition 1 *: ID=0x83"', shell=True).returncode
55    if (rc):   ## 'file|grep' failed
56        try: btog.mkrootfs (btrootfsimg, btrootfsimglabel, btrootfsmnt, btvirtualdisksize, bttargetdir, osarch)
57        except Exception as e:
58            logger.error (str (e))
59            sys.exit (1)
60
61## para hacer schroot --cosas, el mntpt tiene que estar desmontado
62## si está montado da un pete tal que 'E: 10mount: mount: /run/schroot/mount/IMGogclient-7fbf51a2-e37e-48e5-8e5d-83f8901fc7ed: wrong fs type, bad option, bad superblock on /dev/loop1, missing codepage or helper program, or other error.'
63
64def _debootstrap (btrootfsimg, btrootfsmnt, osarch, oscodename, oshttp):
65    logger.info ('Stage 1.2 - debootstrap system')
66    logger.debug ('Try creation of a file within chroot (this operation may fail with "... etc/resolv.conf: No such file or directory"--that is ok)')
67    logger.debug ('Running \'schroot --chroot IMGogclient -- stat /etc\'')
68    cp = subprocess.run (['schroot', '--chroot', 'IMGogclient', '--', 'stat', '/etc'])
69    if (cp.returncode):
70        logger.debug (f'schroot returned code "{cp.returncode}", calling btog.debootstrap()')
71        _mount_rootfs()
72        try: btog.debootstrap (btrootfsimg, btrootfsmnt, osarch, oscodename, oshttp)
73        except Exception as e:
74            logger.error (str (e))
75            sys.exit (1)
76
77# Incluir revisión.
78def _initramfs_version (gitrelease, osrelease, curdir):
79    ## FIXME esto la incluye incondicionalmente, y luego terminamos con "OpenGnsys Client 1.2.0-rc1 gitrelease (osrelease) gitrelease (osrelease) gitrelease (osrelease) gitrelease (osrelease) gitrelease (osrelease) gitrelease (osrelease) ..."
80    #sed -i "1 s/$/ $GITRELEASE ($OSRELEASE)/" ${BTDIR}/includes/etc/initramfs-tools/scripts/VERSION.txt
81    utils.run (['sed', '-i', f'1 s/$/ {gitrelease} ({osrelease})/', f'{curdir}/includes/etc/initramfs-tools/scripts/VERSION.txt'])
82
83def _copy_og_files (btrootfsmnt, osdistrib, oscodename):
84    _mount_rootfs()
85    builder   = '/tmp/opengnsys/oglive_builder'
86    og_shared = '/tmp/opengnsys/shared'
87    og_engine = '/tmp/opengnsys/engine'
88    btog.copy_og_files (builder, og_shared, og_engine, btrootfsmnt, osdistrib, oscodename)
89    utils.umount (btrootfsmnt)
90
91def _chroot_tasks (curdir, osrelease, osarch):
92    logger.debug (f'running \'schroot --chroot IMGogclient -- {curdir}/chroot-tasks.py --osrelease "{osrelease}" --osarch "{osarch}"\'')
93    stdout, _ = utils.run (['schroot', '--chroot', 'IMGogclient', '--', f'{curdir}/chroot-tasks.py', '--osrelease', osrelease, '--osarch', osarch, '--config', args.config or 'mkoglive.cfg'])
94    ## esto deja initrd.img-6.8.0-31-generic y vmlinuz-6.8.0-31-generic en /tmp
95
96def _ssh_stuff (btrootfsmnt):
97    _mount_rootfs()
98    btog.ssh_server (btrootfsmnt)
99    btog.ssh_client (btrootfsmnt)
100    utils.umount (btrootfsmnt)
101    ## el resultado es:
102    ## - hay un nuevo par de claves en la VM /root/.ssh
103    ## - hay otro nuevo par de claves en el rootfs /var/lib/tftpboot/ogclient/ogclientmount/root/.ssh
104    ## - las dos claves públicas (una de cada par) están autorizadan en el rootfs /var/lib/tftpboot/ogclient/ogclientmount/root/.ssh/authorized_keys
105
106def _mkinitrd_squashfs_isofs (bttargetdir, osrelease, btrootfsmnt, pxepkg, isolinux_tpl, nameisoclient):
107    logger.info ('Stage 4.1 - Put initrd in place')
108    _mount_rootfs()
109    btog.move_initrd (bttargetdir, osrelease)
110
111    logger.info ('Stage 4.2 - make squash filesystem')
112    btog.mksquashfs (bttargetdir, btrootfsmnt)
113    utils.umount (btrootfsmnt)
114
115    logger.info ('Stage 4.3 - make iso filesystem')
116    btog.mkisofs (pxepkg, isolinux_tpl, bttargetdir, nameisoclient)
117
118
119parser = argparse.ArgumentParser()
120parser.add_argument ('--loglevel', help='Log level',                  action='store')
121parser.add_argument ('--codename', help='OS codename',                action='store')
122parser.add_argument ('--config',   help='Path to configuration file', action='store')
123args = parser.parse_args()
124
125config = utils.read_config (args.config or 'mkoglive.cfg')
126if config is None:
127    sys.exit (1)
128isolinux_tpl = config['General'].get ('isolinux_template')
129cfg_loglevel = config['General'].get ('logging_level')
130btrootfsimglabel = config['General'].get ('rootfs_image_label')
131
132logger = _logging (args.loglevel or cfg_loglevel)
133type_client = args.codename or 'host'
134
135if os.getuid():
136    logger.error ('ERROR: this program must run under root privileges!!')
137    sys.exit (1)
138
139## this is convenient in case the previous run failed and we want to run this program again
140try: utils.umount (btrootfsmnt)
141except: pass
142
143logger.info ('OpenGnsys CLIENT installation begins')
144
145fd = open (f'{curdir}/gitrelease', 'r')     ## per the Dockerfile
146gitrelease = fd.readline().strip()
147fd.close()
148
149osdistrib, oscodename, osrelease, osarch, oshttp = btog.GetOsInfo (type_client)
150if osdistrib is None:
151    logger.error ('GetOsInfo() failed')
152    sys.exit (1)
153bttargetdir, btrootfsimg, btrootfsmnt, btvirtualdisksize = btog.GetVar (osarch)
154logger.info (':'.join ([osdistrib, oscodename, osrelease, osarch, oshttp]))
155
156logger.info ('STAGE 1 - create and bootstrap rootfs')
157_mkrootfs (btrootfsimg, btrootfsmnt, btrootfsimglabel, btvirtualdisksize, bttargetdir, osarch)
158_debootstrap (btrootfsimg, btrootfsmnt, osarch, oscodename, oshttp)
159
160logger.info ('STAGE 2 - copy files to the rootfs')
161_initramfs_version (gitrelease, osrelease, curdir)
162_copy_og_files (btrootfsmnt, osdistrib, oscodename)
163
164logger.info ('STAGE 3 - perform tasks within the chroot')
165_chroot_tasks (curdir, osrelease, osarch)
166
167_ssh_stuff (btrootfsmnt)
168
169logger.info ('STAGE 4 - generate distribution files')
170pxepkg = _get_pxepkg()
171nameisoclient  = '-'.join (['ogLive', oscodename, osrelease, osarch, gitrelease])
172_mkinitrd_squashfs_isofs (bttargetdir, osrelease, btrootfsmnt, pxepkg, isolinux_tpl, nameisoclient)
173
174logger.info ('OpenGnsys installation finished')
Note: See TracBrowser for help on using the repository browser.