Giter Club home page Giter Club logo

systemk's Issues

add k3s token support

this is taken from the k3s site, and even though it's k3s specific it will simplify my intended use case for it, namely using it with k3s first.

sudo k3s server &
# Kubeconfig is written to /etc/rancher/k3s/k3s.yaml
sudo k3s kubectl get node

# On a different node run the below. NODE_TOKEN comes from /var/lib/rancher/k3s/server/node-token
# on your server
sudo k3s agent --server https://myserver:6443 --token ${NODE_TOKEN}

This still doesn't solve the TLS cert issue, but makes bootstrapping slightly easier.

static pods

Should do something like static pods? Can probably use k3s server for this, but something needs to mirror it in the api server, and systemk must do that.

Would simplify a bunch of things as we can just throw some yaml in a directory and stuff will happen.

Fix Image == Name confusion

Currently it is assume image == pod name, which is generally not true. There is also an Image function that should actually be Name.

Clear up this confusion and use the right terms in the right place.

Force mountPaths to be below directory

To further restrict what a podspec can do we could enforce that only mount points under /opt/systemk (or whatever) are acceptable. This prevents systemk from chowning directories it shouldn't.

feature: support different versions of systemd

For instance, in RHEL7 (systemd 219), user-mode systemd doesn't seem to be a thing. Also, certain unit attributes we populate today are unsupported, such as:

  • BindReadOnlyPaths
  • PrivateMounts
  • ReadOnlyPaths
  • TemporaryFileSystem

I understand older distros may not be a goal but if we want this project to be used on bigger companies, we'll have to account for this.

root-less: syntax for not installing packages

I have a use case where the binaries are mounted into the system via some automounter (not that important). But this means the binaries are just there, nothing to install, this means we don't need root access (#30) just to the ability to speak systemd (systemd should be configured to disallow privilege escalation or maybe we can build something into systemk).

Anyway to do this know you do the following:

  - name: while
    image: bash
    command: ["bash", "-c"]
    args: ["while true; do cat /etc/uptimed/test.txt; sleep 1; done"]

where bash will be installed, but the args and command don't need to be in the image, they can reference anything on the filesystem.

So (1) to run root-less and prevent installing software we can do 2 things: a bogus image or something more structured, i.e.

  - name: while
    image: never-install-this
    command: ["bash", "-c"]
    args: ["while true; do cat /etc/uptimed/test.txt; sleep 1; done"

Will mean never-install-this is a special name for which we skip installation.

Or: (2)

  - name: while
    image: /this/image/contains/slashes/don't/install
    command: ["bash", "-c"]
    args: ["while true; do cat /etc/uptimed/test.txt; sleep 1; done"

Here the image name contains slashes (or starts with a slash). We take this as a cue to not install anything in this case. This approach is similar to the https:// prefix that gets the package and installs it.

I like approach (2) the best. Upgrading and getting a new version is changing the image-name/path which is how it should be.
If agreed actual implementation is fairly trival

Figure out how to do e2e tests

Having (copying from k8s?) a (simple?) e2e test frame work would help. Case in point, if I update a project secret will systemk update the file(s) on disk? There is currently no code in the repo that captures systemk's behavior other than a few unit tests.

This requires a way to script these tests, capture the change in addition to having a control plane running.

Stop chowning paths from systemk

I think (not sure here) that we want to outsource the creation/chowning of files and directories to systemd. I thought of this before but the thinking back then was this will be too much shell scripting.

I'm coming back to this because permissions: if we (systemk binary) doesn't do it, we can run root-less pretty easily and just outsource it to systemd.

Alternatively we can write a little go utility that does this and that gets called from systemd, main point(s) being systemk doesn't do this, something called from a unit file does does. This also removed state tracking from systemk, as we just create more units. Ordering will be done with Before: and After:.
This can just be done with (multiple) ExecPreStart and ExecPostStops (see comments below)

Keeping systemk stateless is also worth while.

export metrics

Things are working well enough that it is time to think about exporting metrics and what would be a good set of metrics to have.

warn when unimplemented podspec constructs are seen

Right now there is no good way (except reading the source of pod.go) to know if a specific construct in a podspec is implemented or not. It would be good to log/alert/fail if we see such a construct. This would also make it clear what things are still "to be implemented"

Test k8s Jobs

I need something to run once (across all nodes - which Jobs doesn't do), but Jobs make heavy use of restartPolicy, so we should check how they fare with systemk

chore: address code quality

It's always a good idea - or so I believe - to adopt some best-practices early on, before a project moves past the prototype phase. While growing functionality is always great, there's added value in ensuring the code is properly documented.

Now, linting code at this point will make at least one of us go through it and learn. And, following #15, automatic linting should be run by CI so every contributor comments their code appropriately. That said, don't forget to set --set_error_status when calling golint in the Github worklow.

Tracking VK changes

This is just a way for us to track changes to VK that we'll want to adopt for various reasons, such as reduce boilerplate code, improvements, bugfixes, etc. I'm not expecting this issue to be closed by a PR.

Reduce boilerplate

internal/external address

Right now there is a bit of code that figures out what the external addresses are and which are internal. This assumes rfc-1918 address space, which may be a stretch.

We probable need the make flags for this if the defaults don't suite you. A pod can then use these by inspecting the node object (I think that how you do it) and set some env vars which can then be used.

My use case: prom metrics should be exposed on the private port.

Implement runInContainer

I thinking of implementing run-in-container, but I'm wondering about auth. I don't fully understand it yet from the k8s side, but I do think it makes sense to have a defense in depth and also check the local user on the system.

So I'm thinking of utilizing ssh and using the user ID from the kubectl call (how to get that though?) and then performing a ssh USER@localhost and dropping you in the /var/run/systemk/UID directory; which you can escape as you are free to roam the system; just like normal ssh. And commands given are dropped for the time being, but we may just want to go with garbage in; garbage out.

liveness (network) probes

Implement liveness probes: httpGet and tcpSocket. Execing a command in the container is hard(er), as we may need to get into the namespace - this is doable as we know the volumes that exist. But we should guard against an rm -rf / command as we run as root...
httpGet and tcpSocket are much less destructive and can be simply built into systemk

When run in user mode use /var/run/$UID instead of /var/run for bindmounts

With the -u flag we run in user mode, talking to user systemd. This also moved the unitdir to the per-user tmp dir in /var/run. However the bind mount directories are still created under /var/run/ which means that will still fail.

Those directories should also be created under the /var/run/$UID dir.

ExecStart has 'need'

[Service]
ProtectSystem=true
ProtectHome=tmpfs
PrivateMounts=true
ReadOnlyPaths=/
StandardOutput=journal
StandardError=journal
User=0
Group=0
RemainAfterExit=true
ExecStart=need "--config.file=/etc/prometheus/prometheus.yml" "--storage.tsdb.path=/tmp/prometheus"
TemporaryFileSystem=/var /run
Environment=HOSTNAME=localhost
Environment=KUBERNETES_SERVICE_PORT=6444
Environment=KUBERNETES_SERVICE_HOST=127.0.0.1

[X-Kubernetes]
Namespace=default
ClusterName=
Id=aa-bb

This is wrong:

ExecStart=need "--config.file=/etc/prometheus/prometheus.yml" "--storage.tsdb.path=/tmp/prometheus"

it may be wrong because of testing, but it's wrong nonetheless.

[question] systemk <-> k3s server tunnel ?

does systemk vk use k3s remotedialer to setup tunnel with k3s server ? I dont see it referenced in this repo. If not, does it mean vk (or any worker node) can join k3s cluster without tunnel ?

add configmap updates

One of the last things I need is having a watch on configmap and update the file in the unit.

With that piece only the infrastructure side of TLS certificates remains

feature: kubectl logs options

Unit logs are made available to journald, and that's great but that's an implementation detail. For any Kubernetes user, kubectl logs [--follow] <pod name> is what's expected to work.

At the time of this writing, there are hints that we agree this feature makes sense:

systemk/systemd/pod.go

Lines 265 to 274 in 745f958

func (p *P) GetContainerLogs(ctx context.Context, namespace, podName, containerName string, opts api.ContainerLogOpts) (io.ReadCloser, error) {
log.Printf("GetContainerLogs called")
unitname := UnitPrefix(namespace, podName) + separator + containerName
args := []string{"-u", unitname}
cmd := exec.Command("journalctl", args...)
// returns the buffers? What about following, use pipes here or something?
buf, err := cmd.CombinedOutput()
return ioutil.NopCloser(bytes.NewReader(buf)), err
}

The way I see it, the implementation could do with a bit more love. And as I was looking into what could be done on that front, I recalled moby (dockerd) does provide a journald logging driver, which relies on https://github.com/coreos/go-systemd/blob/master/sdjournal/journal.go, but it is quite verbose. So I'm starting this issue to brainstorm if it makes sense to adopt such code, if there are any known alternatives or, ultimately, if this becomes a non-goal entirely.

Flag --nodename doesn't work

In VK, it is possible to define the hostname that a virtual node will be registered with in Kubernetes. However, this is not possible here given a bunch of calls to

// Hostname returns the machine's host name.
// if the environment variabe HOSTNAME is present this takes precedence.
func Hostname() string {
// there is also a flag for this to systemk ? use that instead?
if h := os.Getenv("HOSTNAME"); h != "" {
return h
}
h, _ := os.Hostname()
return h
}
. These calls happen in the included NodeProvider implementation

systemk/systemd/node.go

Lines 24 to 33 in 745f958

node.ObjectMeta = metav1.ObjectMeta{
Name: system.Hostname(),
Labels: map[string]string{
"type": "virtual-kubelet",
"kubernetes.io/role": "agent",
"kubernetes.io/hostname": system.Hostname(),
corev1.LabelZoneFailureDomainStable: "localhost",
corev1.LabelZoneRegionStable: system.Hostname(),
},
}

I think the flag should either be removed (inherited from virtual-kubelet/node-cli) or somehow be respected in the first block.

flags.Lookup("nodename") does not work

We are being smart on how --nodename is used, but looking up the flag. But that code does not seem to be executed because the flags.Lookup() func is looking in the wrong flag set. We need to look this up in the original VK flagset, but that's hidden from us in cli.Command. That type doesn't give us access to corba.Command which does have method to access the flagset.

This also means we can't remove flags from the original set even though they are useless in systemk - they still show up in the --help ๐Ÿ‘Ž

TLS certs for handlers we run

For the log handler we have the tls-cert and tls-key flags that read a cert. It would be nice(r) if we just embed a ACME client that gets these certs from a CA.

Alternatively this could be outsourced, but then we would need to periodically re-read the key and cert from disk.

I think at this point I prefer ACME as I need to run my own CA anyhow.

crashloopBackoff

when we see this:
systemk.monitoring.prometheus.prometheus.service: Scheduled restart job, restart counter is at 5.
we should probably signal crashloopBackoff to the server.

unit file getter function

Right now we have a bunch of write functions for unit file Overwrite, Delete and Insert we don't have a Read function, so there is a bunch of u.Contents["Service"]["ExecStart"] to get to a value.

An Getter function would be nice here, maybe:

// Content returns the values set in section, under name. If not found nil is returned.
func (u *File) Content(section, name string) []string { .... }

Should be added in internal/unit/file.go and then all callers should be updated.

log support requires CGO

#70 and #69 add log support, but it calls a clib, so now we no longer create a static build, but ref libc and friends

This also makes a releasing a no go, because I will probably have an incompatible libc.

go bc -ldflags="-extldflags=-static"  
# github.com/virtual-kubelet/systemk
/usr/bin/ld: /tmp/go-link-075005359/000015.o: in function `_cgo_d744bec0c646_Cfunc_dlopen':
/tmp/go-build/cgo-gcc-prolog:90: warning: Using 'dlopen' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/bin/ld: /tmp/go-link-075005359/000025.o: in function `mygetgrouplist':
/home/miek/up/go/src/os/user/getgrouplist_unix.go:16: warning: Using 'getgrouplist' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/bin/ld: /tmp/go-link-075005359/000024.o: in function `mygetgrgid_r':
/home/miek/up/go/src/os/user/cgo_lookup_unix.go:38: warning: Using 'getgrgid_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/bin/ld: /tmp/go-link-075005359/000024.o: in function `mygetgrnam_r':
/home/miek/up/go/src/os/user/cgo_lookup_unix.go:43: warning: Using 'getgrnam_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/bin/ld: /tmp/go-link-075005359/000024.o: in function `mygetpwnam_r':
/home/miek/up/go/src/os/user/cgo_lookup_unix.go:33: warning: Using 'getpwnam_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/bin/ld: /tmp/go-link-075005359/000024.o: in function `mygetpwuid_r':
/home/miek/up/go/src/os/user/cgo_lookup_unix.go:28: warning: Using 'getpwuid_r' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
/usr/bin/ld: /tmp/go-link-075005359/000020.o: in function `_cgo_26061493d47f_C2func_getaddrinfo':
/tmp/go-build/cgo-gcc-prolog:58: warning: Using 'getaddrinfo' in statically linked applications requires at runtime the shared libraries from the glibc version used for linking
****

This creates a static bin on my setup.
Another downside of cgo is that per go routines stack is no longer 2k, it's 1M or something

ownership of host mountpath

When setting up a bindmount there needs to be a dir on the host fs that is used to hook the bind mount on.

    volumeMounts:
    - mountPath: /data/cdrom
      name: demo-volume

the directory /data/cdrom needs to exist, we currently chown this to uid/gid of the user running the pod (or via the security context), this means when 2 pods use the same mountPath but run as different users we chown this twice and to different user.

A better idea is to just create this with the uid/gid of the user running systemk and setting a liberal mode on it.

run root-less?

Can we run as non-root? Potentially letting systemd doing all the heavy lifting?

Of course being able to send arbitrary unit to systemd is indistinguishable from actually being root... But it might benefit some use cases.

It could very much turn out this is not possbile.

metrics server

Check to see if we can easily run metrics server to provide resource metrics.

This probably means exporting a bunch of metrics from systemk side

securityContext

securityContext can be applied on the pod level or even per container. This focusses on the pod
level one.

For starters it only allows integers to be specified. Systemd allows user/group names (and also
numbers?). Anyway. I want to run prometheus with the 'prometheus' user. As the pkg (on Debian) gets
installed, it will also add the user 'prometheus' and reference it in the unit file. This works perfectly
fine from the systemd perspective.

Now... from the k8s side you can't guess the user id of the prometheus user, so you probably then
will want to omit the securityContext and let the unit figure it out. (1)

Or (2) you make sure users exist and the securityContext can reference those by ID.

So I don't want to go the (2) route because I don't want to saddle myself with syncing users ID as
well. But doing (1) has implications as well, mostly for chowning the dirs on disk for volumes.

Example:

Say the user is prometheus and the securityContext is empty. Empty context assumes "root" in k8s
land, and of course doing everything as root will work. But we want to use 'prometheus' here. So we
need to figure out what user the unit file has and delay making changes on disk until we know this.

But how does this work with multiple units (=containers) and different user IDs?
If they share a emptyDir, what perms should we do there?

Also when there are multiple units which one is the one we looks for the user?
The first? Or with some annotation?

remove klog flags that are not needed

I've used one klog flag today klog.v. It seems odd that the logging library needs to have the majority of the flags of the binary.

I propose we ditch them all except for the v one

enhancement: systemd-nspawn to launch real Image= container

using systemd-nspawn would let us run real containers, under systemd. from the man page's description:

systemd-nspawn may be used to run a command or OS in a light-weight namespace container. In many ways it is similar to chroot(1), but more powerful since it fully virtualizes the file system hierarchy, as well as the process tree, the various IPC subsystems and the host and domain name.).

it would be neat to add a mode to systemk that allows us to use systemd-nspawn to run full containers. Image= could be real images. systemd-nspawn supports a variety of network modes, such as macvlan and ipvlan. there is an machinectl shell which would enable runInContainer, a systemk feature request tracked in #37. pretty specific/fancy stuff but there's also things like the ability to clone a btrfs subvolume & launch that.

to run a systemd-nspawn container is a couple step process:

  1. create a filesystem in /var/lib/machines/ with the expanded image. systemd's machinectl tool includes import-tar and import-fs helpers which could help load images. to fetch an image, we could use docker save, docker export, or something like what nspawn-oci does to load the image ( using skopeo to get & oci-image-tools to expand an image).
  2. run the container. this can be done ephemerally, or we can create a unit.
    a. use systemd-nspawn to run the container once off, or
    b. create a /etc/systemd/nspawn/my-service.nspawn unit file to configure a container then run machinectl start to start it, in a managed way.

note that two years ago systemd seemed interested in becoming a runc compatible runtime, and if that happens my understanding is we could just run containerd directly against it, which might be a better idea than adapting systemk.

background: current systemk architecture

some notes i took, investigating how systemk works now

kubernetes pods are backed by systemd .service units created by unit manager.

these systemd services use the local system to run. Image= refers to debian packages that are run on the system.

user mode is not feasible

I've gutted everything I can think of, but I keep getting

feb 02 16:18:53 draak systemd[66422]: systemk.default.date.date.service: Failed to set up mount namespacing: Operation not supported
feb 02 16:18:53 draak systemd[66422]: systemk.default.date.date.service: Failed at step NAMESPACE spawning /usr/bin/bash: Operation not supported
feb 02 16:18:53 draak systemd[1762]: systemk.default.date.date.service: Main process exited, code=exited, status=226/NAMESPACE
feb 02 16:18:53 draak systemd[1762]: systemk.default.date.date.service: Failed with result 'exit-code'.

This is with a unit file:

[Unit]
Description=systemk
Documentation=man:systemk(8)

[Install]
WantedBy=multi-user.target

[Service]
PrivateMounts=false
NoNewPrivileges=true
StandardOutput=journal
StandardError=journal
RemainAfterExit=true
ExecStart=/usr/bin/bash -c "while true; do date;  sleep 1; done"
BindPaths=/var/run/user/1000/da80f0e1-5cae-421a-906f-6cd80a7f1bd6/secrets/#0:/var/run/secrets/kubernetes.io/serviceaccount
Environment=HOSTNAME=draak
Environment=KUBERNETES_SERVICE_PORT=6444
Environment=KUBERNETES_SERVICE_HOST=127.0.0.1
Environment=SYSTEMK_NODE_INTERNAL_IP=192.168.86.22
Environment=SYSTEMK_NODE_EXTERNAL_IP=192.168.86.22

[X-Kubernetes]
Namespace=default
ClusterName=
Id=da80f0e1-5cae-421a-906f-6cd80a7f1bd6
Image=bash

I might also drop the BindPaths entirely (that's the last thing that still there), but breaks the setup because that path is assumed to be /var/run/secrets.
But, then again, maybe it's something else entirely that I'm missing

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.