source: ogLive-Builder-Git/mkoglive.py @ 866cdb4

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

refs #597 make image smaller by not keeping a copy of the opengnsys repo

  • Property mode set to 100755
File size: 7.2 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'):
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 ('/tmp/boot-tools_installation.log'),
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():
53    logger.info ('Stage 3.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():
65    logger.info ('Stage 3.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, btdir):
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'{btdir}/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():
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 6.1 - Put initrd in place')
108    _mount_rootfs()
109    btog.move_initrd (bttargetdir, osrelease)
110
111    logger.info ('Stage 6.2 - make squash filesystem')
112    btog.mksquashfs (bttargetdir, btrootfsmnt)
113    utils.umount (btrootfsmnt)
114
115    logger.info ('Stage 6.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')
130
131logger = _logging (args.loglevel or cfg_loglevel)
132type_client = args.codename or 'host'
133
134if os.getuid():
135    logger.error ('ERROR: this program must run under root privileges!!')
136    sys.exit (1)
137
138## this is convenient in case the previous run failed and we want to run this program again
139try: utils.umount (btrootfsmnt)
140except: pass
141
142logger.info ('OpenGnsys CLIENT installation begins')
143
144logger.info ('STAGE 1 - clone opengnsys repo')
145
146fd = open (f'{curdir}/gitrelease', 'r')     ## per the Dockerfile
147gitrelease = fd.readline().strip()
148fd.close()
149
150osdistrib, oscodename, osrelease, osarch, oshttp = btog.GetOsInfo1 (type_client)
151if osdistrib is None:
152    logger.error ('GetOsInfo1() failed')
153    sys.exit (1)
154btdir, bttargetdir, btrootfsimg, btrootfsmnt, btrootfsimglabel, log_file, versionboottools, btvirtualdisksize = btog.GetVar (osarch)
155nameisoclient, namehostclient = btog.GetOsInfo2 (versionboottools, oscodename, osrelease, osarch, gitrelease)
156logger.info (':'.join ([osdistrib, oscodename, osrelease, osarch, oshttp]))
157
158logger.info ('STAGE 2 - install software in the VM')
159pxepkg = _get_pxepkg()
160
161logger.info ('STAGE 3 - create and bootstrap rootfs')
162_mkrootfs()
163_debootstrap()
164
165logger.info ('STAGE 4 - copy files to the rootfs')
166_initramfs_version (gitrelease, osrelease, btdir)
167_copy_og_files (btrootfsmnt, osdistrib, oscodename)
168
169logger.info ('STAGE 5 - perform tasks within the chroot')
170_chroot_tasks (curdir, osrelease, osarch)
171
172_ssh_stuff()
173
174logger.info ('STAGE 6 - generate distribution files')
175_mkinitrd_squashfs_isofs (bttargetdir, osrelease, btrootfsmnt, pxepkg, isolinux_tpl, nameisoclient)
176
177logger.info ('OpenGnsys installation finished')
Note: See TracBrowser for help on using the repository browser.