/* Copyright © 2022 Joel D. Elkins 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" ) type Container struct { Category string Name string Image string Hostname string Command []string Arguments string Networks []network.Network Env map[string]string Mounts []spec.Mount Restart string Umask uint User string 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" } } c.conn = conn if c.Umask == 0 { c.Umask = 0o022 } return c.populateCData() } func (c *Container) LogEntry() *log.Entry { f := log.Fields{ "container": c.Name, } if c.cdata != nil { f["id"] = c.cdata.ID } 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 // if err != nil { // return err // } // return c.populateCData() } func (c *Container) PullCommands() []command.Command { return []command.Command{ command.NewErrFunc("do_pull", func() error { return c.pull() }), } } func (c *Container) CreateCommands() []command.Command { if c.Image == "" { return []command.Command{ command.NewErrFunc("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), }, } if err := spec.Validate(); err != nil { c.LogEntry().WithField("error", err).Warnf("Spec does not validate") } return []command.Command{ command.NewErrFunc("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.NewErrFunc("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.NewErrFunc("do_create", func() error { _, err := containers.CreateWithSpec(c.conn, &spec, nil) if err != nil { return err } return c.populateCData() }), } } func (c *Container) RecreateCommands() []command.Command { wasRunning := false return []command.Command{ command.NewFunc("stash_run_state", func() string { wasRunning = c.IsRunning() runMsg := "not running. Will not start it after recreating." if wasRunning { runMsg = "running. Will restart after recreating." } return fmt.Sprintf("Container %s is %s", c.Name, runMsg) }), 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.Command { cmds := c.StopCommands() cmds = append(cmds, command.NewErrFunc("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.Command { return []command.Command{ command.NewErrFunc("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.Command { return []command.Command{ 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.Command { wasRunning := false return []command.Command{ command.NewErrFunc("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.Command { return []command.Command{ command.NewErrFunc("do_stop", 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() } log.WithFields(log.Fields{ "container": c.Name, "id": c.cdata.ID, }).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 }