ccl/internal/pkg/container/container.go

371 lines
9.7 KiB
Go

/*
Copyright © 2022 Joel D. Elkins <joel@elkins.co>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/
package container
import (
"context"
"fmt"
"net"
"os/exec"
"gitea.elkins.co/Networking/ccl/internal/pkg/command"
"gitea.elkins.co/Networking/ccl/internal/pkg/network"
"github.com/containers/common/libnetwork/types"
"github.com/containers/podman/v4/libpod/define"
"github.com/containers/podman/v4/pkg/bindings/containers"
"github.com/containers/podman/v4/pkg/bindings/images"
"github.com/containers/podman/v4/pkg/specgen"
spec "github.com/opencontainers/runtime-spec/specs-go"
log "github.com/sirupsen/logrus"
"gopkg.in/guregu/null.v4"
)
type Container struct {
Category string `toml:"category"`
Name string `toml:"name"`
Image string `toml:"image"`
Hostname string `toml:"hostname,omitempty"`
Command []string `toml:"command,omitempty"`
Arguments string `toml:"arguments,omitempty"`
Networks []network.Network `toml:"networks,omitempty"`
Env map[string]string `toml:"env,omitempty"`
Mounts []spec.Mount `toml:"mounts,omitempty"`
Restart string `toml:"restart,omitempty"`
Umask null.Int `toml:"umask,omitempty"`
User string `toml:"user,omitempty"`
conn context.Context
cdata *define.InspectContainerData
}
func (c *Container) Init(conn context.Context, nets []network.Network) error {
// initialize user-provided definitions
for i := range c.Networks {
var n *network.Network
for j := range nets {
if nets[j].Name == c.Networks[i].Name {
n = &nets[j]
}
}
if n == nil {
continue
}
if len(c.Networks[i].DNS) == 0 {
c.Networks[i].DNS = n.DNS
}
if !c.Networks[i].IPv6.Valid {
if n.IPv6.Valid {
c.Networks[i].IPv6 = n.IPv6
} else {
c.Networks[i].IPv6.SetValid(true)
}
}
}
for i := range c.Mounts {
if c.Mounts[i].Type == "" {
c.Mounts[i].Type = "bind"
}
}
if !c.Umask.Valid {
c.Umask.SetValid(0o022)
}
if conn == nil {
return fmt.Errorf("conn is nil: %s", c.Name)
}
c.conn = conn
return c.populateCData()
}
func (c *Container) LogEntry() *log.Entry {
f := log.Fields{
"container": c.Name,
}
if c.cdata != nil && c.cdata.ID != "" {
f["id"] = c.cdata.ID[:12] + "…"
}
if c.cdata.State != nil {
f["state"] = c.cdata.State.Status
}
return log.WithFields(f)
}
func (c *Container) pull() error {
_, err := images.Pull(c.conn, c.Image, &images.PullOptions{})
return err
}
func (c *Container) PullCommands() command.Commands {
return command.Commands{
command.NewFunc("do_pull", func() error {
return c.pull()
}),
}
}
func (c *Container) CreateCommands() command.Commands {
if c.Image == "" {
return command.Commands{
command.NewFunc("image_error", func() error {
return fmt.Errorf("Image not configured")
}),
}
}
sysctl := map[string]string{}
nets := map[string]types.PerNetworkOptions{}
dns := []net.IP{}
for i := range c.Networks {
if !c.Networks[i].IPv6.Bool {
sysctl["net.ipv6.conf."+c.Networks[i].Name+".accept_ra"] = "0"
}
ips := []net.IP{}
if c.Networks[i].IPv4Address != nil {
ips = append(ips, c.Networks[i].IPv4Address)
}
if c.Networks[i].IPv6Address != nil {
ips = append(ips, c.Networks[i].IPv6Address)
}
nets[c.Networks[i].Name] = types.PerNetworkOptions{
StaticIPs: ips,
InterfaceName: c.Networks[i].Name,
}
dns = append(dns, c.Networks[i].DNS...)
}
spec := specgen.SpecGenerator{
ContainerBasicConfig: specgen.ContainerBasicConfig{
Name: c.Name,
UtsNS: specgen.Namespace{NSMode: specgen.Private},
Hostname: c.Hostname,
RawImageName: c.Image,
RestartPolicy: c.Restart,
Sysctl: sysctl,
Env: c.Env,
Command: c.Command,
},
ContainerStorageConfig: specgen.ContainerStorageConfig{
Image: c.Image,
Mounts: c.Mounts,
},
ContainerNetworkConfig: specgen.ContainerNetworkConfig{
Networks: nets,
DNSServers: dns,
},
ContainerSecurityConfig: specgen.ContainerSecurityConfig{
User: c.User,
Umask: fmt.Sprintf("%#o", c.Umask.Int64),
},
}
return command.Commands{
command.NewFunc("bail_if_exists", func() error {
if ex, err := containers.Exists(c.conn, c.Name, &containers.ExistsOptions{}); err != nil || ex {
if err != nil {
return err
}
return fmt.Errorf("Container %s exists already", c.Name)
}
return nil
}),
command.NewFunc("pull_if_necessary", func() error {
if ex, err := images.Exists(c.conn, c.Image, &images.ExistsOptions{}); err != nil || !ex {
if err != nil {
return err
}
return c.pull()
}
return nil
}),
command.NewFunc("validate_spec", spec.Validate),
command.NewFunc("do_create", func() error {
_, err := containers.CreateWithSpec(c.conn, &spec, nil)
if err != nil {
return err
}
return c.populateCData()
}),
}
}
func (c *Container) RecreateCommands() command.Commands {
wasRunning := false
return command.Commands{
command.NewFunc("stash_run_state", func() error {
wasRunning = c.IsRunning()
return nil
}),
command.NewSet(c.DestroyCommands()),
command.NewSet(c.CreateCommands()),
command.NewConditional("start_if_was_running",
func() bool { return wasRunning },
command.NewSet(c.StartCommands()),
command.NewNop(),
),
}
}
func (c *Container) DestroyCommands() command.Commands {
cmds := c.StopCommands()
cmds = append(cmds, command.NewFunc("remove_if_exists", func() error {
if c.cdata.ID == "" {
return nil
}
yes := true
_, err := containers.Remove(c.conn, c.cdata.ID, &containers.RemoveOptions{Force: &yes})
return err
}))
return cmds
}
func (c *Container) StartCommands() command.Commands {
return command.Commands{
command.NewFunc("start_container", func() error {
if c.cdata.State != nil && c.cdata.State.Running {
return nil
}
err := containers.Start(c.conn, c.cdata.ID, nil)
if err != nil {
return err
}
_, err = containers.Wait(c.conn, c.cdata.ID, &containers.WaitOptions{Condition: []define.ContainerStatus{define.ContainerStateRunning}})
if err != nil {
return err
}
err = c.populateCData()
if err != nil {
return err
}
err = c.assureNetNS()
if err != nil {
return err
}
return nil
}),
}
}
func (c *Container) RestartCommands() command.Commands {
return command.Commands{
command.NewSet(c.StopCommands()),
command.NewSet(c.StartCommands()),
}
}
func (c *Container) IsRunning() bool {
if c.cdata != nil && c.cdata.State != nil {
return c.cdata.State.Running
}
return false
}
func (c *Container) IsCreated() bool {
if c.cdata == nil || c.cdata.ID == "" {
return false
}
return true
}
func (c *Container) UpdateCommands() command.Commands {
wasRunning := false
return command.Commands{
command.NewFunc("do_update_and_stop", func() error {
err := c.pull()
if err != nil {
return err
}
wasRunning = c.cdata != nil && c.cdata.State != nil && c.cdata.State.Running
if wasRunning {
var timeout uint = 10
err := containers.Stop(c.conn, c.cdata.ID, &containers.StopOptions{Timeout: &timeout})
if err != nil {
return err
}
_, err = containers.Remove(c.conn, c.cdata.ID, nil)
if err != nil {
return err
}
c.cdata = nil
}
return nil
}),
command.NewSet(c.CreateCommands()),
command.NewConditional("restart_if_was_running",
func() bool { return wasRunning },
command.NewSet(c.StartCommands()),
command.NewNop(),
),
}
}
func (c *Container) StopCommands() command.Commands {
return command.Commands{
command.NewFunc("stop_if_running", func() error {
if c.IsRunning() {
var timeout uint = 10
err := containers.Stop(c.conn, c.cdata.ID, &containers.StopOptions{Timeout: &timeout})
if err != nil {
return err
}
_, err = containers.Wait(c.conn, c.cdata.ID, &containers.WaitOptions{Condition: []define.ContainerStatus{define.ContainerStateExited}})
if err != nil {
return err
}
return c.populateCData()
}
c.LogEntry().Debugf("Container stopped but wasn't running. Not a problem.")
return nil
}),
}
}
func (c *Container) populateCData() error {
// TODO: locking
var err error
no := false
c.cdata, err = containers.Inspect(c.conn, c.Name, &containers.InspectOptions{Size: &no})
if err != nil {
return err
}
return nil
}
func (c *Container) Pid() int {
if c.cdata != nil && c.cdata.State != nil {
return c.cdata.State.Pid
}
return 0
}
func (c *Container) assureNetNS() error {
if nil == c.cdata || nil == c.cdata.NetworkSettings {
return fmt.Errorf("Network namespace not available!")
}
netns := c.cdata.NetworkSettings.SandboxKey
if err := exec.Command("rm", "-f", "/var/run/netns/"+c.Name).Run(); err != nil {
return err
}
if err := exec.Command("ln", "-sf", netns, "/var/run/netns/"+c.Name).Run(); err != nil {
return err
}
return nil
}