13 Commits

13 changed files with 543 additions and 246 deletions

View File

@ -1,3 +1,4 @@
v.0.33b : Support jailing datasets on differents pools : jail_zfs_dataset now have to include the pool name v.0.33b : Support jailing datasets on differents pools : jail_zfs_dataset now have to include the pool name
v.0.33c : Parallelize start/stop of jails with same priority v.0.33c : Parallelize start/stop of jails with same priority
v.0.34 : jail name can be shortened v.0.34 : jail name can be shortened
v.0.35 : One can now "gocage destroy"

View File

@ -126,6 +126,17 @@ Stop jails
`gocage stop test` `gocage stop test`
Update jails
----------
To update jail patch version, use gocage update :
`gocage update test`
Delete jails
----------
`gocage destroy test`
Multi datastore Multi datastore
---------- ----------
A datastore is a ZFS dataset mounted. It should be declared in gocage.conf.yml, specifying its ZFS mountpoint : A datastore is a ZFS dataset mounted. It should be declared in gocage.conf.yml, specifying its ZFS mountpoint :
@ -206,9 +217,7 @@ gocage fetch -r 12.3 -o iocage --from file:/iocage/download
TODO TODO
---------- ----------
gocage update
gocage upgrade gocage upgrade
gocage create gocage create
gocage destroy
gocage init gocage init
create default pool with defaults.json create default pool with defaults.json

View File

@ -33,7 +33,6 @@ func shellJail(jail *Jail) error {
jid := strconv.Itoa(jail.JID) jid := strconv.Itoa(jail.JID)
//err := syscall.Exec("/usr/sbin/jexec", []string{"jexec", jid, "/bin/csh"}, os.Environ())
err := syscall.Exec("/usr/sbin/jexec", []string{"jexec", jid, "login", "-f", "root"}, os.Environ()) err := syscall.Exec("/usr/sbin/jexec", []string{"jexec", jid, "login", "-f", "root"}, os.Environ())
// We should never get here, as syscall.Exec replace the gocage binary execution with jexec // We should never get here, as syscall.Exec replace the gocage binary execution with jexec

57
cmd/destroy.go Normal file
View File

@ -0,0 +1,57 @@
package cmd
import (
"fmt"
//"log"
//"errors"
"strings"
)
func DestroyJails(args []string) {
for _, a := range args {
cj, err := getJailFromArray(a, gJails)
if err != nil {
fmt.Printf("Error getting jail: %s\n", err)
return
}
if cj.Running == true {
fmt.Printf("Jail %s is running\n", cj.Name)
if gForce == false {
var answer string
fmt.Printf("Stop jail and delete? (y/n) ")
fmt.Scanln(&answer)
if false == strings.EqualFold(answer, "y") {
return
}
}
fmt.Printf("Stopping jail %s\n", cj.Name)
StopJail([]string{fmt.Sprintf("%s/%s", cj.Datastore, cj.Name)})
}
// Get root and config datasets, then destroy
dsRootName, err := zfsGetDatasetByMountpoint(cj.RootPath)
if err != nil {
fmt.Printf("Error getting root dataset: %s\n", err)
return
}
//fmt.Printf("DEBUG: Prepare to zfs destroy %s\n", dsRootName)
if err = zfsDestroy(dsRootName); err != nil {
fmt.Printf("Error deleting root dataset: %s\n", err)
return
}
dsConfName, err := zfsGetDatasetByMountpoint(cj.ConfigPath)
if err != nil {
fmt.Printf("Error getting config dataset: %s\n", err)
return
}
//fmt.Printf("DEBUG: Prepare to zfs destroy %s\n", dsConfName)
if err = zfsDestroy(dsConfName); err != nil {
fmt.Printf("Error deleting config dataset: %s\n", err)
return
}
//TODO: Delete jail named directory
}
}

View File

@ -61,7 +61,7 @@ func fetchRelease(release string, proto string, arch string, datastore string, f
} }
if false == exist { if false == exist {
// Then create dataset // Then create dataset
if err := createZfsDataset(downloadDsName, downloadDsMountPoint, "lz4"); err != nil { if err := zfsCreateDataset(downloadDsName, downloadDsMountPoint, "lz4"); err != nil {
return fmt.Errorf("Error creating dataset %s: %v\n", downloadDsName, err) return fmt.Errorf("Error creating dataset %s: %v\n", downloadDsName, err)
} }
} }
@ -75,7 +75,7 @@ func fetchRelease(release string, proto string, arch string, datastore string, f
} }
if false == exist { if false == exist {
// Then create dataset // Then create dataset
if err := createZfsDataset(thisDownloadDsName, thisDownloadDsMountPoint, "lz4"); err != nil { if err := zfsCreateDataset(thisDownloadDsName, thisDownloadDsMountPoint, "lz4"); err != nil {
return fmt.Errorf("Error creating dataset %s: %v\n", thisDownloadDsName, err) return fmt.Errorf("Error creating dataset %s: %v\n", thisDownloadDsName, err)
} }
} }
@ -147,7 +147,7 @@ func extractRelease(release string, datastore string) {
} }
if false == exist { if false == exist {
// Then create dataset // Then create dataset
if err := createZfsDataset(releaseDsName, releaseDsMountPoint, "lz4"); err != nil { if err := zfsCreateDataset(releaseDsName, releaseDsMountPoint, "lz4"); err != nil {
fmt.Printf("Error creating dataset %s: %v\n", releaseDsName, err) fmt.Printf("Error creating dataset %s: %v\n", releaseDsName, err)
return return
} }
@ -163,7 +163,7 @@ func extractRelease(release string, datastore string) {
} }
if false == exist { if false == exist {
// Then create dataset // Then create dataset
if err := createZfsDataset(thisReleaseDsName, thisReleaseDsMountPoint, "lz4"); err != nil { if err := zfsCreateDataset(thisReleaseDsName, thisReleaseDsMountPoint, "lz4"); err != nil {
fmt.Printf("Error creating dataset %s: %v\n", thisReleaseDsName, err) fmt.Printf("Error creating dataset %s: %v\n", thisReleaseDsName, err)
return return
} }
@ -179,7 +179,7 @@ func extractRelease(release string, datastore string) {
} }
if false == exist { if false == exist {
// Then create dataset // Then create dataset
if err := createZfsDataset(thisReleaseRootDsName, thisReleaseRootDsMountPoint, "lz4"); err != nil { if err := zfsCreateDataset(thisReleaseRootDsName, thisReleaseRootDsMountPoint, "lz4"); err != nil {
fmt.Printf("Error creating dataset %s: %v\n", thisReleaseRootDsName, err) fmt.Printf("Error creating dataset %s: %v\n", thisReleaseRootDsName, err)
return return
} }

View File

@ -0,0 +1,85 @@
package cmd
const (
fbsdUpdateConfig = `
# $FreeBSD$
# 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 /iocage/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 yes
# 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 no
# 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 no
`
)

View File

@ -118,6 +118,7 @@ func SetJailProperties(args []string) {
gJails[i].ConfigUpdated = true gJails[i].ConfigUpdated = true
} }
} }
writeConfigToDisk(&gJails[i], false)
} }
} }
} }

View File

@ -6,7 +6,6 @@ import (
"sync" "sync"
"strings" "strings"
"io/ioutil" "io/ioutil"
"encoding/json"
"github.com/spf13/cobra" "github.com/spf13/cobra"
"github.com/spf13/viper" "github.com/spf13/viper"
@ -15,7 +14,7 @@ import (
) )
const ( const (
gVersion = "0.34" gVersion = "0.36c"
// TODO : Get from $jail_zpool/defaults.json // TODO : Get from $jail_zpool/defaults.json
MIN_DYN_DEVFS_RULESET = 1000 MIN_DYN_DEVFS_RULESET = 1000
@ -55,6 +54,7 @@ var (
gFetchRelease string gFetchRelease string
gFetchIntoDS string gFetchIntoDS string
gFetchFrom string gFetchFrom string
gUpgradeRelease string
gMdevfs sync.Mutex gMdevfs sync.Mutex
@ -100,7 +100,7 @@ ex: gocage list srv-db srv-web`,
}, },
} }
/* destroyCmd = &cobra.Command{ destroyCmd = &cobra.Command{
Use: "destroy", Use: "destroy",
Short: "destroy jails", Short: "destroy jails",
Long: `Destroy jail filesystem, snapshots and configuration file.`, Long: `Destroy jail filesystem, snapshots and configuration file.`,
@ -109,7 +109,7 @@ ex: gocage list srv-db srv-web`,
DestroyJails(args) DestroyJails(args)
}, },
} }
*/
stopCmd = &cobra.Command{ stopCmd = &cobra.Command{
Use: "stop", Use: "stop",
Short: "stop jail", Short: "stop jail",
@ -136,12 +136,9 @@ ex: gocage list srv-db srv-web`,
} else { } else {
StartJail(args) StartJail(args)
} }
WriteConfigToDisk("", false, false)
}, },
} }
restartCmd = &cobra.Command{ restartCmd = &cobra.Command{
Use: "restart", Use: "restart",
Short: "restart jail", Short: "restart jail",
@ -150,7 +147,6 @@ ex: gocage list srv-db srv-web`,
ListJails(args, false) ListJails(args, false)
StopJail(args) StopJail(args)
StartJail(args) StartJail(args)
WriteConfigToDisk("", false, false)
}, },
} }
@ -173,7 +169,6 @@ 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, false)
}, },
} }
@ -255,7 +250,6 @@ You can specify multiple jails.`,
// Load inventory // Load inventory
ListJails(args, false) ListJails(args, false)
MigrateJail(args) MigrateJail(args)
WriteConfigToDisk("", false, false)
}, },
} }
@ -305,7 +299,7 @@ You can specify multiple datastores.`,
}, },
} }
UpdateCmd = &cobra.Command{ updateCmd = &cobra.Command{
Use: "update", Use: "update",
Short: "Update FreeBSD release", Short: "Update FreeBSD release",
Run: func(cmd *cobra.Command, args []string) { Run: func(cmd *cobra.Command, args []string) {
@ -314,6 +308,15 @@ You can specify multiple datastores.`,
}, },
} }
upgradeCmd = &cobra.Command{
Use: "upgrade",
Short: "Upgrade FreeBSD release",
Run: func(cmd *cobra.Command, args []string) {
ListJails(args, false)
UpgradeJail(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",
@ -343,7 +346,7 @@ func init() {
listCmd.Flags().StringVarP(&gFilterJails, "filter", "f", "none", "Only display jails with these values. Ex: \"gocage list -f Config.Boot=1\" will only list started on boot jails") listCmd.Flags().StringVarP(&gFilterJails, "filter", "f", "none", "Only display jails with these values. Ex: \"gocage list -f Config.Boot=1\" will only list started on boot jails")
listCmd.Flags().StringVarP(&gSortJailFields, "sort", "s", "none", "Display jails sorted by field values. Ex: \"gocage list -s +Name,-Config.Priority\" will sort jails by their decreasing name, then increasing start priority. 3 critera max supported.") listCmd.Flags().StringVarP(&gSortJailFields, "sort", "s", "none", "Display jails sorted by field values. Ex: \"gocage list -s +Name,-Config.Priority\" will sort jails by their decreasing name, then increasing start priority. 3 critera max supported.")
// destroyCmd.Flags().BoolVarP(&gForce, "force", "f", false, "Force stop jail if running") destroyCmd.Flags().BoolVarP(&gForce, "force", "f", false, "Force stop jail if running")
snapshotListCmd.Flags().StringVarP(&gDisplaySColumns, "outcol", "o", "Jailname,Name,Creation,Referenced,Used", "Show these columns in output") snapshotListCmd.Flags().StringVarP(&gDisplaySColumns, "outcol", "o", "Jailname,Name,Creation,Referenced,Used", "Show these columns in output")
snapshotListCmd.Flags().BoolVarP(&gNoSnapLineSep, "nolinesep", "l", false, "Do not display line separator between snapshots") snapshotListCmd.Flags().BoolVarP(&gNoSnapLineSep, "nolinesep", "l", false, "Do not display line separator between snapshots")
@ -373,6 +376,8 @@ func init() {
fetchCmd.MarkFlagRequired("release") fetchCmd.MarkFlagRequired("release")
fetchCmd.MarkFlagRequired("datastore") fetchCmd.MarkFlagRequired("datastore")
upgradeCmd.Flags().StringVarP(&gUpgradeRelease, "release", "r", "", "Release to upgrade to (e.g.: \"13.1-RELEASE\"")
upgradeCmd.MarkFlagRequired("release")
// Now declare commands // Now declare commands
rootCmd.AddCommand(versionCmd) rootCmd.AddCommand(versionCmd)
@ -381,7 +386,7 @@ func init() {
rootCmd.AddCommand(stopCmd) rootCmd.AddCommand(stopCmd)
rootCmd.AddCommand(startCmd) rootCmd.AddCommand(startCmd)
rootCmd.AddCommand(restartCmd) rootCmd.AddCommand(restartCmd)
// rootCmd.AddCommand(destroyCmd) rootCmd.AddCommand(destroyCmd)
rootCmd.AddCommand(shellCmd) rootCmd.AddCommand(shellCmd)
rootCmd.AddCommand(getCmd) rootCmd.AddCommand(getCmd)
rootCmd.AddCommand(setCmd) rootCmd.AddCommand(setCmd)
@ -389,7 +394,8 @@ 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(updateCmd)
rootCmd.AddCommand(upgradeCmd)
rootCmd.AddCommand(testCmd) rootCmd.AddCommand(testCmd)
@ -472,66 +478,6 @@ func initConfig() {
} }
} }
/********************************************************************************
* 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
* 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
* start)
*******************************************************************************/
func WriteConfigToDisk(jailName string, changeauto bool, forceWrite bool) {
for _, j := range gJails {
if len(jailName) > 0 && j.Name == jailName || len(jailName) == 0 {
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
jc := j.Config
if changeauto == false {
// Overwrite "auto" properties
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 {
panic(err)
}
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, "", " ")
if err != nil {
fmt.Printf("ERROR marshaling config: %s\n", err.Error())
}
//fmt.Printf("DEBUG: Will write config to disk, with content:\n")
//fmt.Printf(string(marshaled))
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 {

View File

@ -1176,7 +1176,7 @@ func StartJail(args []string) {
continue continue
} }
fmt.Printf("> Starting jail %s\n", a) fmt.Printf("> Starting jail %s\n", cj.Name)
// Set InternalName as it is used by some of these // Set InternalName as it is used by some of these
cj.InternalName = fmt.Sprintf("ioc-%s", cj.Name) cj.InternalName = fmt.Sprintf("ioc-%s", cj.Name)
@ -1365,7 +1365,7 @@ func StartJail(args []string) {
} }
// Synchronize jail config to disk // Synchronize jail config to disk
WriteConfigToDisk(cj.Name, false, false) writeConfigToDisk(cj, 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)
@ -1512,10 +1512,11 @@ func StartJail(args []string) {
// TODO: Apply rctl // TODO: Apply rctl
// Update last_started // Update last_started
// 23/07/2023 : This is not working, when writing to disk the old value is used
dt := time.Now() dt := time.Now()
curDate := fmt.Sprintf("%s", dt.Format("2006-01-02 15:04:05")) curDate := fmt.Sprintf("%s", dt.Format("2006-01-02 15:04:05"))
fmt.Sprintf(cj.Config.Last_started, curDate) cj.Config.Last_started = curDate
WriteConfigToDisk(cj.Name, false, true) writeConfigToDisk(cj, false)
/* /*

View File

@ -281,25 +281,10 @@ func StopJail(args []string) {
continue continue
} }
fmt.Printf("> Stopping jail %s\n", a) fmt.Printf("> Stopping jail %s\n", cj.Name)
// Get current version to update config.json // Get and write new release into config.json
cvers, err := executeCommandInJail(cj, "/bin/freebsd-version") updateVersion(cj)
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
return
}
cvers = strings.TrimRight(cvers, "\n")
//fmt.Sprintf(cj.Config.Release, cvers)
//cj.Config.Release = cvers
//cj.ConfigUpdated = true
// This is working in this context, but value is not available in WriteConfigToDisk context :/
setStructFieldValue(cj, "Config.Release", cvers)
fmt.Printf("DEBUG: release was set, now is : %s\n", cj.Config.Release)
// We need to get the real Config object, not a copy of it
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 {
@ -464,9 +449,7 @@ func StopJail(args []string) {
} }
} }
} }
writeConfigToDisk(cj, false)
fmt.Printf("DEBUG: release = %s\n", cj.Config.Release)
WriteConfigToDisk(cj.Name, false, true)
} }
} }

View File

@ -7,93 +7,9 @@ import (
"time" "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 // Internal usage only
func updateJail(jail *Jail) error { func updateJail(jail *Jail) error {
// Create default config as temporary file // Create default config as temporary file
cfgFile, err := os.CreateTemp("", "gocage-jail-update-") cfgFile, err := os.CreateTemp("", "gocage-jail-update-")
if err != nil { if err != nil {
@ -103,12 +19,21 @@ func updateJail(jail *Jail) error {
cfgFile.Write([]byte(fbsdUpdateConfig)) cfgFile.Write([]byte(fbsdUpdateConfig))
defer cfgFile.Close() defer cfgFile.Close()
//defer os.Remove(cfgFile.Name()) defer os.Remove(cfgFile.Name())
// Folder containing update/uipgrade temporary files. Common so we save bandwith when upgrading multiple jails
// TODO: Variabilize /iocage/freebsd-update
_, err = os.Stat("/iocage/freebsd-update")
if os.IsNotExist(err) {
if err := os.Mkdir("/iocage/freebsd-update", 0755); err != nil {
return err
}
}
cmd := fmt.Sprintf("/usr/sbin/freebsd-update --not-running-from-cron -f %s -b %s --currently-running %s fetch install", 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) cfgFile.Name(), jail.RootPath, jail.Config.Release)
fmt.Printf("DEBUG: Prepare to execute \"%s\"\n", cmd) //fmt.Printf("DEBUG: Prepare to execute \"%s\"\n", cmd)
err = executeCommandWithOutputToStdout(cmd) err = executeCommandWithOutputToStdout(cmd)
if err != nil { if err != nil {
@ -116,7 +41,7 @@ func updateJail(jail *Jail) error {
} }
// Get and write new release into config.json // Get and write new release into config.json
updateVersion(jail)
return nil return nil
} }

125
cmd/upgrade.go Normal file
View File

@ -0,0 +1,125 @@
package cmd
import (
"os"
"fmt"
//"log"
"time"
"strings"
)
// Internal usage only
func upgradeJail(jail *Jail, version string) error {
// Create default config as temporary file
cfgFile, err := os.CreateTemp("", "gocage-jail-upgrade-")
if err != nil {
return err
}
cfgFile.Write([]byte(fbsdUpdateConfig))
defer cfgFile.Close()
defer os.Remove(cfgFile.Name())
// Folder containing update/uipgrade temporary files. Common so we save bandwith when upgrading multiple jails
// TODO: Variabilize /iocage/freebsd-update
_, err = os.Stat("/iocage/freebsd-update")
if os.IsNotExist(err) {
if err := os.Mkdir("/iocage/freebsd-update", 0755); err != nil {
return err
}
}
// Get current version. Won't work on stopped jail.
fbsdvers, err := executeCommandInJail(jail, "/bin/freebsd-version")
if err != nil {
fmt.Printf("ERROR executeCommandInJail: %s\n", err.Error())
return err
}
fbsdvers = strings.TrimRight(fbsdvers, "\n")
//fbsdvers := jail.Config.Release
cmd := fmt.Sprintf("/usr/sbin/freebsd-update -f %s -b %s --currently-running %s -r %s upgrade",
cfgFile.Name(), jail.RootPath, fbsdvers, version)
//fmt.Printf("DEBUG: Prepare to execute \"%s\"\n", cmd)
// Need to give user control, bc there could be merge edit needs
err = executeCommandWithStdinStdoutStderr(cmd)
if err != nil {
return err
}
cmd = fmt.Sprintf("/usr/sbin/freebsd-update -f %s -b %s --currently-running %s -r %s install",
cfgFile.Name(), jail.RootPath, fbsdvers, version)
//fmt.Printf("DEBUG: Prepare to execute \"%s\"\n", cmd)
err = executeCommandWithStdinStdoutStderr(cmd)
if err != nil {
return err
}
cmd = fmt.Sprintf("/usr/sbin/freebsd-update -f %s -b %s --currently-running %s -r %s install",
cfgFile.Name(), jail.RootPath, fbsdvers, version)
//fmt.Printf("DEBUG: Prepare to execute \"%s\"\n", cmd)
err = executeCommandWithStdinStdoutStderr(cmd)
if err != nil {
return err
}
cmd = fmt.Sprintf("/usr/local/sbin/pkg-static -j %d install -q -f -y pkg", jail.JID)
err = executeCommandWithStdinStdoutStderr(cmd)
if err != nil {
return err
}
// Get and write new release into config.json
updateVersion(jail)
return nil
}
func UpgradeJail(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
}
if cj.Running == false {
fmt.Printf("Error: jail must be running for upgrade.\n")
return
}
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_upgrade_%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(" > Upgrade jail %s to %s\n", cj.Name, gUpgradeRelease)
err = upgradeJail(cj, gUpgradeRelease)
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
} else {
fmt.Printf(" > Upgrade jail %s: OK\n", cj.Name)
}
}
}

View File

@ -13,6 +13,7 @@ import (
"strconv" "strconv"
"strings" "strings"
"io/ioutil" "io/ioutil"
"encoding/json"
"github.com/google/shlex" "github.com/google/shlex"
"github.com/c2h5oh/datasize" "github.com/c2h5oh/datasize"
log "github.com/sirupsen/logrus" log "github.com/sirupsen/logrus"
@ -365,9 +366,83 @@ func executeCommandWithOutputToStdout(cmdline string) (error) {
return fmt.Errorf("Unknown error: you shouldn't be here!\n") return fmt.Errorf("Unknown error: you shouldn't be here!\n")
} }
/* Execute command plugging stdin and stdout to those of the running command.
* Blocking while the command run
*/
func executeCommandWithStdinStdoutStderr(cmdline string) (error) {
var cmd []string
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 command *exec.Cmd
if len(cmd) > 1 {
command = exec.Command(cmd[0], cmd[1:]...)
} else {
command = exec.Command(cmd[0])
}
// Get environment
command.Env = os.Environ()
// Connect command to current stdin/out/err
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
if err := command.Start(); err != nil {
return err
}
err := command.Wait()
return err
}
func executeCommandInJail(jail *Jail, cmdline string) (string, error) { func executeCommandInJail(jail *Jail, cmdline string) (string, error) {
var cmd []string var cmd []string
// We can't execute on non-running jail
if jail.Running == false {
return "", errors.New("Can't execute command on stopped jail")
}
if gUseSudo { if gUseSudo {
cmd = append(cmd, "sudo") cmd = append(cmd, "sudo")
} }
@ -415,6 +490,10 @@ func executeCommandInJail(jail *Jail, cmdline string) (string, error) {
word = word + string(c) word = word + string(c)
} }
if gDebug {
fmt.Printf("DEBUG: executeCommandInJail: prepare to execute \"%s\"\n", cmd)
}
out, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput() out, err := exec.Command(cmd[0], cmd[1:]...).CombinedOutput()
return string(out), err return string(out), err
@ -568,7 +647,7 @@ func doZfsDatasetExist(dataset string) (bool, error) {
} }
// Create ZFS dataset. mountpoint can be "none", then the dataset won't be mounted // Create ZFS dataset. mountpoint can be "none", then the dataset won't be mounted
func createZfsDataset(dataset, mountpoint, compression string) error { func zfsCreateDataset(dataset, mountpoint, compression string) error {
cmd := fmt.Sprintf("zfs create -o mountpoint=%s -o compression=%s %s", mountpoint, compression, dataset) cmd := fmt.Sprintf("zfs create -o mountpoint=%s -o compression=%s %s", mountpoint, compression, dataset)
out, err := executeCommand(cmd) out, err := executeCommand(cmd)
if err != nil { if err != nil {
@ -576,6 +655,26 @@ func createZfsDataset(dataset, mountpoint, compression string) error {
} }
return nil return nil
} }
// Return dataset name for a given mountpoint
func zfsGetDatasetByMountpoint(mountpoint string) (string, error) {
cmd := fmt.Sprintf("zfs list -p -r -H -o name %s", mountpoint)
out, err := executeCommand(cmd)
if err != nil {
return "", errors.New(fmt.Sprintf("%v; command returned \"%s\"", err, out))
}
return strings.TrimSuffix(out, "\n"), nil
}
// Delete a ZFS Dataset by name
func zfsDestroy(dataset string) error {
cmd := fmt.Sprintf("zfs destroy -r %s", dataset)
out, err := executeCommand(cmd)
if err != nil {
return errors.New(fmt.Sprintf("%v; command returned \"%s\"", err, out))
}
return nil
}
/***************************************************************************** /*****************************************************************************
* *
@ -682,6 +781,33 @@ func copyDevfsRuleset(ruleset int, srcrs int) error {
return nil return nil
} }
/********************************************************************************
* Add a rule to specified ruleset
* Ex.: addDevfsRuleToRuleset("path bpf* unhide", 1002)
*******************************************************************************/
func addDevfsRuleToRuleset(rule string, ruleset int) error {
// TODO: Check if rule not already enabled. We will need to recurse into includes.
// Get last rule index
rules := getDevfsRuleset(ruleset)
if len(rules) == 0 {
fmt.Printf("Error listing ruleset %d\n", ruleset)
return errors.New(fmt.Sprintf("Error listing rueset %d\n", ruleset))
}
f := strings.Fields(rules[(len(rules)-1)])
//fmt.Printf("Dernier index du ruleset %d: %s\n", ruleset, f[0])
index, _ := strconv.Atoi(f[0])
index += 100
cmd := fmt.Sprintf("/sbin/devfs rule -s %d add %d %s", ruleset, index, rule)
out, err := executeCommand(cmd)
if err != nil {
return errors.New(fmt.Sprintf("Error adding rule \"%s\" to ruleset %d: %s", rule, ruleset, out))
}
return nil
}
/******************************************************************************** /********************************************************************************
* Returns value of parameter as read in /var/run/jail.$InternalName.conf * Returns value of parameter as read in /var/run/jail.$InternalName.conf
* Directives without value will return "true" if found * Directives without value will return "true" if found
@ -710,32 +836,6 @@ func getValueFromRunningConfig(jname string, param string) (string, error) {
return "", fmt.Errorf("Parameter not found: %s", param) return "", fmt.Errorf("Parameter not found: %s", param)
} }
/********************************************************************************
* Add a rule to specified ruleset
* Ex.: addDevfsRuleToRuleset("path bpf* unhide", 1002)
*******************************************************************************/
func addDevfsRuleToRuleset(rule string, ruleset int) error {
// TODO: Check if rule not already enabled. We will need to recurse into includes.
// Get last rule index
rules := getDevfsRuleset(ruleset)
if len(rules) == 0 {
fmt.Printf("Error listing ruleset %d\n", ruleset)
return errors.New(fmt.Sprintf("Error listing rueset %d\n", ruleset))
}
f := strings.Fields(rules[(len(rules)-1)])
//fmt.Printf("Dernier index du ruleset %d: %s\n", ruleset, f[0])
index, _ := strconv.Atoi(f[0])
index += 100
cmd := fmt.Sprintf("/sbin/devfs rule -s %d add %d %s", ruleset, index, rule)
out, err := executeCommand(cmd)
if err != nil {
return errors.New(fmt.Sprintf("Error adding rule \"%s\" to ruleset %d: %s", rule, ruleset, out))
}
return nil
}
/****************************************************************************** /******************************************************************************
@ -822,6 +922,71 @@ func setJailConfigUpdated(jail *Jail) error {
return nil return nil
} }
func updateVersion(jail *Jail) error {
cvers, err := executeCommandInJail(jail, "/bin/freebsd-version")
if err != nil {
fmt.Printf("ERROR: %s\n", err.Error())
return err
}
cvers = strings.TrimRight(cvers, "\n")
jail.Config.Release = cvers
writeConfigToDisk(jail, false)
return nil
}
/********************************************************************************
* 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
* 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
* start)
*******************************************************************************/
func writeConfigToDisk(j *Jail, changeauto bool) {
// we will manipulate properties so get a copy
jc := j.Config
if changeauto == false {
// Overwrite "auto" properties
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 {
panic(err)
}
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, "", " ")
if err != nil {
fmt.Printf("ERROR marshaling config: %s\n", err.Error())
}
//fmt.Printf("DEBUG: Will write config to disk, with content:\n")
//fmt.Printf(string(marshaled))
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)
}
}
/****************************************************************************** /******************************************************************************
* Return the quantity of jails with the name passed as parameter * Return the quantity of jails with the name passed as parameter
*****************************************************************************/ *****************************************************************************/