From d14705f1f0b1f555e233aaab33524dd602a3bcf9 Mon Sep 17 00:00:00 2001 From: buty4649 Date: Sun, 24 Mar 2024 18:55:10 +0900 Subject: [PATCH] Add flag to always run post-script in apply command --- cmd/apply.go | 22 ++++++++++++++-------- 1 file changed, 14 insertions(+), 8 deletions(-) diff --git a/cmd/apply.go b/cmd/apply.go index 387c8d0..2954205 100644 --- a/cmd/apply.go +++ b/cmd/apply.go @@ -31,15 +31,18 @@ import ( "github.com/spf13/cobra" ) -// applyCmd represents the apply command +var alwaysRunPostScript bool + var applyCmd = &cobra.Command{ Use: "apply", Short: "Apply netns networks configuration to running system", Long: "Apply netns networks configuration to running system", RunE: func(cmd *cobra.Command, args []string) error { for netns, values := range cfg.Netns { + needPostScript := true if ip.ExistsNetns(netns) { slog.Warn("netns is already exists", "name", netns) + needPostScript = false } else { slog.Info("create netns", "name", netns) err := ip.AddNetns(netns) @@ -68,15 +71,22 @@ var applyCmd = &cobra.Command{ return err } - err = RunPostScript(netns, values.PostScript) - if err != nil { - return err + if needPostScript || alwaysRunPostScript { + err = RunPostScript(netns, values.PostScript) + if err != nil { + return err + } } } return nil }, } +func init() { + rootCmd.AddCommand(applyCmd) + applyCmd.Flags().BoolVarP(&alwaysRunPostScript, "always-run-post-script", "R", false, "always run post-script. by default, runs only when a netns is created.") +} + type IpCommand interface { SetLinkUp(name string) error ShowLink(name string) (*iproute2.Link, error) @@ -301,10 +311,6 @@ func SetupVethDevices(netns string, devices map[string]config.VethDevice) error return nil } -func init() { - rootCmd.AddCommand(applyCmd) -} - func RunPostScript(netns string, script string) error { if script == "" { return nil