| 1 | |
| 2 | |
| 3 | |
| 4 | package main |
| 5 | |
| 6 | import ( |
| 7 | "context" |
| 8 | "encoding/json" |
| 9 | "errors" |
| 10 | "fmt" |
| 11 | "maps" |
| 12 | "net" |
| 13 | "os" |
| 14 | "slices" |
| 15 | "strings" |
| 16 | "text/tabwriter" |
| 17 | |
| 18 | "github.com/sirupsen/logrus" |
| 19 | "github.com/spf13/cobra" |
| 20 | |
| 21 | "github.com/lima-vm/lima/v2/pkg/networks" |
| 22 | "github.com/lima-vm/lima/v2/pkg/yqutil" |
| 23 | ) |
| 24 | |
| 25 | const networkExample = ` List all networks: |
| 26 | $ limactl network list |
| 27 | |
| 28 | Create a network: |
| 29 | $ limactl network create foo --gateway 192.168.42.1/24 |
| 30 | |
| 31 | Connect VM instances to the newly created network: |
| 32 | $ limactl create --network lima:foo --name vm1 |
| 33 | $ limactl create --network lima:foo --name vm2 |
| 34 | |
| 35 | Delete a network: |
| 36 | $ limactl network delete --force foo |
| 37 | ` |
| 38 | |
| 39 | const networkCreateExample = ` Create a network: |
| 40 | $ limactl network create foo --gateway 192.168.42.1/24 |
| 41 | |
| 42 | Connect VM instances to the newly created network: |
| 43 | $ limactl create --network lima:foo --name vm1 |
| 44 | $ limactl create --network lima:foo --name vm2 |
| 45 | ` |
| 46 | |
| 47 | func newNetworkCommand() *cobra.Command { |
| 48 | networkCommand := &cobra.Command{ |
| 49 | Use: "network", |
| 50 | Short: "Lima network management", |
| 51 | Example: networkExample, |
| 52 | GroupID: advancedCommand, |
| 53 | } |
| 54 | networkCommand.AddCommand( |
| 55 | newNetworkListCommand(), |
| 56 | newNetworkCreateCommand(), |
| 57 | newNetworkDeleteCommand(), |
| 58 | ) |
| 59 | return networkCommand |
| 60 | } |
| 61 | |
| 62 | func newNetworkListCommand() *cobra.Command { |
| 63 | cmd := &cobra.Command{ |
| 64 | Use: "list", |
| 65 | Short: "List networks", |
| 66 | Example: ` List all networks: |
| 67 | $ limactl network list |
| 68 | |
| 69 | List networks in JSON format: |
| 70 | $ limactl network list --json |
| 71 | `, |
| 72 | Aliases: []string{"ls"}, |
| 73 | Args: WrapArgsError(cobra.ArbitraryArgs), |
| 74 | RunE: networkListAction, |
| 75 | ValidArgsFunction: networkBashComplete, |
| 76 | } |
| 77 | flags := cmd.Flags() |
| 78 | flags.Bool("json", false, "JSONify output") |
| 79 | return cmd |
| 80 | } |
| 81 | |
| 82 | func networkListAction(cmd *cobra.Command, args []string) error { |
| 83 | flags := cmd.Flags() |
| 84 | jsonFormat, err := flags.GetBool("json") |
| 85 | if err != nil { |
| 86 | return err |
| 87 | } |
| 88 | |
| 89 | config, err := networks.LoadConfig() |
| 90 | if err != nil { |
| 91 | return err |
| 92 | } |
| 93 | |
| 94 | allNetworks := slices.Sorted(maps.Keys(config.Networks)) |
| 95 | |
| 96 | networkNames := []string{} |
| 97 | if len(args) > 0 { |
| 98 | for _, arg := range args { |
| 99 | matches := nameMatches(arg, allNetworks) |
| 100 | if len(matches) > 0 { |
| 101 | networkNames = append(networkNames, matches...) |
| 102 | } else { |
| 103 | logrus.Warnf("No network matching %v found.", arg) |
| 104 | } |
| 105 | } |
| 106 | } else { |
| 107 | networkNames = allNetworks |
| 108 | } |
| 109 | |
| 110 | if jsonFormat { |
| 111 | w := cmd.OutOrStdout() |
| 112 | for _, name := range networkNames { |
| 113 | nw, ok := config.Networks[name] |
| 114 | if !ok { |
| 115 | logrus.Errorf("network %#q does not exist", nw) |
| 116 | continue |
| 117 | } |
| 118 | j, err := json.Marshal(struct { |
| 119 | Name string `json:"name"` |
| 120 | networks.Network |
| 121 | }{Name: name, Network: nw}) |
| 122 | if err != nil { |
| 123 | return err |
| 124 | } |
| 125 | fmt.Fprintln(w, string(j)) |
| 126 | } |
| 127 | return nil |
| 128 | } |
| 129 | |
| 130 | w := tabwriter.NewWriter(cmd.OutOrStdout(), 4, 8, 4, ' ', 0) |
| 131 | fmt.Fprintln(w, "NAME\tMODE\tGATEWAY\tINTERFACE") |
| 132 | for _, name := range networkNames { |
| 133 | nw, ok := config.Networks[name] |
| 134 | if !ok { |
| 135 | logrus.Errorf("network %#q does not exist", nw) |
| 136 | continue |
| 137 | } |
| 138 | gwStr := "-" |
| 139 | if nw.Gateway != nil { |
| 140 | gw := net.IPNet{ |
| 141 | IP: nw.Gateway, |
| 142 | Mask: net.IPMask(nw.NetMask), |
| 143 | } |
| 144 | gwStr = gw.String() |
| 145 | } |
| 146 | intfStr := "-" |
| 147 | if nw.Interface != "" { |
| 148 | intfStr = nw.Interface |
| 149 | } |
| 150 | fmt.Fprintf(w, "%s\t%s\t%s\t%s\n", name, nw.Mode, gwStr, intfStr) |
| 151 | } |
| 152 | return w.Flush() |
| 153 | } |
| 154 | |
| 155 | func newNetworkCreateCommand() *cobra.Command { |
| 156 | cmd := &cobra.Command{ |
| 157 | Use: "create NETWORK", |
| 158 | Short: "Create a Lima network", |
| 159 | Example: networkCreateExample, |
| 160 | Args: WrapArgsError(cobra.ExactArgs(1)), |
| 161 | RunE: networkCreateAction, |
| 162 | } |
| 163 | flags := cmd.Flags() |
| 164 | flags.String("mode", networks.ModeUserV2, "mode") |
| 165 | _ = cmd.RegisterFlagCompletionFunc("mode", func(*cobra.Command, []string, string) ([]string, cobra.ShellCompDirective) { |
| 166 | return networks.Modes, cobra.ShellCompDirectiveNoFileComp |
| 167 | }) |
| 168 | flags.String("gateway", "", "gateway, e.g., \"192.168.42.1/24\"") |
| 169 | flags.String("interface", "", "interface for bridged mode") |
| 170 | _ = cmd.RegisterFlagCompletionFunc("interface", bashFlagCompleteNetworkInterfaceNames) |
| 171 | return cmd |
| 172 | } |
| 173 | |
| 174 | func networkCreateAction(cmd *cobra.Command, args []string) error { |
| 175 | name := args[0] |
| 176 | |
| 177 | config, err := networks.LoadConfig() |
| 178 | if err != nil { |
| 179 | return err |
| 180 | } |
| 181 | if _, ok := config.Networks[name]; ok { |
| 182 | return fmt.Errorf("network %#q already exists", name) |
| 183 | } |
| 184 | |
| 185 | flags := cmd.Flags() |
| 186 | mode, err := flags.GetString("mode") |
| 187 | if err != nil { |
| 188 | return err |
| 189 | } |
| 190 | |
| 191 | gateway, err := flags.GetString("gateway") |
| 192 | if err != nil { |
| 193 | return err |
| 194 | } |
| 195 | |
| 196 | intf, err := flags.GetString("interface") |
| 197 | if err != nil { |
| 198 | return err |
| 199 | } |
| 200 | |
| 201 | ctx := cmd.Context() |
| 202 | |
| 203 | switch mode { |
| 204 | case networks.ModeBridged: |
| 205 | if gateway != "" { |
| 206 | return fmt.Errorf("network mode %#q does not support specifying gateway", mode) |
| 207 | } |
| 208 | if intf == "" { |
| 209 | return fmt.Errorf("network mode %#q requires specifying interface", mode) |
| 210 | } |
| 211 | yq := fmt.Sprintf(`.networks.%q = {"mode":%q,"interface":%q}`, name, mode, intf) |
| 212 | return networkApplyYQ(ctx, yq) |
| 213 | default: |
| 214 | if gateway == "" { |
| 215 | return fmt.Errorf("network mode %#q requires specifying gateway", mode) |
| 216 | } |
| 217 | if intf != "" { |
| 218 | return fmt.Errorf("network mode %#q does not support specifying interface", mode) |
| 219 | } |
| 220 | if !strings.Contains(gateway, "/") { |
| 221 | gateway += "/24" |
| 222 | } |
| 223 | gwIP, gwMask, err := net.ParseCIDR(gateway) |
| 224 | if err != nil { |
| 225 | return fmt.Errorf("failed to parse CIDR %#q: %w", gateway, err) |
| 226 | } |
| 227 | if gwIP.IsUnspecified() || gwIP.IsLoopback() { |
| 228 | return fmt.Errorf("invalid IP address: %v", gwIP) |
| 229 | } |
| 230 | gwMaskStr := "255.255.255.0" |
| 231 | if gwMask != nil { |
| 232 | gwMaskStr = net.IP(gwMask.Mask).String() |
| 233 | } |
| 234 | TODO: |
| 235 | |
| 236 | yq := fmt.Sprintf(`.networks.%q = {"mode":%q,"gateway":%q,"netmask":%q,"interface":%q}`, name, mode, gwIP.String(), gwMaskStr, intf) |
| 237 | return networkApplyYQ(ctx, yq) |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | func networkApplyYQ(ctx context.Context, yq string) error { |
| 242 | filePath, err := networks.ConfigFile() |
| 243 | if err != nil { |
| 244 | return err |
| 245 | } |
| 246 | yContent, err := os.ReadFile(filePath) |
| 247 | if err != nil { |
| 248 | return err |
| 249 | } |
| 250 | yBytes, err := yqutil.EvaluateExpression(ctx, yq, yContent) |
| 251 | if err != nil { |
| 252 | return err |
| 253 | } |
| 254 | if err := os.WriteFile(filePath, yBytes, 0o644); err != nil { |
| 255 | return err |
| 256 | } |
| 257 | return nil |
| 258 | } |
| 259 | |
| 260 | func newNetworkDeleteCommand() *cobra.Command { |
| 261 | cmd := &cobra.Command{ |
| 262 | Use: "delete NETWORK [NETWORK, ...]", |
| 263 | Short: "Delete one or more Lima networks", |
| 264 | Example: ` Delete a network: |
| 265 | $ limactl network delete --force foo |
| 266 | |
| 267 | Delete multiple networks: |
| 268 | $ limactl network delete --force foo bar |
| 269 | `, |
| 270 | Aliases: []string{"remove", "rm"}, |
| 271 | Args: WrapArgsError(cobra.MinimumNArgs(1)), |
| 272 | RunE: networkDeleteAction, |
| 273 | ValidArgsFunction: networkBashComplete, |
| 274 | } |
| 275 | flags := cmd.Flags() |
| 276 | flags.BoolP("force", "f", false, "Force delete (currently always required)") |
| 277 | return cmd |
| 278 | } |
| 279 | |
| 280 | func networkDeleteAction(cmd *cobra.Command, args []string) error { |
| 281 | flags := cmd.Flags() |
| 282 | force, err := flags.GetBool("force") |
| 283 | if err != nil { |
| 284 | return err |
| 285 | } |
| 286 | if !force { |
| 287 | return errors.New("`limactl network delete` currently always requires `--force`") |
| 288 | |
| 289 | } |
| 290 | |
| 291 | networks := make([]string, len(args)) |
| 292 | for i, name := range args { |
| 293 | networks[i] = fmt.Sprintf("del(.networks.%q)", name) |
| 294 | } |
| 295 | yq := strings.Join(networks, " | ") |
| 296 | return networkApplyYQ(cmd.Context(), yq) |
| 297 | } |
| 298 | |
| 299 | func networkBashComplete(cmd *cobra.Command, _ []string, _ string) ([]string, cobra.ShellCompDirective) { |
| 300 | return bashCompleteNetworkNames(cmd) |
| 301 | } |