network

package
v1.42.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 1, 2024 License: MIT Imports: 15 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AddRouteCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "add-route NETWORK FLAGS",
			Short:                 "Add a route to a network",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().IPNet("destination", net.IPNet{}, "Destination network or host (required)")
		cmd.MarkFlagRequired("destination")

		cmd.Flags().IP("gateway", net.IP{}, "Gateway IP address (required)")
		cmd.MarkFlagRequired("gateway")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		gateway, _ := cmd.Flags().GetIP("gateway")
		destination, _ := cmd.Flags().GetIPNet("destination")
		idOrName := args[0]

		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		opts := hcloud.NetworkAddRouteOpts{
			Route: hcloud.NetworkRoute{
				Gateway:     gateway,
				Destination: &destination,
			},
		}
		action, _, err := s.Client().Network().AddRoute(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.ActionProgress(cmd, s, action); err != nil {
			return err
		}
		cmd.Printf("Route added to network %d\n", network.ID)

		return nil
	},
}
View Source
var AddSubnetCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "add-subnet NETWORK FLAGS",
			Short:                 "Add a subnet to a network",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().String("type", "", "Type of subnet (required)")
		cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("cloud", "server", "vswitch"))
		cmd.MarkFlagRequired("type")

		cmd.Flags().String("network-zone", "", "Name of network zone (required)")
		cmd.RegisterFlagCompletionFunc("network-zone", cmpl.SuggestCandidatesF(client.Location().NetworkZones))
		cmd.MarkFlagRequired("network-zone")

		cmd.Flags().IPNet("ip-range", net.IPNet{}, "Range to allocate IPs from")

		cmd.Flags().Int64("vswitch-id", 0, "ID of the vSwitch")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		subnetType, _ := cmd.Flags().GetString("type")
		networkZone, _ := cmd.Flags().GetString("network-zone")
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		vSwitchID, _ := cmd.Flags().GetInt64("vswitch-id")
		idOrName := args[0]

		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}
		subnet := hcloud.NetworkSubnet{
			Type:        hcloud.NetworkSubnetType(subnetType),
			NetworkZone: hcloud.NetworkZone(networkZone),
		}

		if ipRange.IP != nil && ipRange.Mask != nil {
			subnet.IPRange = &ipRange
		}
		if subnetType == "vswitch" {
			subnet.VSwitchID = vSwitchID
		}

		opts := hcloud.NetworkAddSubnetOpts{
			Subnet: subnet,
		}
		action, _, err := s.Client().Network().AddSubnet(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.ActionProgress(cmd, s, action); err != nil {
			return err
		}
		cmd.Printf("Subnet added to network %d\n", network.ID)

		return nil
	},
}
View Source
var ChangeIPRangeCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "change-ip-range [FLAGS] NETWORK",
			Short:                 "Change the IP range of a network",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().IPNet("ip-range", net.IPNet{}, "New IP range (required)")
		cmd.MarkFlagRequired("ip-range")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		opts := hcloud.NetworkChangeIPRangeOpts{
			IPRange: &ipRange,
		}

		action, _, err := s.Client().Network().ChangeIPRange(s, network, opts)
		if err != nil {
			return err
		}

		if err := s.ActionProgress(cmd, s, action); err != nil {
			return err
		}
		cmd.Printf("IP range of network %d changed\n", network.ID)
		return nil
	},
}
View Source
var CreateCmd = base.CreateCmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "create [FLAGS]",
			Short: "Create a network",
			Args:  cobra.NoArgs,
		}

		cmd.Flags().String("name", "", "Network name (required)")
		cmd.MarkFlagRequired("name")

		cmd.Flags().IPNet("ip-range", net.IPNet{}, "Network IP range (required)")
		cmd.MarkFlagRequired("ip-range")

		cmd.Flags().Bool("expose-routes-to-vswitch", false, "Expose routes from this network to the vSwitch connection. It only takes effect if a vSwitch connection is active.")

		cmd.Flags().StringToString("label", nil, "User-defined labels ('key=value') (can be specified multiple times)")

		cmd.Flags().StringSlice("enable-protection", []string{}, "Enable protection (delete) (default: none)")
		cmd.RegisterFlagCompletionFunc("enable-protection", cmpl.SuggestCandidates("delete"))
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) (any, any, error) {
		name, _ := cmd.Flags().GetString("name")
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		labels, _ := cmd.Flags().GetStringToString("label")
		exposeRoutesToVSwitch, _ := cmd.Flags().GetBool("expose-routes-to-vswitch")
		protection, _ := cmd.Flags().GetStringSlice("enable-protection")

		protectionOpts, err := getChangeProtectionOpts(true, protection)
		if err != nil {
			return nil, nil, err
		}

		createOpts := hcloud.NetworkCreateOpts{
			Name:                  name,
			IPRange:               &ipRange,
			Labels:                labels,
			ExposeRoutesToVSwitch: exposeRoutesToVSwitch,
		}

		network, _, err := s.Client().Network().Create(s, createOpts)
		if err != nil {
			return nil, nil, err
		}

		cmd.Printf("Network %d created\n", network.ID)

		if err := changeProtection(s, cmd, network, true, protectionOpts); err != nil {
			return nil, nil, err
		}

		return network, util.Wrap("network", hcloud.SchemaFromNetwork(network)), nil
	},
}
View Source
var DeleteCmd = base.DeleteCmd{
	ResourceNameSingular: "Network",
	ShortDescription:     "Delete a network",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.Network().Names },
	Fetch: func(s state.State, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().Network().Get(s, idOrName)
	},
	Delete: func(s state.State, cmd *cobra.Command, resource interface{}) error {
		network := resource.(*hcloud.Network)
		if _, err := s.Client().Network().Delete(s, network); err != nil {
			return err
		}
		return nil
	},
}
View Source
var DescribeCmd = base.DescribeCmd{
	ResourceNameSingular: "network",
	ShortDescription:     "Describe a network",
	JSONKeyGetByID:       "network",
	JSONKeyGetByName:     "networks",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.Network().Names },
	Fetch: func(s state.State, cmd *cobra.Command, idOrName string) (interface{}, interface{}, error) {
		n, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return nil, nil, err
		}
		return n, hcloud.SchemaFromNetwork(n), nil
	},
	PrintText: func(s state.State, cmd *cobra.Command, resource interface{}) error {
		network := resource.(*hcloud.Network)

		cmd.Printf("ID:\t\t%d\n", network.ID)
		cmd.Printf("Name:\t\t%s\n", network.Name)
		cmd.Printf("Created:\t%s (%s)\n", util.Datetime(network.Created), humanize.Time(network.Created))
		cmd.Printf("IP Range:\t%s\n", network.IPRange.String())
		cmd.Printf("Expose Routes to vSwitch: %s\n", util.YesNo(network.ExposeRoutesToVSwitch))

		cmd.Printf("Subnets:\n")
		if len(network.Subnets) == 0 {
			cmd.Print("  No subnets\n")
		} else {
			for _, subnet := range network.Subnets {
				cmd.Printf("  - Type:\t\t%s\n", subnet.Type)
				cmd.Printf("    Network Zone:\t%s\n", subnet.NetworkZone)
				cmd.Printf("    IP Range:\t\t%s\n", subnet.IPRange.String())
				cmd.Printf("    Gateway:\t\t%s\n", subnet.Gateway.String())
				if subnet.Type == hcloud.NetworkSubnetTypeVSwitch {
					cmd.Printf("    vSwitch ID:\t\t%d\n", subnet.VSwitchID)
				}
			}
		}

		cmd.Printf("Routes:\n")
		if len(network.Routes) == 0 {
			cmd.Print("  No routes\n")
		} else {
			for _, route := range network.Routes {
				cmd.Printf("  - Destination:\t%s\n", route.Destination.String())
				cmd.Printf("    Gateway:\t\t%s\n", route.Gateway.String())
			}
		}

		cmd.Printf("Protection:\n")
		cmd.Printf("  Delete:\t%s\n", util.YesNo(network.Protection.Delete))

		cmd.Print("Labels:\n")
		if len(network.Labels) == 0 {
			cmd.Print("  No labels\n")
		} else {
			for key, value := range network.Labels {
				cmd.Printf("  %s: %s\n", key, value)
			}
		}

		return nil
	},
}

DescribeCmd defines a command for describing a network.

View Source
var DisableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "disable-protection [FLAGS] NETWORK PROTECTIONLEVEL [PROTECTIONLEVEL...]",
			Short: "Disable resource protection for a network",
			Args:  cobra.MinimumNArgs(2),
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.Network().Names),
				cmpl.SuggestCandidates("delete"),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		opts, err := getChangeProtectionOpts(false, args[1:])
		if err != nil {
			return err
		}

		return changeProtection(s, cmd, network, false, opts)
	},
}
View Source
var EnableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "enable-protection [FLAGS] NETWORK PROTECTIONLEVEL [PROTECTIONLEVEL...]",
			Short: "Enable resource protection for a network",
			Args:  cobra.MinimumNArgs(2),
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.Network().Names),
				cmpl.SuggestCandidates("delete"),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		opts, err := getChangeProtectionOpts(true, args[1:])
		if err != nil {
			return err
		}

		return changeProtection(s, cmd, network, true, opts)
	},
}
View Source
var ExposeRoutesToVSwitchCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "expose-routes-to-vswitch [flags] network",
			Short:                 "Expose routes to connected vSwitch",
			Long:                  "Enabling this will expose routes to the connected vSwitch. Set the --disable flag to remove the exposed routes.",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().Bool("disable", false, "Remove any exposed routes from the connected vSwitch")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		disable, _ := cmd.Flags().GetBool("disable")
		opts := hcloud.NetworkUpdateOpts{
			ExposeRoutesToVSwitch: hcloud.Ptr(!disable),
		}

		_, _, err = s.Client().Network().Update(s, network, opts)
		if err != nil {
			return err
		}

		if disable {
			cmd.Printf("Exposing routes to connected vSwitch of network %s disabled\n", network.Name)
		} else {
			cmd.Printf("Exposing routes to connected vSwitch of network %s enabled\n", network.Name)
		}

		return nil
	},
}
View Source
var LabelCmds = base.LabelCmds{
	ResourceNameSingular:   "Network",
	ShortDescriptionAdd:    "Add a label to a Network",
	ShortDescriptionRemove: "Remove a label from a Network",
	NameSuggestions:        func(c hcapi2.Client) func() []string { return c.Network().Names },
	LabelKeySuggestions:    func(c hcapi2.Client) func(idOrName string) []string { return c.Network().LabelKeys },
	FetchLabels: func(s state.State, idOrName string) (map[string]string, int64, error) {
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return nil, 0, err
		}
		if network == nil {
			return nil, 0, fmt.Errorf("network not found: %s", idOrName)
		}
		return network.Labels, network.ID, nil
	},
	SetLabels: func(s state.State, id int64, labels map[string]string) error {
		opts := hcloud.NetworkUpdateOpts{
			Labels: labels,
		}
		_, _, err := s.Client().Network().Update(s, &hcloud.Network{ID: id}, opts)
		return err
	},
}
View Source
var ListCmd = base.ListCmd{
	ResourceNamePlural: "Networks",
	JSONKeyGetByName:   "networks",
	DefaultColumns:     []string{"id", "name", "ip_range", "servers", "age"},

	Fetch: func(s state.State, _ *pflag.FlagSet, listOpts hcloud.ListOpts, sorts []string) ([]interface{}, error) {
		opts := hcloud.NetworkListOpts{ListOpts: listOpts}
		if len(sorts) > 0 {
			opts.Sort = sorts
		}
		networks, err := s.Client().Network().AllWithOpts(s, opts)

		var resources []interface{}
		for _, n := range networks {
			resources = append(resources, n)
		}
		return resources, err
	},

	OutputTable: func(_ hcapi2.Client) *output.Table {
		return output.NewTable().
			AddAllowedFields(hcloud.Network{}).
			AddFieldFn("servers", output.FieldFn(func(obj interface{}) string {
				network := obj.(*hcloud.Network)
				serverCount := len(network.Servers)
				if serverCount <= 1 {
					return fmt.Sprintf("%v server", serverCount)
				}
				return fmt.Sprintf("%v servers", serverCount)
			})).
			AddFieldFn("ip_range", output.FieldFn(func(obj interface{}) string {
				network := obj.(*hcloud.Network)
				return network.IPRange.String()
			})).
			AddFieldFn("labels", output.FieldFn(func(obj interface{}) string {
				network := obj.(*hcloud.Network)
				return util.LabelsToString(network.Labels)
			})).
			AddFieldFn("protection", output.FieldFn(func(obj interface{}) string {
				network := obj.(*hcloud.Network)
				var protection []string
				if network.Protection.Delete {
					protection = append(protection, "delete")
				}
				return strings.Join(protection, ", ")
			})).
			AddFieldFn("created", output.FieldFn(func(obj interface{}) string {
				network := obj.(*hcloud.Network)
				return util.Datetime(network.Created)
			})).
			AddFieldFn("age", output.FieldFn(func(obj interface{}) string {
				network := obj.(*hcloud.Network)
				return util.Age(network.Created, time.Now())
			}))
	},
	Schema: func(resources []interface{}) interface{} {
		networkSchemas := make([]schema.Network, 0, len(resources))
		for _, resource := range resources {
			network := resource.(*hcloud.Network)
			networkSchemas = append(networkSchemas, hcloud.SchemaFromNetwork(network))
		}
		return networkSchemas
	},
}
View Source
var RemoveRouteCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "remove-route NETWORK FLAGS",
			Short:                 "Remove a route from a network",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}

		cmd.Flags().IPNet("destination", net.IPNet{}, "Destination network or host (required)")
		cmd.MarkFlagRequired("destination")

		cmd.Flags().IP("gateway", net.IP{}, "Gateway IP address (required)")
		cmd.MarkFlagRequired("gateway")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		gateway, _ := cmd.Flags().GetIP("gateway")
		destination, _ := cmd.Flags().GetIPNet("destination")
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		opts := hcloud.NetworkDeleteRouteOpts{
			Route: hcloud.NetworkRoute{
				Gateway:     gateway,
				Destination: &destination,
			},
		}
		action, _, err := s.Client().Network().DeleteRoute(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.ActionProgress(cmd, s, action); err != nil {
			return err
		}
		cmd.Printf("Route removed from network %d\n", network.ID)

		return nil
	},
}
View Source
var RemoveSubnetCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "remove-subnet NETWORK FLAGS",
			Short:                 "Remove a subnet from a network",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.Network().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().IPNet("ip-range", net.IPNet{}, "Subnet IP range (required)")
		cmd.MarkFlagRequired("ip-range")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		idOrName := args[0]
		network, _, err := s.Client().Network().Get(s, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		opts := hcloud.NetworkDeleteSubnetOpts{
			Subnet: hcloud.NetworkSubnet{
				IPRange: &ipRange,
			},
		}
		action, _, err := s.Client().Network().DeleteSubnet(s, network, opts)
		if err != nil {
			return err
		}
		if err := s.ActionProgress(cmd, s, action); err != nil {
			return err
		}
		cmd.Printf("Subnet %s removed from network %d\n", ipRange.String(), network.ID)

		return nil
	},
}
View Source
var UpdateCmd = base.UpdateCmd{
	ResourceNameSingular: "Network",
	ShortDescription:     "Update a Network.\n\nTo enable or disable exposing routes to the vSwitch connection you can use the subcommand \"hcloud network expose-routes-to-vswitch\".",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.Network().Names },
	Fetch: func(s state.State, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().Network().Get(s, idOrName)
	},
	DefineFlags: func(cmd *cobra.Command) {
		cmd.Flags().String("name", "", "Network name")
	},
	Update: func(s state.State, cmd *cobra.Command, resource interface{}, flags map[string]pflag.Value) error {
		floatingIP := resource.(*hcloud.Network)
		updOpts := hcloud.NetworkUpdateOpts{
			Name: flags["name"].String(),
		}
		_, _, err := s.Client().Network().Update(s, floatingIP, updOpts)
		if err != nil {
			return err
		}
		return nil
	},
}

Functions

func NewCommand

func NewCommand(s state.State) *cobra.Command

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL