Files
kairos-agent/internal/machine/openrc/unit.go
Ettore Di Giacinto 63cd28d1cb Split off cli into separate binaries (#37)
* 🎨 Split off cli into separate binaries

This commit splits off the cli into 3 binaries:
- agent
- cli
- provider

The provider now is a separate component that can be tested by itself
and have its own lifecycle. This paves the way to a ligher c3os variant,
HA support and other features that can be provided on runtime.

This is working, but still there are low hanging fruit to care about.

Fixes #14

* 🤖 Add provider bin to releases

* ⚙️ Handle signals

* ⚙️ Reduce buildsize footprint

* 🎨 Scan for providers also in /system/providers

* 🤖 Run goreleaser

* 🎨 Refactoring
2022-07-04 22:39:34 +02:00

87 lines
1.7 KiB
Go

package openrc
import (
"fmt"
"io/ioutil"
"path/filepath"
"strings"
"github.com/c3os-io/c3os/internal/utils"
)
type ServiceUnit struct {
content string
name string
rootdir string
}
type ServiceOpts func(*ServiceUnit) error
func WithRoot(n string) ServiceOpts {
return func(su *ServiceUnit) error {
su.rootdir = n
return nil
}
}
func WithName(n string) ServiceOpts {
return func(su *ServiceUnit) error {
su.name = n
return nil
}
}
func WithUnitContent(n string) ServiceOpts {
return func(su *ServiceUnit) error {
su.content = n
return nil
}
}
func NewService(opts ...ServiceOpts) (ServiceUnit, error) {
s := &ServiceUnit{}
for _, o := range opts {
if err := o(s); err != nil {
return *s, err
}
}
return *s, nil
}
func (s ServiceUnit) WriteUnit() error {
uname := s.name
if err := ioutil.WriteFile(filepath.Join(s.rootdir, fmt.Sprintf("/etc/init.d/%s", uname)), []byte(s.content), 0755); err != nil {
return err
}
return nil
}
// TODO: This is too much k3s specific
func (s ServiceUnit) OverrideCmd(cmd string) error {
cmd = strings.ReplaceAll(cmd, "/usr/bin/k3s ", "")
svcDir := filepath.Join(s.rootdir, fmt.Sprintf("/etc/rancher/k3s/%s.env", s.name))
return ioutil.WriteFile(svcDir, []byte(fmt.Sprintf(`command_args="%s >>/var/log/%s.log 2>&1"`, cmd, s.name)), 0600)
}
func (s ServiceUnit) Start() error {
_, err := utils.SH(fmt.Sprintf("/etc/init.d/%s start", s.name))
return err
}
func (s ServiceUnit) Restart() error {
_, err := utils.SH(fmt.Sprintf("/etc/init.d/%s restart", s.name))
return err
}
func (s ServiceUnit) Enable() error {
_, err := utils.SH(fmt.Sprintf("ln -sf /etc/init.d/%s /etc/runlevels/default/%s", s.name, s.name))
return err
}
func (s ServiceUnit) StartBlocking() error {
return s.Start()
}