Giter Club home page Giter Club logo

systemk's Introduction

Virtual Kubelet

Go Reference

Virtual Kubelet is an open source Kubernetes kubelet implementation that masquerades as a kubelet for the purposes of connecting Kubernetes to other APIs. This allows the nodes to be backed by other services like ACI, AWS Fargate, IoT Edge, Tensile Kube etc. The primary scenario for VK is enabling the extension of the Kubernetes API into serverless container platforms like ACI and Fargate, though we are open to others. However, it should be noted that VK is explicitly not intended to be an alternative to Kubernetes federation.

Virtual Kubelet features a pluggable architecture and direct use of Kubernetes primitives, making it much easier to build on.

We invite the Kubernetes ecosystem to join us in empowering developers to build upon our base. Join our slack channel named, virtual-kubelet, within the Kubernetes slack group.

The best description is "Kubernetes API on top, programmable back."

Table of Contents

How It Works

The diagram below illustrates how Virtual-Kubelet works.

diagram

Usage

Virtual Kubelet is focused on providing a library that you can consume in your project to build a custom Kubernetes node agent.

See godoc for up to date instructions on consuming this project: https://godoc.org/github.com/virtual-kubelet/virtual-kubelet

There are implementations available for several providers, see those repos for details on how to deploy.

Current Features

  • create, delete and update pods
  • container logs, exec, and metrics
  • get pod, pods and pod status
  • capacity
  • node addresses, node capacity, node daemon endpoints
  • operating system
  • bring your own virtual network

Providers

This project features a pluggable provider interface developers can implement that defines the actions of a typical kubelet.

This enables on-demand and nearly instantaneous container compute, orchestrated by Kubernetes, without having VM infrastructure to manage and while still leveraging the portable Kubernetes API.

Each provider may have its own configuration file, and required environmental variables.

Providers must provide the following functionality to be considered a supported integration with Virtual Kubelet.

  1. Provides the back-end plumbing necessary to support the lifecycle management of pods, containers and supporting resources in the context of Kubernetes.
  2. Conforms to the current API provided by Virtual Kubelet.
  3. Does not have access to the Kubernetes API Server and has a well-defined callback mechanism for getting data like secrets or configmaps.

Admiralty Multi-Cluster Scheduler

Admiralty Multi-Cluster Scheduler mutates annotated pods into "proxy pods" scheduled on a virtual-kubelet node and creates corresponding "delegate pods" in remote clusters (actually running the containers). A feedback loop updates the statuses and annotations of the proxy pods to reflect the statuses and annotations of the delegate pods. You can find more details in the Admiralty Multi-Cluster Scheduler documentation.

Alibaba Cloud ECI Provider

Alibaba Cloud ECI(Elastic Container Instance) is a service that allow you run containers without having to manage servers or clusters.

You can find more details in the Alibaba Cloud ECI provider documentation.

Configuration File

The alibaba ECI provider will read configuration file specified by the --provider-config flag.

The example configure file is in the ECI provider repository.

Azure Container Instances Provider

The Azure Container Instances Provider allows you to utilize both typical pods on VMs and Azure Container instances simultaneously in the same Kubernetes cluster.

You can find detailed instructions on how to set it up and how to test it in the Azure Container Instances Provider documentation.

Configuration File

The Azure connector can use a configuration file specified by the --provider-config flag. The config file is in TOML format, and an example lives in providers/azure/example.toml.

AWS Fargate Provider

AWS Fargate is a technology that allows you to run containers without having to manage servers or clusters.

The AWS Fargate provider allows you to deploy pods to AWS Fargate. Your pods on AWS Fargate have access to VPC networking with dedicated ENIs in your subnets, public IP addresses to connect to the internet, private IP addresses to connect to your Kubernetes cluster, security groups, IAM roles, CloudWatch Logs and many other AWS services. Pods on Fargate can co-exist with pods on regular worker nodes in the same Kubernetes cluster.

Easy instructions and a sample configuration file is available in the AWS Fargate provider documentation. Please note that this provider is not currently supported.

Elotl Kip

Kip is a provider that runs pods in cloud instances, allowing a Kubernetes cluster to transparently scale workloads into a cloud. When a pod is scheduled onto the virtual node, Kip starts a right-sized cloud instance for the pod's workload and dispatches the pod onto the instance. When the pod is finished running, the cloud instance is terminated.

When workloads run on Kip, your cluster size naturally scales with the cluster workload, pods are strongly isolated from each other and the user is freed from managing worker nodes and strategically packing pods onto nodes.

HashiCorp Nomad Provider

HashiCorp Nomad provider for Virtual Kubelet connects your Kubernetes cluster with Nomad cluster by exposing the Nomad cluster as a node in Kubernetes. By using the provider, pods that are scheduled on the virtual Nomad node registered on Kubernetes will run as jobs on Nomad clients as they would on a Kubernetes node.

For detailed instructions, follow the guide here.

Interlink Provider

interLink provides an abstraction for the execution of a Kubernetes pod on any remote resource that has the capability to manage a container's execution lifecycle. The use cases that drove the initial development of the tool are the Slurm-powered HPC centers, regardless the plugin based design is enabling several additional use cases to provide Kubernetes-API based access to infrastracture that cannot host a Kubelet processes. InterLink is a Virtual Kubelet provider that can manage container lifecycle through a well defined API specification, allowing for any resource provider to be integrated with a simple http server and a handful of methods. In other words, this is an attempt to streamline the process of creating custom Virtual Kubelet providers, avoiding the need for any resource provider to implement its own version of a Kubelet workflow, which would require having some domain expertise in the Kubernetes internals.

For detailed instruction, follow the guide here.

Liqo Provider

Liqo implements a provider for Virtual Kubelet designed to transparently offload pods and services to "peered" Kubernetes remote cluster. Liqo is capable of discovering neighbor clusters (using DNS, mDNS) and "peer" with them, or in other words, establish a relationship to share part of the cluster resources. When a cluster has established a peering, a new instance of the Liqo Virtual Kubelet is spawned to seamlessly extend the capacity of the cluster, by providing an abstraction of the resources of the remote cluster. The provider combined with the Liqo network fabric extends the cluster networking by enabling Pod-to-Pod traffic and multi-cluster east-west services, supporting endpoints on both clusters.

For detailed instruction, follow the guide here

OpenStack Zun Provider

OpenStack Zun provider for Virtual Kubelet connects your Kubernetes cluster with OpenStack in order to run Kubernetes pods on OpenStack Cloud. Your pods on OpenStack have access to OpenStack tenant networks because they have Neutron ports in your subnets. Each pod will have private IP addresses to connect to other OpenStack resources (i.e. VMs) within your tenant, optionally have floating IP addresses to connect to the internet, and bind-mount Cinder volumes into a path inside a pod's container.

./bin/virtual-kubelet --provider="openstack"

For detailed instructions, follow the guide here.

Tensile Kube Provider

Tensile kube is contributed by tencent games, which is provider for Virtual Kubelet connects your Kubernetes cluster with other Kubernetes clusters. This provider enables us extending Kubernetes to an unlimited one. By using the provider, pods that are scheduled on the virtual node registered on Kubernetes will run as jobs on other Kubernetes clusters' nodes.

Adding a New Provider via the Provider Interface

Providers consume this project as a library which implements the core logic of a Kubernetes node agent (Kubelet), and wire up their implementation for performing the neccessary actions.

There are 3 main interfaces:

PodLifecycleHandler

When pods are created, updated, or deleted from Kubernetes, these methods are called to handle those actions.

godoc#PodLifecylceHandler

type PodLifecycleHandler interface {
    // CreatePod takes a Kubernetes Pod and deploys it within the provider.
    CreatePod(ctx context.Context, pod *corev1.Pod) error

    // UpdatePod takes a Kubernetes Pod and updates it within the provider.
    UpdatePod(ctx context.Context, pod *corev1.Pod) error

    // DeletePod takes a Kubernetes Pod and deletes it from the provider.
    DeletePod(ctx context.Context, pod *corev1.Pod) error

    // GetPod retrieves a pod by name from the provider (can be cached).
    GetPod(ctx context.Context, namespace, name string) (*corev1.Pod, error)

    // GetPodStatus retrieves the status of a pod by name from the provider.
    GetPodStatus(ctx context.Context, namespace, name string) (*corev1.PodStatus, error)

    // GetPods retrieves a list of all pods running on the provider (can be cached).
    GetPods(context.Context) ([]*corev1.Pod, error)
}

There is also an optional interface PodNotifier which enables the provider to asynchronously notify the virtual-kubelet about pod status changes. If this interface is not implemented, virtual-kubelet will periodically check the status of all pods.

It is highly recommended to implement PodNotifier, especially if you plan to run a large number of pods.

godoc#PodNotifier

type PodNotifier interface {
    // NotifyPods instructs the notifier to call the passed in function when
    // the pod status changes.
    //
    // NotifyPods should not block callers.
    NotifyPods(context.Context, func(*corev1.Pod))
}

PodLifecycleHandler is consumed by the PodController which is the core logic for managing pods assigned to the node.

	pc, _ := node.NewPodController(podControllerConfig) // <-- instatiates the pod controller
	pc.Run(ctx) // <-- starts watching for pods to be scheduled on the node

NodeProvider

NodeProvider is responsible for notifying the virtual-kubelet about node status updates. Virtual-Kubelet will periodically check the status of the node and update Kubernetes accordingly.

godoc#NodeProvider

type NodeProvider interface {
    // Ping checks if the node is still active.
    // This is intended to be lightweight as it will be called periodically as a
    // heartbeat to keep the node marked as ready in Kubernetes.
    Ping(context.Context) error

    // NotifyNodeStatus is used to asynchronously monitor the node.
    // The passed in callback should be called any time there is a change to the
    // node's status.
    // This will generally trigger a call to the Kubernetes API server to update
    // the status.
    //
    // NotifyNodeStatus should not block callers.
    NotifyNodeStatus(ctx context.Context, cb func(*corev1.Node))
}

Virtual Kubelet provides a NaiveNodeProvider that you can use if you do not plan to have custom node behavior.

godoc#NaiveNodeProvider

NodeProvider gets consumed by the NodeController, which is core logic for managing the node object in Kubernetes.

	nc, _ := node.NewNodeController(nodeProvider, nodeSpec) // <-- instantiate a node controller from a node provider and a kubernetes node spec
	nc.Run(ctx) // <-- creates the node in kubernetes and starts up he controller

API endpoints

One of the roles of a Kubelet is to accept requests from the API server for things like kubectl logs and kubectl exec. Helpers for setting this up are provided here

Scrape Pod metrics

If you want to use HPA(Horizontal Pod Autoscaler) in your cluster, the provider should implement the GetStatsSummary function. Then metrics-server will be able to get the metrics of the pods on virtual-kubelet. Otherwise, you may see No metrics for pod on metrics-server, which means the metrics of the pods on virtual-kubelet are not collected.

Testing

Unit tests

Running the unit tests locally is as simple as make test.

End-to-end tests

Check out test/e2e for more details.

Known quirks and workarounds

Missing Load Balancer IP addresses for services

Providers that do not support service discovery

Kubernetes 1.9 introduces a new flag, ServiceNodeExclusion, for the control plane's Controller Manager. Enabling this flag in the Controller Manager's manifest allows Kubernetes to exclude Virtual Kubelet nodes from being added to Load Balancer pools, allowing you to create public facing services with external IPs without issue.

Workaround

Cluster requirements: Kubernetes 1.9 or above

Enable the ServiceNodeExclusion flag, by modifying the Controller Manager manifest and adding --feature-gates=ServiceNodeExclusion=true to the command line arguments.

Contributing

Virtual Kubelet follows the CNCF Code of Conduct. Sign the CNCF CLA to be able to make Pull Requests to this repo.

Monthly Virtual Kubelet Office Hours are held at 10am PST on the second Thursday of every month in this zoom meeting room. Check out the calendar here.

Our google drive with design specifications and meeting notes are here.

We also have a community slack channel named virtual-kubelet in the Kubernetes slack. You can also connect with the Virtual Kubelet community via the mailing list.

systemk's People

Contributors

miekg avatar pathcl avatar pires avatar sh4d1 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

systemk's Issues

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.

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?

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.

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.

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.

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

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

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.

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

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.

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.

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.

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"

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.

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 ๐Ÿ‘Ž

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.

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.

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

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.

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.

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

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.

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.

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

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

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

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.

[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 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.

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.

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

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.

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.

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.