WIP on start, go fmt on *

This commit is contained in:
yo 2022-04-24 16:49:54 +02:00
parent dbd9153513
commit 43f26d099f
12 changed files with 1498 additions and 1169 deletions

View File

@ -2,8 +2,8 @@ package cmd
import (
"fmt"
"net"
"golang.org/x/net/route"
"net"
)
var defaultRoute4 = [4]byte{0, 0, 0, 0}
@ -83,7 +83,6 @@ func (jh *JailHost) InitNetworkProperties() {
}
}
func (jh *JailHost) GetDefaultInterface() string {
if len(jh.default_interface) == 0 {
jh.InitNetworkProperties()
@ -91,7 +90,6 @@ func (jh *JailHost) GetDefaultInterface() string {
return jh.default_interface
}
func (jh *JailHost) GetDefaultGateway4() string {
if len(jh.default_gateway4) == 0 {
jh.InitNetworkProperties()
@ -99,11 +97,9 @@ func (jh *JailHost) GetDefaultGateway4() string {
return jh.default_gateway4
}
func(jh *JailHost) GetDefaultGateway6() string {
func (jh *JailHost) GetDefaultGateway6() string {
if len(jh.default_gateway6) == 0 {
jh.InitNetworkProperties()
}
return jh.default_gateway6
}

View File

@ -1,15 +1,15 @@
package cmd
import (
"os"
"encoding/json"
"fmt"
"github.com/spf13/viper"
"gocage/jail"
"io/ioutil"
"log"
"os"
"reflect"
"strings"
"io/ioutil"
"gocage/jail"
"encoding/json"
"github.com/spf13/viper"
)
/********************************************************************************
@ -82,7 +82,6 @@ func ListJails(args []string, display bool) {
jails = gJails
}
/***************************************************************
/ Filter jails by names given on command line
/**************************************************************/
@ -123,10 +122,13 @@ func ListJails(args []string, display bool) {
fmt.Printf("ERROR getting JailSort struct field %s. Please check the field name: %s\n", fctName, fieldName)
return
}
switch i+1 {
case 1: fct1 = fct
case 2: fct2 = fct
case 3: fct3 = fct
switch i + 1 {
case 1:
fct1 = fct
case 2:
fct2 = fct
case 3:
fct3 = fct
}
}
@ -148,25 +150,33 @@ func ListJails(args []string, display bool) {
}
}
func listJailsFromDatastore(datastore string) {
fileInfo, err := os.Stat(datastore)
if err != nil { log.Fatalln(fmt.Sprintf("Unable to access %s, check path and/or rights", datastore)) }
if fileInfo.IsDir() == false { log.Fatalln(fmt.Sprintf("%s is not a directory", datastore)) }
if err != nil {
log.Fatalln(fmt.Sprintf("Unable to access %s, check path and/or rights", datastore))
}
if fileInfo.IsDir() == false {
log.Fatalln(fmt.Sprintf("%s is not a directory", datastore))
}
// A datastore have to contain a "jails" directory
jailsDir := fmt.Sprintf("%s/jails", datastore)
fileInfo, err = os.Stat(jailsDir)
if err != nil { log.Fatalln(fmt.Sprintf("Unable to access %s, check path and/or rights", jailsDir)) }
if fileInfo.IsDir() == false { log.Fatalln(fmt.Sprintf("%s is not a directory", jailsDir)) }
if err != nil {
log.Fatalln(fmt.Sprintf("Unable to access %s, check path and/or rights", jailsDir))
}
if fileInfo.IsDir() == false {
log.Fatalln(fmt.Sprintf("%s is not a directory", jailsDir))
}
listJailsFromDirectory(jailsDir)
}
func listJailsFromDirectory(dir string) ([]Jail) {
func listJailsFromDirectory(dir string) []Jail {
files, err := ioutil.ReadDir(dir)
if err != nil { log.Fatalln(fmt.Sprintf("Unable to browse %s, check path and/or rights", dir)) }
if err != nil {
log.Fatalln(fmt.Sprintf("Unable to browse %s, check path and/or rights", dir))
}
for _, fi := range files {
if fi.IsDir() == true {
@ -174,7 +184,9 @@ func listJailsFromDirectory(dir string) ([]Jail) {
// 1. Get conf from config.json
jailConfPath := fmt.Sprintf("%s/%s/%s", dir, fi.Name(), "config.json")
jailConf, err := getJailConfig(jailConfPath)
if err != nil { log.Println("ERROR reading jail config for %s", jailConfPath) }
if err != nil {
log.Println("ERROR reading jail config for %s", jailConfPath)
}
// 2. Build jail object from config
jailRootPath := fmt.Sprintf("%s/%s/%s", dir, fi.Name(), "root")
@ -188,7 +200,9 @@ func listJailsFromDirectory(dir string) ([]Jail) {
// 3. Add current running informations
rjails, err := jail.GetJails()
if err != nil { log.Fatalln("Unable to list running jails") }
if err != nil {
log.Fatalln("Unable to list running jails")
}
for _, rj := range rjails {
if rj.Path == j.RootPath {
j.JID = rj.Jid
@ -198,7 +212,7 @@ func listJailsFromDirectory(dir string) ([]Jail) {
}
}
/* This op take some 600ms for ~40 jails :^( */
/* This op take some 600ms for ~40 jails :^( */
out, err := executeCommand(fmt.Sprintf("zfs list -H -o name %s", j.RootPath))
if err != nil {
fmt.Printf("ERROR getting dataset from %s: %s\n", j.RootPath, err.Error())
@ -213,10 +227,11 @@ func listJailsFromDirectory(dir string) ([]Jail) {
return gJails
}
func getJailConfig(jailConfigPath string) (JailConfig, error) {
content, err := ioutil.ReadFile(jailConfigPath)
if err != nil { log.Fatalln(fmt.Sprintf("Unable to read %s, check path and/or rights", jailConfigPath)) }
if err != nil {
log.Fatalln(fmt.Sprintf("Unable to read %s, check path and/or rights", jailConfigPath))
}
// Mandatory constructor to init default values
jc, err := NewJailConfig()
@ -224,7 +239,9 @@ func getJailConfig(jailConfigPath string) (JailConfig, error) {
return jc, err
}
err = json.Unmarshal([]byte(content), &jc)
if err != nil { log.Fatalln(fmt.Sprintf("Error occured during unmarshaling %s: %s", jailConfigPath, err.Error())) }
if err != nil {
log.Fatalln(fmt.Sprintf("Error occured during unmarshaling %s: %s", jailConfigPath, err.Error()))
}
return jc, err
}

View File

@ -1,11 +1,11 @@
package cmd
import (
"fmt"
"errors"
"fmt"
"reflect"
"strings"
"strconv"
"strings"
)
func GetJailProperties(args []string) {
@ -120,5 +120,3 @@ func SetJailProperties(args []string) {
}
}
}

View File

@ -1,19 +1,21 @@
package cmd
import (
"os"
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"strings"
"io/ioutil"
"encoding/json"
"github.com/spf13/cobra"
"github.com/spf13/viper"
// TODO : Use log
//log "github.com/sirupsen/logrus"
)
const (
gVersion = "0.25"
gVersion = "0.26a"
)
var (
@ -32,7 +34,7 @@ var (
gTimeZone string
gSnapshotName string
rootCmd = & cobra.Command {
rootCmd = &cobra.Command{
Use: "gocage",
Short: "GoCage is a FreeBSD Jail management tool",
Long: `GoCage is a jail management tool. It support VNET, host-only, NAT networks. Provides snapshots and cloning.
@ -43,7 +45,7 @@ It support iocage jails and can coexist with iocage.`,
},
}
versionCmd = &cobra.Command {
versionCmd = &cobra.Command{
Use: "version",
Short: "Print the version number of GoCage",
Long: `Let this show you how much fail I had to get this *cough* perfect`,
@ -52,7 +54,7 @@ It support iocage jails and can coexist with iocage.`,
},
}
listCmd = &cobra.Command {
listCmd = &cobra.Command{
Use: "list",
Short: "Print jails",
Long: `Display jails, their IP and OS.
@ -63,7 +65,7 @@ ex: gocage list srv-db srv-web`,
},
}
listPropsCmd = &cobra.Command {
listPropsCmd = &cobra.Command{
Use: "properties",
Short: "Print jails properties",
Long: "Display jails properties. You can use properties to filter, get or set them.",
@ -72,7 +74,7 @@ ex: gocage list srv-db srv-web`,
},
}
stopCmd = &cobra.Command {
stopCmd = &cobra.Command{
Use: "stop",
Short: "stop jail",
Long: "shutdown jail",
@ -83,7 +85,7 @@ ex: gocage list srv-db srv-web`,
},
}
startCmd = &cobra.Command {
startCmd = &cobra.Command{
Use: "start",
Short: "start jail",
Run: func(cmd *cobra.Command, args []string) {
@ -94,7 +96,7 @@ ex: gocage list srv-db srv-web`,
},
}
/* shellCmd = &cobra.Command {
/* shellCmd = &cobra.Command {
Use: "console",
Short: "Execute shell on jail",
Run: func(cmd *cobra.Command, args []string) {
@ -103,8 +105,8 @@ ex: gocage list srv-db srv-web`,
ShellJail(args)
},
}
*/
setCmd = &cobra.Command {
*/
setCmd = &cobra.Command{
Use: "set",
Short: "Set a jail property",
Long: `Set jail property value. Specify property=value, end command with jail name.
@ -117,7 +119,7 @@ Multiples properties can be specified, separated with space (Ex: gocage set allo
},
}
getCmd = &cobra.Command {
getCmd = &cobra.Command{
Use: "get",
Short: "Get a jail property",
Long: `Get jail property value. Specify property, end command with jail name.
@ -130,7 +132,7 @@ For all properties specify "all" (Ex: gocage get all myjail)`,
},
}
snapshotCmd = &cobra.Command {
snapshotCmd = &cobra.Command{
Use: "snapshot",
Short: "snapshot jail",
Long: "Commands to manage jail snapshots. If no arguments given, ",
@ -139,7 +141,7 @@ For all properties specify "all" (Ex: gocage get all myjail)`,
},
}
snapshotListCmd = &cobra.Command {
snapshotListCmd = &cobra.Command{
Use: "list",
Short: "list snapshots",
Long: `List snapshots of a jail by specifying its name.
@ -152,11 +154,11 @@ You can specify multiple jails.`,
},
}
snapshotCreateCmd = &cobra.Command {
snapshotCreateCmd = &cobra.Command{
Use: "create",
Short: "create snapshots",
Long: `Create snapshot of a jail by specifying snapshot name and jail name.`,
// You can specify multiple jails.`,
// You can specify multiple jails.`,
Run: func(cmd *cobra.Command, args []string) {
// Load inventory
ListJails(args, false)
@ -164,11 +166,11 @@ You can specify multiple jails.`,
},
}
snapshotRollbackCmd = &cobra.Command {
snapshotRollbackCmd = &cobra.Command{
Use: "rollback",
Short: "Rollback snapshots",
Long: `Rollback jail to specifyed snapshot.`,
// You can specify multiple jails.`,
// You can specify multiple jails.`,
Run: func(cmd *cobra.Command, args []string) {
// Load inventory
ListJails(args, false)
@ -176,7 +178,7 @@ You can specify multiple jails.`,
},
}
snapshotDeleteCmd = &cobra.Command {
snapshotDeleteCmd = &cobra.Command{
Use: "destroy",
Short: "destroy snapshots",
Long: `Destroy snapshot of a jail by specifying snapshot name and jail name.`,
@ -189,17 +191,16 @@ You can specify multiple jails.`,
}
)
// TODO : Init log level and log output
func init() {
cobra.OnInitialize(initConfig)
// Global switches
// Global switches
rootCmd.PersistentFlags().StringVarP(&gConfigFile, "config", "c", "/usr/local/etc/gocage.conf.yml", "GoCage configuration file")
rootCmd.PersistentFlags().BoolVarP(&gUseSudo, "sudo", "u", false, "Use sudo to run commands")
rootCmd.PersistentFlags().StringVarP(&gTimeZone, "timezone", "t", "", "Specify timezone. Will get from /var/db/zoneinfo if not set.")
// Command dependant switches
// Command dependant switches
// These are persistent so we can reuse them in "gocage list snapshot myjail" command (TODO)
listCmd.PersistentFlags().StringVarP(&gDisplayColumns, "outcol", "o", "JID,Name,Config.Release,Config.Ip4_addr,Running", "Show these columns in output")
@ -215,7 +216,7 @@ func init() {
snapshotRollbackCmd.Flags().StringVarP(&gSnapshotName, "snapname", "n", "", "Name of the snapshot to rollback to")
snapshotRollbackCmd.MarkFlagRequired("snapname")
// Now declare commands
// Now declare commands
rootCmd.AddCommand(versionCmd)
rootCmd.AddCommand(listCmd)
listCmd.AddCommand(listPropsCmd)
@ -245,7 +246,7 @@ func initConfig() {
os.Exit(1)
}
// fmt.Printf("We are in initConfig(), with config file %s\n", gConfigFile)
// fmt.Printf("We are in initConfig(), with config file %s\n", gConfigFile)
viper.SetConfigFile(gConfigFile)
@ -254,9 +255,9 @@ func initConfig() {
os.Exit(1)
}
// fmt.Println("Using config file:", viper.ConfigFileUsed())
// fmt.Printf("datastore in config : %s\n", viper.GetStringSlice("datastore"))
// fmt.Printf("datastore.0 in config : %s\n", viper.GetStringSlice("datastore.0"))
// fmt.Println("Using config file:", viper.ConfigFileUsed())
// fmt.Printf("datastore in config : %s\n", viper.GetStringSlice("datastore"))
// fmt.Printf("datastore.0 in config : %s\n", viper.GetStringSlice("datastore.0"))
// Command line flags have priority on config file
if rootCmd.Flags().Lookup("sudo") != nil && false == rootCmd.Flags().Lookup("sudo").Changed {
@ -292,7 +293,6 @@ func initConfig() {
}
}
/********************************************************************************
* Write jails config which been updated to disk.
* If changeauto not set, values which are in "auto" mode on disk
@ -352,5 +352,3 @@ func Execute() {
os.Exit(1)
}
}

View File

@ -1,13 +1,13 @@
package cmd
import (
"os"
"fmt"
"time"
"bufio"
"errors"
"fmt"
"os"
"regexp"
"strings"
"time"
)
/********************************************************************************
@ -36,10 +36,9 @@ func ListJailsSnapshots(args []string) {
}
}
}
displaySnapshotsFields(snapshots, []string{"Jailname","Name","Creation","Referenced","Used"})
displaySnapshotsFields(snapshots, []string{"Jailname", "Name", "Creation", "Referenced", "Used"})
}
/********************************************************************************
* List all snapshots a jail have
*******************************************************************************/
@ -89,7 +88,6 @@ func listJailSnapshots(jail Jail) []Snapshot {
return snapshots
}
/********************************************************************************
* Create snapshot for jail(s)
*******************************************************************************/

View File

@ -1,13 +1,16 @@
package cmd
import (
"os"
"fmt"
"errors"
"regexp"
"strings"
"strconv"
"fmt"
"github.com/c-robinson/iplib"
log "github.com/sirupsen/logrus"
"io/ioutil"
"net"
"os"
"regexp"
"strconv"
"strings"
)
// FIXME : Do not work?!
@ -153,7 +156,6 @@ func mountAllJailFsFromHost(jail *Jail) error {
}
}
// Ces montages doivent-ils etre effectués une fois le jail démarré?
// FreeBSD <= 9.3 do not support fdescfs
@ -189,7 +191,6 @@ func mountAllJailFsFromHost(jail *Jail) error {
return nil
}
// TODO
func prepareJailedZfsDatasets(jail *Jail) error {
if jail.Config.Jail_zfs > 0 {
@ -262,7 +263,7 @@ func getNatForwardsArray(nat_forwards string, decompose_range bool) ([]NatDesc,
if (ejrange - sjrange) != (ehrange - shrange) {
return res, errors.New(fmt.Sprintf("Invalid port range in nat_forwards: %s", match[0]))
}
for i := sjrange ; i <= ejrange ; i++ {
for i := sjrange; i <= ejrange; i++ {
nd := NatDesc{Proto: match[1],
JailPort: strconv.Itoa(i),
HostPort: strconv.Itoa(shrange + (i - sjrange)),
@ -281,6 +282,216 @@ func getNatForwardsArray(nat_forwards string, decompose_range bool) ([]NatDesc,
return res, nil
}
func enableRcKeyValue(rcconfpath string, key string, value string) error {
cmd := fmt.Sprintf("/usr/sbin/sysrc -f %s %s=%s", rcconfpath, key, value)
_, err := executeCommand(cmd)
if err != nil {
return err
}
return nil
}
func disableRcKey(rcconfpath string, key string) error {
cmd := fmt.Sprintf("/usr/sbin/sysrc -f %s -x %s", rcconfpath, key)
_, err := executeCommand(cmd)
if err != nil {
return err
}
return nil
}
/*****************************************************************************
* Enable or disables DHCP or accept_rtadv for interfaces declared with this
* option
****************************************************************************/
func configureDhcpOrAcceptRtadv(jail *Jail, ipproto int, enable bool) error {
var nics []string
// Iocage legacy behavior to enable on all interfaces if Config.Dhcp is set...
if ipproto == IPv4 && jail.Config.Dhcp > 0 || enable == false {
nic_list := strings.Split(jail.Config.Interfaces, ",")
for _, n := range nic_list {
nics = append(nics, strings.Split(n, ":")[0])
}
// ...else enable for selected interface in Config.IpX_addr
} else {
if ipproto == IPv4 {
for _, i := range strings.Split(jail.Config.Ip4_addr, ",") {
if strings.EqualFold(strings.ToLower(strings.Split(i, "|")[1]), "dhcp") {
nics = append(nics, i)
}
}
} else {
for _, i := range strings.Split(jail.Config.Ip6_addr, ",") {
if strings.EqualFold(strings.ToLower(strings.Split(i, "|")[1]), "accept_rtadv") {
nics = append(nics, i)
}
}
}
}
for _, n := range nics {
// vnet0 is epair0b inside jail
if strings.Contains(n, "vnet") {
n = fmt.Sprintf("%sb", strings.Replace(n, "vnet", "epair", 1))
}
key := fmt.Sprintf("ifconfig_%s", n)
value := "SYNCDHCP"
if ipproto == IPv6 {
key = fmt.Sprintf("%s_ipv6", key)
value = "inet6 auto_linklocal accept_rtadv autoconf"
}
if enable == true {
err := enableRcKeyValue(jail.ConfigPath, key, value)
if err != nil {
return fmt.Errorf("ERROR setting %s=%s with sysrc for jail %s: %s\n", key, value, jail.Name, err)
}
} else {
err := disableRcKey(jail.ConfigPath, key)
if err != nil {
return fmt.Errorf("ERROR deleting %s with sysrc for jail %s: %s\n", key, value, jail.Name, err)
}
}
}
return nil
}
func checkRtsold(jail *Jail) error {
if strings.Contains(jail.Config.Ip6_addr, "accept_rtadv") == false {
return fmt.Errorf("Must set at least one ip6_addr to accept_rtadv!\n")
}
err := enableRcKeyValue(jail.ConfigPath, "rtsold_enable", "yes")
if err != nil {
return fmt.Errorf("ERROR setting rtsold_enable=YES with sysrc for jail %s: %s\n", jail.Name, err)
}
return nil
}
func checkNat(backend string) error {
cmd := "/sbin/sysctl -q net.inet.ip.forwarding=1"
_, err := executeCommand(cmd)
if err != nil {
return fmt.Errorf("ERROR executing \"/sbin/sysctl -q net.inet.ip.forwarding=1\": %s", err)
}
if strings.EqualFold(backend, "pf") {
// Load module and enable pf
out, err := executeCommand("/sbin/kldload -n pf")
if err != nil {
if false == strings.Contains(out, "module already loaded or in kernel") {
return fmt.Errorf("ERROR executing \"/sbin/kldload pf\": %s", err)
}
}
out, err = executeCommand("/sbin/pfctl -e")
if err != nil {
if false == strings.Contains(out, "pf already enabled") {
return fmt.Errorf("ERROR executing \"/sbin/pfctl -e\": %s", err)
}
}
} else if strings.EqualFold(backend, "ipwf") {
// Check if module loaded
out, err := executeCommand("/sbin/sysctl net.inet.ip.fw.enable=1")
if err != nil {
if false == strings.Contains(out, "unknown oid 'net.inet.ip.fw.enable'") {
return fmt.Errorf("ERROR executing \"/sbin/sysctl net.inet.ip.fw.enable=1\": %s", err)
}
}
_, _ = executeCommand("/bin/kenv net.inet.ip.fw.default_to_accept=1")
_, _ = executeCommand("/sbin/kldload -n ipfw")
_, _ = executeCommand("/sbin/kldload -n ipfw_nat")
_, err = executeCommand("/sbin/sysctl -q net.inet.ip.fw.enable=1")
if err != nil {
return fmt.Errorf("ERROR executing \"/sbin/sysctl -q net.inet.ip.fw.enable=1\": %s", err)
}
}
return nil
}
func getJailsInUseIPv4() ([]string, error) {
var ips []string
re := regexp.MustCompile(ifconfigipv4re)
for _, j := range gJails {
out, err := executeCommandInJail(&j, "/sbin/ifconfig")
if err != nil {
return ips, fmt.Errorf("ERROR executing \"/sbin/ifconfig\" in jail %s: %s", j.Name, err)
}
for _, line := range strings.Split(out, "\n") {
if re.MatchString(line) {
ips = append(ips, re.FindStringSubmatch(line)[1])
}
}
}
return ips, nil
}
func getHostInUseIPv4() ([]string, error) {
var ips []string
re := regexp.MustCompile(ifconfigipv4re)
out, err := executeCommand("/sbin/ifconfig")
if err != nil {
return ips, fmt.Errorf("ERROR executing \"/sbin/ifconfig\": %s", err)
}
for _, line := range strings.Split(out, "\n") {
if re.MatchString(line) {
ips = append(ips, re.FindStringSubmatch(line)[1])
}
}
return ips, nil
}
func genNatIpv4(jail *Jail) ([]string, error) {
var ippair []string
// Get all IP in use, host and jails
inuseip4, err := getHostInUseIPv4()
if err != nil {
return ippair, err
}
ij, err := getJailsInUseIPv4()
if err != nil {
return ippair, err
}
inuseip4 = append(inuseip4, ij...)
// TODO : Voir https://github.com/iocage/iocage/blob/e94863d4c54f02523fb09e62e48be7db9ac92eda/iocage_lib/ioc_common.py#L1026
for i := 0; i < 256; i++ {
for j := 0; j < 256; j += 4 {
n := iplib.NewNet4(net.ParseIP(fmt.Sprintf("172.16.%d.%d", i, j)), 30)
for _, ip := range n.Enumerate(0, 0) {
ippair = append(ippair, ip.String())
}
found := false
for _, ip := range inuseip4 {
for _, ipn := range ippair {
if ip == ipn {
found = true
}
}
}
if found == false {
return ippair, nil
}
}
}
return ippair, nil
}
/*
Start jail:
Check jail fstab?
@ -309,6 +520,7 @@ func getNatForwardsArray(nat_forwards string, decompose_range bool) ([]NatDesc,
func StartJail(args []string) {
// jail we have to start
var cj *Jail
var err error
for _, j := range args {
fmt.Printf("> Starting jail %s\n", j)
@ -344,8 +556,8 @@ func StartJail(args []string) {
}
var props_missing []string
// DHCP can also be set with "DHCP" value in ip4_addr
if cj.Config.Dhcp > 0 || strings.EqualFold(cj.Config.Ip4_addr, "DHCP") == true {
// DHCP can also be set with "dhcp" value in ip4_addr (Eg: "vnet0|dhcp")
if cj.Config.Dhcp > 0 || strings.Contains(strings.ToLower(cj.Config.Ip4_addr), "dhcp") == true {
if cj.Config.Bpf == 0 {
props_missing = append(props_missing, fmt.Sprintf("%s: dhcp requires bpf", cj.Name))
}
@ -403,7 +615,48 @@ func StartJail(args []string) {
// "auto" default Gateway should not be updated to support jailhost route change
}
// Continue here
if strings.EqualFold(cj.Config.Ip6_addr, "accept_rtadv") && cj.Config.Vnet == 0 {
props_missing = append(props_missing, fmt.Sprintf("%s: accept_rtadv requires vnet", cj.Name))
}
if cj.Config.Bpf > 0 && cj.Config.Vnet == 0 {
props_missing = append(props_missing, fmt.Sprintf("%s: bpf requires vnet", cj.Name))
}
if len(props_missing) > 0 {
for _, m := range props_missing {
fmt.Printf("%s\n", m)
}
return
}
if cj.Config.Dhcp > 0 || strings.Contains(strings.ToLower(cj.Config.Ip4_addr), "dhcp") == true {
err = configureDhcpOrAcceptRtadv(cj, IPv4, true)
} else {
err = configureDhcpOrAcceptRtadv(cj, IPv4, false)
}
if err != nil {
fmt.Printf(err.Error())
return
}
if cj.Config.Rtsold > 0 {
err = checkRtsold(cj)
}
if err != nil {
fmt.Printf(err.Error())
return
}
if strings.Contains(strings.ToLower(cj.Config.Ip6_addr), "accept_rtadv") == true {
err = configureDhcpOrAcceptRtadv(cj, IPv6, true)
} else {
err = configureDhcpOrAcceptRtadv(cj, IPv6, false)
}
if err != nil {
fmt.Printf(err.Error())
return
}
fmt.Printf(" > Mount special filesystems:\n")
err := mountAllJailFsFromHost(cj)
@ -423,8 +676,48 @@ func StartJail(args []string) {
}
}
// TODO : Check capabilites relative to FreeBSD Version when executing jail with all parameters
// See l.335 of https://github.com/iocage/iocage/blob/e94863d4c54f02523fb09e62e48be7db9ac92eda/iocage_lib/ioc_start.py
//checkCapabilities(cj)
/*
// Check NAT backend
if cj.Config.Nat > 0 {
log.Debug("Check NAT backend %s\n", cj.Config.Nat_backend)
err = checkNat(cj.Config.Nat_backend)
if err != nil {
fmt.Printf(err.Error())
return
}
if cj.Config.Vnet == 0 {
log.Debug("Generate NAT IPv4 without VNet")
ip4, err := genNatIpv4(cj)
if err != nil {
fmt.Printf("%s\n", err.Error())
return
}
log.Debug("Configuring NAT : Set ip4_addr to %s", ip4[0])
// This IP should not be saved into json
cj.Config.Ip4_addr = fmt.Sprintf("%s|%s", cj.Config.Nat_interface, ip4[0])
} else {
log.Debug("Generate NAT IPv4 with VNet")
ip4, err := genNatIpv4(cj)
if err != nil {
fmt.Printf("%s\n", err.Error())
return
}
log.Debug("Configuring NAT : Set ip4_addr to %s, defaultrouter to %s", ip4[1], ip4[0])
// This IP should not be saved into json
cj.Config.Ip4_addr = fmt.Sprintf("vnet0|%s", ip4[1])
cj.Config.Defaultrouter = ip4[0]
}
}
// CONTINUE HERE
// See https://github.com/iocage/iocage/blob/e94863d4c54f02523fb09e62e48be7db9ac92eda/iocage_lib/ioc_start.py:401
/*
out, err := executeCommand(fmt.Sprintf("rctl jail:%s", cj.InternalName))
if err == nil && len(out) > 0 {
fmt.Printf(" > Remove RCTL rules:\n")
@ -491,8 +784,7 @@ func StartJail(args []string) {
} else {
fmt.Printf(" > Stop jail %s: OK\n", cj.Name)
}
*/
*/
}
}

View File

@ -1,13 +1,13 @@
package cmd
import (
"os"
"fmt"
// "log"
"os"
// "log"
"errors"
"regexp"
"os/exec"
// "reflect"
"regexp"
// "reflect"
"strings"
)
@ -38,7 +38,6 @@ func removeRctlRules(jail string, rules []string) error {
return nil
}
// TODO: Validate with >1 dataset
func umountAndUnjailZFS(jail *Jail) error {
var ds []string
@ -79,7 +78,6 @@ func umountAndUnjailZFS(jail *Jail) error {
return nil
}
func destroyVNetInterfaces(jail *Jail) error {
for _, i := range strings.Split(jail.Config.Ip4_addr, ",") {
iname := fmt.Sprintf("%s.%d", strings.Split(i, "|")[0], jail.JID)
@ -119,7 +117,6 @@ func deleteDevfsRuleset(jail *Jail) error {
return nil
}
func umountJailFsFromHost(jail *Jail, mountpoint string) error {
cmd := "mount -p"
out, err := executeCommand(cmd)
@ -145,7 +142,6 @@ func umountJailFsFromHost(jail *Jail, mountpoint string) error {
return nil
}
// Internal usage only
func stopJail(jail *Jail) error {
cmd := "jail -q"
@ -221,7 +217,7 @@ func StopJail(args []string) {
}
}
if len (cj.Config.Exec_prestop) > 0 {
if len(cj.Config.Exec_prestop) > 0 {
fmt.Printf(" > Execute prestop:\n")
_, err := executeCommand(cj.Config.Exec_prestop)
if err != nil {
@ -231,7 +227,7 @@ func StopJail(args []string) {
}
}
if len (cj.Config.Exec_stop) > 0 {
if len(cj.Config.Exec_stop) > 0 {
fmt.Printf(" > Execute stop:\n")
_, err := executeCommandInJail(cj, cj.Config.Exec_stop)
if err != nil {
@ -340,4 +336,3 @@ func StopJail(args []string) {
}
}
}

View File

@ -4,6 +4,11 @@ import (
"time"
)
const (
IPv4 = 0
IPv6 = 1
)
// To allow sorting, just duplicate fields in JailSort below
type Jail struct {
Name string

View File

@ -1,19 +1,23 @@
package cmd
import (
"os"
"fmt"
"log"
"sort"
"bufio"
"errors"
"fmt"
"io/ioutil"
"log"
"os"
"os/exec"
"reflect"
"strings"
"sort"
"strconv"
"io/ioutil"
"strings"
)
const (
ipv4re = `[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}`
ifconfigipv4re = `inet[[:space:]](` + ipv4re + `)`
)
/*****************************************************************************
* Mandatory constructor for JailConfig type. It set default values
@ -177,7 +181,7 @@ func executeCommand(cmdline string) (string, error) {
cmd = append(cmd, cs...)
if len (cmd) > 1 {
if len(cmd) > 1 {
out, err = exec.Command(cmd[0], cmd[1:]...).Output()
} else {
out, err = exec.Command(cmd[0]).Output()
@ -186,7 +190,6 @@ func executeCommand(cmdline string) (string, error) {
return string(out), err
}
func executeCommandInJail(jail *Jail, cmdline string) (string, error) {
var cmd []string
@ -238,12 +241,12 @@ func getFstab(path string) ([]Mount, error) {
return mounts, fmt.Errorf("Incorrect format for fstab line %s: Pass is not an integer\n", scan.Text())
}
m := Mount{
Device : res[0],
Mountpoint : res[1],
Type : res[2],
Options : strings.Split(res[3], ","),
Fs_Freq : freq,
Fs_Passno : pass,
Device: res[0],
Mountpoint: res[1],
Type: res[2],
Options: strings.Split(res[3], ","),
Fs_Freq: freq,
Fs_Passno: pass,
}
mounts = append(mounts, m)
}
@ -251,7 +254,6 @@ func getFstab(path string) ([]Mount, error) {
return mounts, nil
}
/********************************************************************************
* Get a specific jail source reference, to update properties after a range loop
*******************************************************************************/
@ -277,7 +279,7 @@ func getStructFieldKind(parentStruct interface{}, fieldName string) (reflect.Kin
// For debugging
if false {
for i := 0 ; i < v.NumField(); i++ {
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.Kind() == reflect.String {
fmt.Printf("%v=%v\n", v.Type().Field(i).Name, f.Interface())
@ -313,7 +315,7 @@ func getStructFieldKind(parentStruct interface{}, fieldName string) (reflect.Kin
func getStructFieldNames(parentStruct interface{}, result []string, prefix string) []string {
v := reflect.ValueOf(parentStruct)
for i := 0 ; i < v.NumField() ; i++ {
for i := 0; i < v.NumField(); i++ {
if v.Type().Field(i).Type.Kind() == reflect.Struct {
result = getStructFieldNames(v.Field(i).Interface(), result, v.Type().Field(i).Name)
} else {
@ -337,7 +339,8 @@ func getStructFieldValue(parentStruct interface{}, fieldName string) (*reflect.V
v := reflect.ValueOf(parentStruct)
// Get value while we're dealing with pointers
for ; v.Kind() == reflect.Ptr ; v = v.Elem() {}
for ; v.Kind() == reflect.Ptr; v = v.Elem() {
}
if v.Kind() != reflect.Struct {
return &v, fieldName, errors.New(fmt.Sprintf("parentStruct is not a struct! Kind: %s", v.Kind().String()))
@ -346,7 +349,7 @@ func getStructFieldValue(parentStruct interface{}, fieldName string) (*reflect.V
typeOfV := v.Type()
if false {
for i := 0 ; i < v.NumField(); i++ {
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.Kind() == reflect.String {
fmt.Printf("%v=%v\n", v.Type().Field(i).Name, f.Interface())
@ -361,7 +364,7 @@ func getStructFieldValue(parentStruct interface{}, fieldName string) (*reflect.V
// Loop through properties
for i, curF := range fs {
found = false
for j := 0 ; j < v.NumField() ; j++ {
for j := 0; j < v.NumField(); j++ {
if typeOfV.Field(j).Name == curF {
f = v.Field(j)
found = true
@ -372,7 +375,8 @@ func getStructFieldValue(parentStruct interface{}, fieldName string) (*reflect.V
return &v, fieldName, errors.New(fmt.Sprintf("Field not found: %s", fieldName))
}
for ; f.Kind() == reflect.Ptr ; f = f.Elem() {}
for ; f.Kind() == reflect.Ptr; f = f.Elem() {
}
/*fmt.Printf("v.kind() = %v\n", v.Kind().String())
fmt.Printf("v = %v\n", v)
@ -397,7 +401,6 @@ func getStructFieldValue(parentStruct interface{}, fieldName string) (*reflect.V
return &v, fieldName, nil
}
/********************************************************************************
* TODO : Replace by getStructFieldValue
* Recurse into structure, returning reflect.Value of wanted field.
@ -411,7 +414,7 @@ func getStructField(parentStruct interface{}, fieldName string) (reflect.Value,
}
if false {
for i := 0 ; i < v.NumField(); i++ {
for i := 0; i < v.NumField(); i++ {
f := v.Field(i)
if f.Kind() == reflect.String {
fmt.Printf("%v=%v\n", v.Type().Field(i).Name, f.Interface())
@ -501,7 +504,7 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
for i, f := range valsToDisplay {
a, f := getStructField(tj, f)
field := Field {
field := Field{
Name: f,
}
if a.FieldByName(f).IsValid() {
@ -530,7 +533,7 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
// Get real maximum length
maxlen := make([]int, len(valsToDisplay))
for i := 0; i< len(valsToDisplay); i++ {
for i := 0; i < len(valsToDisplay); i++ {
maxlen[i] = len(valsToDisplay[i])
}
for _, l := range out {
@ -567,13 +570,16 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
// Lets draw things on the screen!
// First, headers: 1st separator line
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("=") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("=")
}
fmt.Printf("+")
}
fmt.Printf("\n")
// Column names
for i, f := range out[0] {
if i == 0 {
@ -583,7 +589,7 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
* fmt.Printf(" %s", f.Name)
* for i := len(f.Name)+1 ; i < f.MaxLen+1 ; i++ { */
fmt.Printf(" %s", valsToDisplay[i])
for i := len(valsToDisplay[i])+1 ; i < f.MaxLen+1 ; i++ {
for i := len(valsToDisplay[i]) + 1; i < f.MaxLen+1; i++ {
fmt.Printf(" ")
}
fmt.Printf(" |")
@ -591,8 +597,12 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
// Finally separator line
fmt.Printf("\n")
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("=") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("=")
}
fmt.Printf("+")
}
fmt.Printf("\n")
@ -626,7 +636,7 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
fmt.Printf(" %s", f.Value)
}
// Complete with spaces to the max length
for i := len(f.Value)+1 ; i < f.MaxLen+1 ; i++ {
for i := len(f.Value) + 1; i < f.MaxLen+1; i++ {
fmt.Printf(" ")
}
fmt.Printf(" |")
@ -648,7 +658,7 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
//fmt.Printf(" %s", f.Value)
}
// Complete with spaces to the max length
for i := len(v)+1 ; i < f.MaxLen+1 ; i++ {
for i := len(v) + 1; i < f.MaxLen+1; i++ {
fmt.Printf(" ")
}
fmt.Printf(" |")
@ -658,8 +668,12 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
if !gNoLineSep {
fmt.Printf("\n")
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("-") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("-")
}
fmt.Printf("+")
}
}
@ -667,8 +681,12 @@ func displayJailsFields(jails []Jail, valsToDisplay []string) {
}
if gNoLineSep {
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("-") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("-")
}
fmt.Printf("+")
}
}
@ -711,7 +729,7 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
for i, f := range valsToDisplay {
a, f := getStructField(tj, f)
field := Field {
field := Field{
Name: f,
}
if a.FieldByName(f).IsValid() {
@ -740,7 +758,7 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
// Get real maximum length
maxlen := make([]int, len(valsToDisplay))
for i := 0; i< len(valsToDisplay); i++ {
for i := 0; i < len(valsToDisplay); i++ {
maxlen[i] = len(valsToDisplay[i])
}
for _, l := range out {
@ -777,13 +795,16 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
// Lets draw things on the screen!
// First, headers: 1st separator line
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("=") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("=")
}
fmt.Printf("+")
}
fmt.Printf("\n")
// Column names
for i, f := range out[0] {
if i == 0 {
@ -793,7 +814,7 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
* fmt.Printf(" %s", f.Name)
* for i := len(f.Name)+1 ; i < f.MaxLen+1 ; i++ { */
fmt.Printf(" %s", valsToDisplay[i])
for i := len(valsToDisplay[i])+1 ; i < f.MaxLen+1 ; i++ {
for i := len(valsToDisplay[i]) + 1; i < f.MaxLen+1; i++ {
fmt.Printf(" ")
}
fmt.Printf(" |")
@ -801,8 +822,12 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
// Finally separator line
fmt.Printf("\n")
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("=") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("=")
}
fmt.Printf("+")
}
fmt.Printf("\n")
@ -819,7 +844,7 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
fmt.Printf("|")
}
// Special cases of value displaying
/* if f.Name == "JID" && f.Value == "0" {
/* if f.Name == "JID" && f.Value == "0" {
fmt.Printf(" ")
} else if f.Name == "Ip4_addr" {
ia := strings.Split(f.Value, ",")
@ -836,7 +861,7 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
fmt.Printf(" %s", f.Value)
/*}*/
// Complete with spaces to the max length
for i := len(f.Value)+1 ; i < f.MaxLen+1 ; i++ {
for i := len(f.Value) + 1; i < f.MaxLen+1; i++ {
fmt.Printf(" ")
}
fmt.Printf(" |")
@ -858,7 +883,7 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
//fmt.Printf(" %s", f.Value)
}
// Complete with spaces to the max length
for i := len(v)+1 ; i < f.MaxLen+1 ; i++ {
for i := len(v) + 1; i < f.MaxLen+1; i++ {
fmt.Printf(" ")
}
fmt.Printf(" |")
@ -868,8 +893,12 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
if !gNoLineSep {
fmt.Printf("\n")
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("-") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("-")
}
fmt.Printf("+")
}
}
@ -877,8 +906,12 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
}
if gNoLineSep {
for i, f := range out[0] {
if i == 0 { fmt.Printf("+") }
for i := 0 ; i < f.MaxLen+2 ; i++ { fmt.Printf("-") }
if i == 0 {
fmt.Printf("+")
}
for i := 0; i < f.MaxLen+2; i++ {
fmt.Printf("-")
}
fmt.Printf("+")
}
}
@ -886,7 +919,6 @@ func displaySnapshotsFields(snaps []Snapshot, valsToDisplay []string) {
fmt.Printf("\n")
}
/*****************************************************************************
*
* Sorting jails
@ -1822,7 +1854,6 @@ func (js *jailSorter) Less(i, j int) bool {
return js.less[k](p, q)
}
/*****************************************************************************
*
* Sorting snapshots
@ -1937,7 +1968,6 @@ func (ss *snapshotSorter) Less(i, j int) bool {
return ss.less[k](p, q)
}
/*****************************************************************************
*
* Generic utilities
@ -1951,4 +1981,3 @@ func isStringInArray(strarr []string, searched string) bool {
}
return false
}

2
go.mod
View File

@ -3,6 +3,8 @@ module gocage
go 1.17
require (
github.com/c-robinson/iplib v1.0.3
github.com/sirupsen/logrus v1.8.1
github.com/spf13/cobra v1.2.1
github.com/spf13/viper v1.9.0
golang.org/x/net v0.0.0-20210503060351-7fd8e65b6420

View File

@ -4,7 +4,6 @@ import (
"gocage/cmd"
)
func main () {
func main() {
cmd.Execute()
}