container: add option to run init command after container initialization

This commit is contained in:
criyle 2024-04-16 10:47:48 +00:00
parent 598c606a99
commit 60a64d0fb1
4 changed files with 21 additions and 4 deletions

View File

@ -4,6 +4,7 @@ import (
"errors"
"fmt"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
@ -237,7 +238,17 @@ func initContainer(c containerConfig) error {
if err := syscall.Sethostname([]byte(c.HostName)); err != nil {
return err
}
return os.Chdir(c.WorkDir)
if err := os.Chdir(c.WorkDir); err != nil {
return err
}
if len(c.InitCommand) > 0 {
cm := exec.Command(c.InitCommand[0], c.InitCommand[1:]...)
if output, err := cm.CombinedOutput(); err != nil {
os.Stderr.Write(output)
return err
}
}
return nil
}
func initFileSystem(c containerConfig) error {

View File

@ -59,6 +59,10 @@ type Builder struct {
// DomainName set container domainname (default: go-sandbox)
DomainName string
// InitCommand defines command that runs after the initialization of the container
// to do additional setups (for example, loopback network)
InitCommand []string
// ContainerUID & ContainerGID set the container uid / gid mapping
ContainerUID int
ContainerGID int
@ -178,6 +182,7 @@ func (b *Builder) Build() (Environment, error) {
Mounts: mounts,
SymbolicLinks: links,
MaskPaths: maskPaths,
InitCommand: b.InitCommand,
Cred: b.CredGenerator != nil,
ContainerUID: b.ContainerUID,
ContainerGID: b.ContainerGID,

View File

@ -60,6 +60,7 @@ type containerConfig struct {
Mounts []mount.Mount
SymbolicLinks []SymbolicLink
MaskPaths []string
InitCommand []string
ContainerUID int
ContainerGID int

View File

@ -10,16 +10,16 @@ import (
// Mount calls mount syscall
func (m *Mount) Mount() error {
if err := ensureMountTargetExists(m.Source, m.Target); err != nil {
return err
return fmt.Errorf("mkdir: %w", err)
}
if err := syscall.Mount(m.Source, m.Target, m.FsType, m.Flags, m.Data); err != nil {
return err
return fmt.Errorf("mount: %w", err)
}
// Read-only bind mount need to be remounted
const bindRo = syscall.MS_BIND | syscall.MS_RDONLY
if m.Flags&bindRo == bindRo {
if err := syscall.Mount("", m.Target, m.FsType, m.Flags|syscall.MS_REMOUNT, m.Data); err != nil {
return err
return fmt.Errorf("remount: %w", err)
}
}
return nil