Commit graph

57 commits

Author SHA1 Message Date
Simon de Vlieger
ea6085fae6 osbuild: run isort on all files 2022-09-12 13:32:51 +02:00
Simon de Vlieger
321587ad41 linting: fix use-dict-literal
Use the dict literal `{}` instead of `dict()`, this is a warning in
newer pylints and its consistent with what we do elsewhere.
2022-09-12 10:52:09 +02:00
Simon de Vlieger
873a071d43 osbuild: share terminal formats between files 2022-09-09 21:43:56 +02:00
Simon de Vlieger
3703328751 osbuild: explicit encodings for open()
Provides explicit encodings for all calls to `open()`, this is a newer
pylint warning but also just makes sense to do.
2022-09-09 15:33:29 +02:00
Christian Kellner
2e09e7937c objectstore, move {u,}mount methods to util.mnt
Move the mount and umount helpers to the new mount utility module.
No semantic change in the function.
2022-08-13 19:21:52 +01:00
Christian Kellner
a43ea66be2 util/mnt: rename var to avoid future clash
Rename the local `mount` variable to `mnt` so that we can have
a top level `mount` function.
2022-08-13 19:21:52 +01:00
Christian Kellner
b49f3f91f9 util/mnt: extract MountGuard into new module
Extract the `MountGuard` class from all stages that defined it into
a new `mnt` utility module.
2022-08-13 19:21:52 +01:00
Christian Kellner
f05078f66e global: fix PEP-8 formatting
This patch was generated by running `autopep8 --diff` on the
source tree and then applying the diff.
2022-08-05 09:41:05 +02:00
Simon de Vlieger
3fd864e5a9 osbuild: fix optional-types
Optional types were provided in places but were not always correct. Add
mypy checking and fix those that fail(ed).
2022-07-13 17:31:37 +02:00
Thomas Lavocat
441e67a6f6 ostree: show commit metadata
This new API call allows one to check (among other things) if a commit
exists in a repo. It'll throw a RuntimeException if the commit is
missing.
2022-05-11 04:32:42 -05:00
Christian Kellner
1e4507c3d6 util/ostree: new class to store subordinate ids
Add a new class `SubIdsDB` as a database of subordinate Ids, like the
ones in `/etc/subuid` and `/etc/subgid`. Methods to read and write
data from these two files are provided.
Add corresponding unit tests.
2022-04-28 14:38:24 +01:00
Christian Kellner
1874c71920 util/linux: add capability utilities 2022-04-27 23:05:11 +01:00
Christian Kellner
75df59bace util/selinux: add setfilecon method
This is basically a re-implementation of `setfilecon(3)` minus the
translation of human readable context to raw context. Add test for
the new function.
2022-03-18 20:36:10 +01:00
Christian Kellner
e11d86cdf3 util/selinux: define XATTR_NAME_SELINUX
Define the extended attribute name for SELinux at the module level and
use that in the `getfilecon` function.
2022-03-18 20:36:10 +01:00
Christian Kellner
6300a80c84 util/udev: fix path for udev device inhibitor
The udev inhibitor rules are checking for `device-$major:$minor`
but we created them with `f"device-{major}-{minor}"`. So they
did indeed not actually work. Fix that.
2022-02-27 18:47:17 +01:00
Christian Kellner
0f670829a3 util/linux: fix BLK_IOC_FLSBUF on ppc64le
ioctl contants are platform dependent. It should be the same on
x86, aarch64 and s390x but it is indeed different on ppc64le.
This lead to the call to `ioctl_blockdev_flushbuf` actually
raising an exception of `OSError: [Errno 22] Invalid argument`.

The constant was calculated with a little python snippet that
in theory could also go directly into the code, but for now
the simpler condition in this patch is enough.

The snippet is a port of the defines from the Linux kernel,
specifically /usr/include/asm-generic/ioctl.h.

    class IOConstants:
        """IO Commands for Linux"""
        if platform.machine() == "ppc64le":
            NRBITS = 8
            TYPEBITS = 8
            SIZEBITS = 13

            DIR_NONE = 1
        else:
            NRBITS = 8
            TYPEBITS = 8
            SIZEBITS = 14

            DIR_NONE = 0

        NRSHIFT = 0
        TYPESHIFT = NRSHIFT+NRBITS
        SIZESHIFT = TYPESHIFT+TYPEBITS
        DIRSHIFT = SIZESHIFT+SIZEBITS

        @classmethod
        def make(cls, directory, iotype, nr, size):
            return ((directory << cls.DIRSHIFT) |
                    (iotype << cls.TYPESHIFT) |
                    (nr << cls.NRSHIFT) |
                    (size << cls.SIZESHIFT))

        @classmethod
        def make_dir_none(cls, iotype, nr):
            return cls.make(cls.DIR_NONE, iotype, nr, 0)

This is used to get the value for `BLKFLSBUF` taken from the
include `/usr/include/linux/fs.h`:

    #define BLKFLSBUF  _IO(0x12,97)	/* flush buffer cache */

The value is then obtained via:

    print("0x%x" % IOConstants.make_dir_none(0x12,97))
    0x20001261
2022-02-01 16:28:56 +01:00
Christian Kellner
7e2bb524a4 devices: add custom udev rule inhibitor mechanism
Certain udev rules for block devices are problematic for osbuild.
One prominent example is LVM2 related rules that would trigger
a scan and auto-activation of logical volumes. This rules are
triggered for new block devices or when the backing file of an
loop devices changes. The rules will lead to a `lvm pvscan
--cache --activate ay` via the `lvm2-pvscan@.service` systemd
service. This will auto-activate all LVM2 logical volumes and
thus interfering with our own device handling in `devices/
org.osbuild.lvm2.lv`, where we only want to activate a single
logical volume.
Also, if the lvm2 devices get activated after the manual metadata
change done in `org.osbuild.lvm2.metadata` the volume group names
might conflict which results in all lvm2 based tooling to be very,
ver sad and also said stage to hang since the loopback device can
not be detached since the activate logical volumes keep it open.

To work-around this we therefore implement a udev rule inhibition
mechanism: on the osbuild side a lock file is created via the new
class called `UdevInhibitor` in `utils/udev.py`. A custom set of
udev rules in `10-osbuild-inhibitor.rules` is then acting on the
existence of that lock file and if present will opt-out of certain
further processing. See the udev rules file for more details.

In fact, we want this custom inhibition mechanism, for all block
devices that are under osbuild's control, since these rules are
there to provide automatisms and integrations with the host,
something we never want.

NB: this should not affect the detection of devices, since lvm2
does do a scan of devices when we call `lvdisplay` in `lvm2.lv`.
The call chain as of lvm2 git rev f773040:

  _lvdisplay_single           [tools/lvdisplay.c
    process_each_lv           [tools/toollib.c
      lvmcache_label_scan     [lib/cache/lvmcache.c
        label_scan            [ibidem, here is the device detection!
      lvdisplay_full          [lib/display/display.c
2021-12-09 00:44:21 +00:00
Christian Kellner
7a923efb1d util/rmrf: handle broken symlinks
The current implementation of `rmtree` will try to fix permissions
when it encounters permission errors during its operation. This is
done by opening the target via `os.open` and then adjusting the
immutable flag and the permission bits. This is a problem when the
target is a broken symlink since open will fail with `ENOENT`. A
simple reproducer of this scenario is:
  $ mkdir subdir
  $ ln -s foo subdir/broken
  $ chmod a-w subdir/
  $ python3 -c 'import osbuild; osbuild.util.rmrf.rmtree("subdir")'

Since subdir is not writable, removing `subdir/broken` will fail
with `EPERM` and the `on_error` callback will try to fix it by
invoking `fixperms` on `subdir/broken` which will in `open` since
the target does not exist (broken symlink).

This is fixed by using `O_NOFOLLOW` to open so we will never open
the target. Instead `open` will fail with `ELOOP`; we ignore that
error and in fact we ignore now all errors from `open` since it
does not matter: if fixing the permissions didn't work `unlink`
will just fail (again) with `EPERM` and for symlinks it actually
doesn't matter since "on Linux the permissions of an ordinary
symbolic link are not used in an operations", see symlinks(7).
2021-12-02 11:38:30 +01:00
Sanne Raymaekers
5b5ec8e6b4 util/rhsm: Check if repositories is None before iterating
When `get_fallback_rhsm_secrets` was used, `Subscriptions.repositories`
was None, and `get_secrets` never returned the fallback secrets.

So check if `repositories` is None before
iterating over it, otherwise return the fallback secrets.
2021-09-03 20:52:17 +02:00
Martin Sehnoutka
8b0ea15817 stages: add org.osbuild.ostree.passwd
This stage takes /usr/lib/passwd and /usr/etc/passwd from an OSTree
checkout, merges them into one file, and store it as /etc/passwd in the
buildroot.

It does the same for /etc/group.

The reason for doing this is that there is an issue with unstable UIDs
and GIDs when creating OSTree commits from scratch. When there is a
package that creates a system user or a system group, it can change the
UID and GID of users and groups that are created later.

This is not a problem in traditional deployments because already created
users and groups never change their UIDs and GIDs, but with OSTree we
recreate the files from scratch and then replace the previous one so it
can actually change.

By copying the files to the build root before doing any other
operations, we can make sure that the UIDs and GIDs of already existing
users and groups won't change.

Co-author: Christian Kellner <christian@kellner.me>
2021-08-17 13:53:00 +02:00
Christian Kellner
7762f46594 util/linux: add helper for BLK_IOC_FLSBUF ioctl
Add a helper method to call `ioctl(fd, BLK_IOC_FLUSH_BUFFER, 0)`
from python. NB: the ioctl number 0x1261 is wrong on at least
alpha and sparc. A later test will use this call so we should
catch the usage of it on those platforms.
2021-08-13 17:35:32 +02:00
Christian Kellner
0e31e628d7 utils: add lvm2 utility module
This module provides a `Disk` class that can be used
to read in LVM images and explore and manipulate its
metadata directly, i.e. it reads and writes the data
and headers directly. This allows one to rename an
volume group without having to involve the kernel,
which does not like to have two active LVM volume
groups with the same name.
2021-08-13 12:20:54 +02:00
Martin Sehnoutka
54d7128d65 util/rhsm: Implement a fallback to the previous behaviour
The problem is that some deployments might not have the redhat.repo
file, yet they might have the key and certificate to access Red Hat CDN.
If that was the case, the new approach would cause a regression compared
to the previous behavior.

This patch uses the previous method if the redhat.repo file is not
found or does not contain any matching URL.
2021-07-21 14:38:18 +02:00
Christian Kellner
54fe67ece5 utils/ostree: deployment path helper
Add a simple helper method that returns the path for a deployment,
given the sysroot, the osname, the reference or commit and the
deployment serial. Path might not exist.
`
2021-07-12 18:21:05 +02:00
Christian Kellner
dc201d45fd utils/ostree: add rev_parse helper function
Add a simple helper function that wraps `ostree rev-parse` to make
it easy to resolve an OSTree reference given a repository.
2021-07-12 18:21:05 +02:00
Achilleas Koutsou
901de63fb9 util/path: add path checker helper function
Checks if one path is a child of a second one. Useful for checking if
paths defined in a manifest exist inside the tree.
Optionally checks if the target path exists.
2021-06-28 19:07:42 +02:00
Christian Kellner
70b971b83d util/jsoncomm: add send_and_recv helper
Often, a message is being sent and followed by a call to `recv`
to wait for a reply. Create a simple helper `send_and_recv` that
does both in one method.
Add a simple check for that helper to the tests.
2021-06-09 18:37:47 +01:00
Christian Kellner
610d1c45d5 util/jsoncomm: ability to create socket from fd
Add a new constructor method that allows creating a `Socket` from
an existing file-descriptor of a socket. This might be need when
the socket was passed to a child process.
Add a simple test for the new constructor method.
2021-06-09 18:37:47 +01:00
Christian Kellner
0447b00dfc util/jsoncomm: add pair constructor method
Add a new constructor method, `Socket.new_pair`, to create a pair
of connected sockets (via `socketpair`) and wrap both sides via
`jsoncomm.Socket`.
Add a simple test to check it.
2021-06-09 18:37:47 +01:00
Martin Sehnoutka
ee3760e1ba sources/curl: Implement new way of getting RHSM secrets
The previous version covered too few use cases, more specifically a
single subscription. That is of course not the case for many hosts, so
osbuild needs to understand subscriptions.

When running org.osbuild.curl source, read the
/etc/yum.repos.d/redhat.repo file and load the system subscriptions from
there. While processing each url, guess which subscription is tied to
the url and use the CA certificate, client certificate, and client key
associated with this subscription. It must be done this way because the
depsolving and fetching of RPMs may be performed on different hosts and
the subscription credentials are different in such case.

More detailed description of why this approach was chosen is available
in osbuild-composer git: https://github.com/osbuild/osbuild-composer/pull/1405
2021-06-04 18:23:05 +01:00
Christian Kellner
3236bbb8da util: add new checksum related utilities
Small convenience functions to work with checksums, specifically
working with files and their checksums.
2021-05-12 14:26:16 +02:00
Christian Kellner
6767d04ef5 utils/lorax: add lorax template related helpers
A new module that can parse and execute Lorax script templates,
which are mako template based files that support a limited set
of commands, like "install", "remove" and such.
The module provides helper functions to parse such templates
and execute them by providing a re-implementation of a subset
of the commands. All commands needed for running the post
installationtemplates were implemented.
2021-02-19 14:42:32 +00:00
Christian Kellner
cd1f248dca util/jsoncomm: chain the BufferError in recv
Explicit re-raise the BufferError exception in recv from the orignal
JSONDecodeError, so the latter gets recorded as the underlying cause.

Uncovered by pylint 2.6.0: W0707: "Not using raise from makes the
traceback inaccurate, because the message implies there is a bug in
the exception-handling code itself, which is a separate situation
than wrapping an exception."
2020-10-30 17:28:31 +01:00
Christian Kellner
3010d247ea util/osrelease: add default os-release paths
Add a new `DEFAULT_PATHS` constant, a list of all well known paths
where `os-release` can be found, as per os-release(5).
2020-10-21 11:13:28 +02:00
Christian Kellner
cbcb335b3e osbuild: fix spelling mistakes found by codespell
Run codespell on the source ('codespell -f -L msdos -S coverity
-S rpmbuild -S samples') and fix all uncovered mistakes.
2020-10-06 14:41:00 +02:00
Christian Kellner
785f843901 jsoncomm: remove destination from send
Now that jsoncomm.Socket is using a connection-oriented socket,
the destination in `socket.sendmsg` is ignored and thus can and
should be dropped from the `jsoncomm.Socket.send` method.
Adjust the tests accordingly.
2020-07-29 02:16:20 +01:00
Christian Kellner
abbdf06ba5 jsoncomm: switch to use sequenced-packet sockets
Switch to use a connection oriented datagram based protocol, i.e.
`SOCK_SEQPACKET`, instead of `SOCK_DGRAM`. It sill preserves
message boundaries, but since it is connection oriented the client
nor the server do not need to specify the destination addresses
of the peer in sendmsg/recvmesg. Moreover, the host will be able
to send messages to the client, even if the latter is sandboxed
with a separate network namespace. In the `SOCK_DRAM` case the
auto-bound address of the client would not be visible to the host
and thus sending messages would to it would fail.

Adapt the jsoncomm tests as well as `BaseAPI`.
2020-07-29 02:16:20 +01:00
Christian Kellner
fcf3ec4502 jsoncomm: add connection oriented methods
Implement `accept` and `listen`, that call the equivalent methods
on the underlying socket; this prepares the move to a connection
oriented socket, i.e. `SOCK_SEQPACKET`.
2020-07-29 02:16:20 +01:00
Christian Kellner
2da98a57d7 jsoncomm: add blocking property to Socket
Add a new `blocking` property to get and set the blocking state
of the underlying socket. In Python this is tied to the timeout
setting of the `socket.Socket`, i.e. non-blocking means having
any timeout specified, including "0" for not waiting at all.
Blocking means having a timeout value of `None`.
The getter is emulating the logic of `Socket.getblocking`, which
was added in 3.7, and we need to stay compatible with 3.6.
The logic is implemented in `Modules/socketmodule.c` in Python.
2020-07-29 02:16:20 +01:00
Christian Kellner
ac03c257b9 jsoncomm: remove unnecessary brackets
FdSet does derive directly and only from `object`. Not specifying
any base classes is the same as specifying an empty list of base
classes; therefore get rid of the empty list.
2020-07-27 12:50:38 +01:00
Christian Kellner
28947f3bae util/jsoncomm: support PathLike
Add support for `util.types.PathLike` paths for socket addresses,
instead of just plain strings. Test it by using pathlib.Path to
create the address in the corresponding test.
2020-07-27 12:50:38 +01:00
Christian Kellner
2fd83ac90d util: add types module defining PathLike type
Add a simple new module meant to define types that are commonly
used throughout the code-base. For starters, define `PathLike`
meant to represent file system paths, i.e. strings, bytes, or
anything that provides the `os.PathLike` protocol, i.e. that
can be used with `os.fspath`.
2020-07-27 12:50:38 +01:00
Christian Kellner
0cf581a9a4 util/selinux: add gefilecon helper
Add a simple helper that gets the security context for a given
path as a plain string.
2020-06-15 20:36:48 +02:00
Christian Kellner
696219dab9 util/ostree: accept typing.List for List[str]
In python 3.6 the value of `__origin__` for typing.List[str] is
typing.List. This then changed to the actual `list` type in later
versions. Accept both versions.
2020-06-09 13:42:35 +02:00
Christian Kellner
52f33d56b7 ostree: add 'initramfs-args' option to Treefile
Add the initramfs-args Treefile option that can be used to pass
arguments to drauct via rpm-ostree. NB: the ostree module will
always be automatically be included by rpm-ostree.
2020-06-04 10:25:39 +02:00
David Rheinsberg
13c0dec8ee util/jsoncomm: simplify condition
This reduces `if fds && len(fds) > 0:` to `if fds:`. In python, empty
collections are considered false, so the additional check is not needed.
2020-05-29 11:07:29 +02:00
David Rheinsberg
46526cf205 osbuild: avoid [] as default value
Using `[]` as default value for arguments makes `pylint` complain. The
reason is that it creates an array statically at the time the function
is parsed, rather than dynamically on invocation of the function. This
means, when you append to this array, you change the global instance and
every further invocation of that function works on this modified array.

While our use-cases are safe, this is indeed a common pitfall. Lets
avoid using this and resort to `None` instead.

This silences a lot of warnings from pylint about "dangerous use of []".
2020-05-28 11:06:05 +02:00
David Rheinsberg
8a195d7502 util/ctx: extract suppress_oserror()
Extract the `suppress_oserror()` function from the ObjectManager and
make it available as utility for other code as well.

This also adds a bunch of tests that verify it works as expected.
2020-05-11 18:05:12 +02:00
David Rheinsberg
4493d057a2 osbuild: move osrelease parser into ./util
Reduce the clutter in our pipeline implementation and move the
os-release parser into ./osbuild/util/.
2020-04-28 15:39:00 +02:00
David Rheinsberg
e2aa7d8128 util: mark as module
Make sure ./osbuild/util/ is considered a python module. Add
__init__.py to declare it as such and include it in the module-list of
setup.py.
2020-04-21 17:00:04 +02:00