Compare commits

...

7 Commits

Author SHA1 Message Date
yo
7cf4594f34 Update TODO list with some bugs 2022-11-20 20:20:44 +01:00
yo
37fea55e42 Add update command 2022-11-20 20:20:20 +01:00
yo
c15ee68d2e Add update command 2022-11-20 20:20:06 +01:00
yo
54fd1f8064 FIXME: Update Last_started 2022-11-20 20:19:37 +01:00
yo
89db166040 FIXME: Update release in config file when stopping jail 2022-11-20 20:17:59 +01:00
yo
9c18a83ee8 ExecuteCommandWithOutputToStdout 2022-11-20 20:16:23 +01:00
yo
561ae4386a FIXME 2022-11-20 20:13:47 +01:00
7 changed files with 316 additions and 44 deletions

View File

@ -1,4 +1,8 @@
Replicating jails between two servers (use zrepl) Replicating jails between two servers (use zrepl)
DEBUG:
- cmd/list.go:275:
// FIXME ??? Shouldn't be ioc-$Name ?
j.InternalName = rj.Name
- WriteConfigToDisk don't write neither "release" in cmd stop neither "last_started" in cmd start

View File

@ -272,6 +272,7 @@ func listJailsFromDirectory(dir string, dsname string) ([]Jail, error) {
if rj.Path == j.RootPath { if rj.Path == j.RootPath {
j.JID = rj.Jid j.JID = rj.Jid
j.Running = true j.Running = true
// FIXME ??? Shouldn't be ioc-$Name ?
j.InternalName = rj.Name j.InternalName = rj.Name
j.Devfs_ruleset = rj.Devfs_ruleset j.Devfs_ruleset = rj.Devfs_ruleset
break break

View File

@ -14,7 +14,7 @@ import (
) )
const ( const (
gVersion = "0.32a" gVersion = "0.33a"
// TODO : Get from $jail_zpool/defaults.json // TODO : Get from $jail_zpool/defaults.json
MIN_DYN_DEVFS_RULESET = 1000 MIN_DYN_DEVFS_RULESET = 1000
@ -134,7 +134,7 @@ ex: gocage list srv-db srv-web`,
} else { } else {
StartJail(args) StartJail(args)
} }
WriteConfigToDisk(false) WriteConfigToDisk("", false, false)
}, },
} }
@ -148,7 +148,7 @@ ex: gocage list srv-db srv-web`,
ListJails(args, false) ListJails(args, false)
StopJail(args) StopJail(args)
StartJail(args) StartJail(args)
WriteConfigToDisk(false) WriteConfigToDisk("", false, false)
}, },
} }
@ -171,7 +171,7 @@ Multiples properties can be specified, separated with space (Ex: gocage set allo
// Load inventory // Load inventory
ListJails(args, false) ListJails(args, false)
SetJailProperties(args) SetJailProperties(args)
WriteConfigToDisk(true) WriteConfigToDisk("", true, false)
}, },
} }
@ -253,7 +253,7 @@ You can specify multiple jails.`,
// Load inventory // Load inventory
ListJails(args, false) ListJails(args, false)
MigrateJail(args) MigrateJail(args)
WriteConfigToDisk(false) WriteConfigToDisk("", false, false)
}, },
} }
@ -303,6 +303,15 @@ You can specify multiple datastores.`,
}, },
} }
UpdateCmd = &cobra.Command{
Use: "update",
Short: "Update FreeBSD release",
Run: func(cmd *cobra.Command, args []string) {
ListJails(args, false)
UpdateJail(args)
},
}
testCmd = &cobra.Command{ testCmd = &cobra.Command{
Use: "test", Use: "test",
Short: "temporary command to test some code snippet", Short: "temporary command to test some code snippet",
@ -378,6 +387,7 @@ func init() {
rootCmd.AddCommand(migrateCmd) rootCmd.AddCommand(migrateCmd)
rootCmd.AddCommand(datastoreCmd) rootCmd.AddCommand(datastoreCmd)
rootCmd.AddCommand(fetchCmd) rootCmd.AddCommand(fetchCmd)
rootCmd.AddCommand(UpdateCmd)
rootCmd.AddCommand(testCmd) rootCmd.AddCommand(testCmd)
@ -461,59 +471,68 @@ func initConfig() {
} }
/******************************************************************************** /********************************************************************************
* Write jails config which been updated to disk. * Write jail(s) config which been updated to disk.
* If name is specified, work on the jail. If name is empty string, work on all.
* If changeauto not set, values which are in "auto" mode on disk * If changeauto not set, values which are in "auto" mode on disk
* won't be overwritten (p.ex defaultrouter wont be overwritten with current * won't be overwritten (p.ex defaultrouter wont be overwritten with current
* default route, so if route change on jailhost this will reflect on jail next * default route, so if route change on jailhost this will reflect on jail next
* start) * start)
*******************************************************************************/ *******************************************************************************/
func WriteConfigToDisk(changeauto bool) { func WriteConfigToDisk(jailName string, changeauto bool, forceWrite bool) {
for _, j := range gJails { for _, j := range gJails {
if j.ConfigUpdated { if len(jailName) > 0 && j.Name == jailName || len(jailName) == 0 {
//log.Debug("%s config has changed, write changes to disk\n", j.Name) if j.ConfigUpdated || forceWrite {
log.Debug("%s config has changed, write changes to disk\n", j.Name)
// we will manipulate properties so get a copy // we will manipulate properties so get a copy
jc := j.Config jc := j.Config
if changeauto == false { if changeauto == false {
// Overwrite "auto" properties // Overwrite "auto" properties
ondiskjc, err := getJailConfig(j.ConfigPath) ondiskjc, err := getJailConfig(j.ConfigPath)
if err != nil {
panic(err)
}
// TODO : List all fields, then call getStructFieldValue to compare value with "auto"
// If "auto" then keep it that way before writing ondiskjc to disk
var properties []string
properties = getStructFieldNames(ondiskjc, properties, "")
for _, p := range properties {
v, _, err := getStructFieldValue(ondiskjc, p)
if err != nil { if err != nil {
panic(err) panic(err)
} }
if v.String() == "auto" { // TODO : List all fields, then call getStructFieldValue to compare value with "auto"
err = setStructFieldValue(&jc, p, "auto") // If "auto" then keep it that way before writing ondiskjc to disk
var properties []string
properties = getStructFieldNames(ondiskjc, properties, "")
for _, p := range properties {
v, _, err := getStructFieldValue(ondiskjc, p)
if err != nil { if err != nil {
fmt.Printf("ERROR sanitizing config: %s\n", err.Error()) panic(err)
os.Exit(1) }
if v.String() == "auto" {
err = setStructFieldValue(&jc, p, "auto")
if err != nil {
fmt.Printf("ERROR sanitizing config: %s\n", err.Error())
os.Exit(1)
}
} }
} }
} }
}
marshaled, err := json.MarshalIndent(jc, "", " ") marshaled, err := json.MarshalIndent(jc, "", " ")
if err != nil { if err != nil {
fmt.Printf("ERROR marshaling config: %s\n", err.Error()) fmt.Printf("ERROR marshaling config: %s\n", err.Error())
} }
//fmt.Printf(string(marshaled))
if os.WriteFile(j.ConfigPath, []byte(marshaled), 0644); err != nil { fmt.Printf("DEBUG: Will write config to disk, with content:\n")
fmt.Printf("Error writing config file %s: %v\n", j.ConfigPath, err) fmt.Printf(string(marshaled))
os.Exit(1)
if os.WriteFile(j.ConfigPath, []byte(marshaled), 0644); err != nil {
fmt.Printf("Error writing config file %s: %v\n", j.ConfigPath, err)
os.Exit(1)
}
} }
} }
} }
} }
func Execute() { func Execute() {
if err := rootCmd.Execute(); err != nil { if err := rootCmd.Execute(); err != nil {
fmt.Fprintln(os.Stderr, err) fmt.Fprintln(os.Stderr, err)

View File

@ -4,6 +4,7 @@ import (
"os" "os"
"fmt" "fmt"
"net" "net"
"time"
"errors" "errors"
"regexp" "regexp"
"reflect" "reflect"
@ -945,7 +946,7 @@ func setupVnetInterfaceJailSide(jail *Jail, hsepair string) error {
// Get bridge MTU // Get bridge MTU
mtu, err := gJailHost.GetBridgeMTU(bridge) mtu, err := gJailHost.GetBridgeMTU(bridge)
if err != nil { if err != nil {
return fmt.Errorf("Error getting bridge mtu: %v\n", err) return fmt.Errorf("Error getting bridge %s mtu: %v\n", bridge, err)
} }
cmd = fmt.Sprintf("/usr/sbin/jexec %d ifconfig %s mtu %d", jail.JID, jsepair, mtu) cmd = fmt.Sprintf("/usr/sbin/jexec %d ifconfig %s mtu %d", jail.JID, jsepair, mtu)
@ -1309,7 +1310,7 @@ func StartJail(args []string) {
} }
// Synchronize jail config to disk // Synchronize jail config to disk
WriteConfigToDisk(false) WriteConfigToDisk(cj.Name, false, false)
start_cmd := fmt.Sprintf("/usr/sbin/jail -f /var/run/jail.%s.conf -c", cj.InternalName) start_cmd := fmt.Sprintf("/usr/sbin/jail -f /var/run/jail.%s.conf -c", cj.InternalName)
@ -1455,6 +1456,11 @@ func StartJail(args []string) {
// TODO: Handle dhcp // TODO: Handle dhcp
// TODO: Apply rctl // TODO: Apply rctl
// Update last_started
dt := time.Now()
curDate := fmt.Sprintf("%s", dt.Format("2006-01-02 15:04:05"))
fmt.Sprintf(cj.Config.Last_started, curDate)
WriteConfigToDisk(cj.Name, false, true)
/* /*

View File

@ -228,14 +228,24 @@ func StopJail(args []string) {
fmt.Printf("Error getting jail: %s\n", err) fmt.Printf("Error getting jail: %s\n", err)
continue continue
} }
if cj.Running == false { if cj.Running == false {
fmt.Printf("Jail %s is not running!\n", cj.Name) fmt.Printf("Jail %s is not running!\n", cj.Name)
continue continue
} }
fmt.Printf("> Stopping jail %s\n", a) fmt.Printf("> Stopping jail %s\n", a)
// Get current version to update config.json
cvers, err := executeCommandInJail(cj, "/bin/freebsd-version")
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
return
}
cvers = strings.TrimRight(cvers, "\n")
fmt.Sprintf(cj.Config.Release, cvers)
cj.ConfigUpdated = true
out, err := executeCommand(fmt.Sprintf("rctl jail:%s", cj.InternalName)) out, err := executeCommand(fmt.Sprintf("rctl jail:%s", cj.InternalName))
if err == nil && len(out) > 0 { if err == nil && len(out) > 0 {
fmt.Printf(" > Remove RCTL rules:\n") fmt.Printf(" > Remove RCTL rules:\n")
@ -399,5 +409,8 @@ func StopJail(args []string) {
} }
} }
} }
WriteConfigToDisk(cj.Name, false, true)
} }
} }

157
cmd/update.go Normal file
View File

@ -0,0 +1,157 @@
package cmd
import (
"os"
"fmt"
//"log"
"time"
)
const (
fbsdUpdateConfig = `
# $FreeBSD: releng/12.2/usr.sbin/freebsd-update/freebsd-update.conf 337338 2018-08-04 22:25:41Z brd $
# Trusted keyprint. Changing this is a Bad Idea unless you've received
# a PGP-signed email from <security-officer@FreeBSD.org> telling you to
# change it and explaining why.
KeyPrint 800651ef4b4c71c27e60786d7b487188970f4b4169cc055784e21eb71d410cc5
# Server or server pool from which to fetch updates. You can change
# this to point at a specific server if you want, but in most cases
# using a "nearby" server won't provide a measurable improvement in
# performance.
ServerName update.FreeBSD.org
# Components of the base system which should be kept updated.
Components world
# Example for updating the userland and the kernel source code only:
# Components src/base src/sys world
# Paths which start with anything matching an entry in an IgnorePaths
# statement will be ignored.
IgnorePaths
# Paths which start with anything matching an entry in an IDSIgnorePaths
# statement will be ignored by "freebsd-update IDS".
IDSIgnorePaths /usr/share/man/cat
IDSIgnorePaths /usr/share/man/whatis
IDSIgnorePaths /var/db/locate.database
IDSIgnorePaths /var/log
# Paths which start with anything matching an entry in an UpdateIfUnmodified
# statement will only be updated if the contents of the file have not been
# modified by the user (unless changes are merged; see below).
UpdateIfUnmodified /etc/ /var/ /root/ /.cshrc /.profile
# When upgrading to a new FreeBSD release, files which match MergeChanges
# will have any local changes merged into the version from the new release.
MergeChanges /etc/
### Default configuration options:
# Directory in which to store downloaded updates and temporary
# files used by FreeBSD Update.
# WorkDir /var/db/freebsd-update
# Destination to send output of "freebsd-update cron" if an error
# occurs or updates have been downloaded.
# MailTo root
# Is FreeBSD Update allowed to create new files?
# AllowAdd yes
# Is FreeBSD Update allowed to delete files?
# AllowDelete yes
# If the user has modified file ownership, permissions, or flags, should
# FreeBSD Update retain this modified metadata when installing a new version
# of that file?
# KeepModifiedMetadata yes
# When upgrading between releases, should the list of Components be
# read strictly (StrictComponents yes) or merely as a list of components
# which *might* be installed of which FreeBSD Update should figure out
# which actually are installed and upgrade those (StrictComponents no)?
# StrictComponents no
# When installing a new kernel perform a backup of the old one first
# so it is possible to boot the old kernel in case of problems.
# BackupKernel yes
# If BackupKernel is enabled, the backup kernel is saved to this
# directory.
# BackupKernelDir /boot/kernel.old
# When backing up a kernel also back up debug symbol files?
# BackupKernelSymbolFiles no
# Create a new boot environment when installing patches
# CreateBootEnv yes
`
)
// Internal usage only
func updateJail(jail *Jail) error {
// Create default config as temporary file
cfgFile, err := os.CreateTemp("", "gocage-jail-update-")
if err != nil {
return err
}
cfgFile.Write([]byte(fbsdUpdateConfig))
defer cfgFile.Close()
//defer os.Remove(cfgFile.Name())
cmd := fmt.Sprintf("/usr/sbin/freebsd-update --not-running-from-cron -f %s -b %s --currently-running %s fetch install",
cfgFile.Name(), jail.RootPath, jail.Config.Release)
fmt.Printf("DEBUG: Prepare to execute \"%s\"\n", cmd)
err = executeCommandWithOutputToStdout(cmd)
if err != nil {
return err
}
// Get and write new release into config.json
return nil
}
func UpdateJail(args []string) {
// Current jail were stopping
var cj *Jail
var err error
for _, a := range args {
// Check if jail exist and is distinctly named
cj, err = getJailFromArray(a, gJails)
if err != nil {
fmt.Printf("Error getting jail: %s\n", err)
continue
}
fmt.Printf(" > Snapshot jail %s\n", cj.Name)
// Set snapshot name
dt := time.Now()
curDate := fmt.Sprintf("%s", dt.Format("2006-01-02_15-04-05"))
gSnapshotName = fmt.Sprintf("goc_update_%s_%s", cj.Config.Release, curDate)
err := createJailSnapshot(*cj)
if err != nil {
fmt.Printf(" > Snapshot jail %s: ERROR: %s\n", cj.Name, err.Error())
return
}
fmt.Printf(" > Snapshot jail %s: OK\n", cj.Name)
fmt.Printf(" > Update jail %s\n", cj.Name)
err = updateJail(cj)
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
} else {
fmt.Printf(" > Update jail %s: OK\n", cj.Name)
}
}
}

View File

@ -225,6 +225,78 @@ func executeCommand(cmdline string) (string, error) {
return string(out), err return string(out), err
} }
// Executed command outputs to stdout in realtime
func executeCommandWithOutputToStdout(cmdline string) (error) {
var cmd []string
var err error
if gUseSudo {
cmd = append(cmd, "sudo")
}
var word string
var in_escaped bool
// Split by words, or " enclosed words
for i, c := range (cmdline) {
if string(c) == "\"" {
if in_escaped {
// This is the closing "
cmd = append(cmd, word)
in_escaped = false
} else {
in_escaped = true
}
continue
}
if string(c) == " " {
if in_escaped {
word = word + string(c)
continue
} else {
cmd = append(cmd, word)
word = ""
continue
}
}
if i == (len(cmdline) - 1) {
word = word + string(c)
cmd = append(cmd, word)
break
}
// else
word = word + string(c)
}
var execHandle *exec.Cmd
if len(cmd) > 1 {
execHandle = exec.Command(cmd[0], cmd[1:]...)
} else {
execHandle = exec.Command(cmd[0])
}
stdout, err := execHandle.StdoutPipe()
if err != nil {
return err
}
execHandle.Start()
buf := bufio.NewReader(stdout)
for {
line, _, err := buf.ReadLine()
if err != nil {
if err.Error() == "EOF" {
return nil
} else {
return err
}
}
fmt.Println(string(line))
}
return fmt.Errorf("Unknown error: you shouldn't be here!\n")
}
func executeCommandInJail(jail *Jail, cmdline string) (string, error) { func executeCommandInJail(jail *Jail, cmdline string) (string, error) {
var cmd []string var cmd []string
@ -677,7 +749,7 @@ func setJailConfigUpdated(jail *Jail) error {
return err return err
} }
j.ConfigUpdated = true j.ConfigUpdated = true
return nil return nil
} }