network

package
v1.33.2 Latest Latest
Warning

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

Go to latest
Published: May 8, 2023 License: MIT Imports: 16 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 AddRouteCommand = 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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		gateway, _ := cmd.Flags().GetIP("gateway")
		destination, _ := cmd.Flags().GetIPNet("destination")
		idOrName := args[0]

		network, _, err := client.Network().Get(ctx, 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 := client.Network().AddRoute(ctx, network, opts)
		if err != nil {
			return err
		}
		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}
		fmt.Printf("Route added to network %d\n", network.ID)

		return nil
	},
}
View Source
var AddSubnetCommand = 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().Int("vswitch-id", 0, "ID of the vSwitch")
		return cmd
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, 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().GetInt("vswitch-id")
		idOrName := args[0]

		network, _, err := client.Network().Get(ctx, 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 := client.Network().AddSubnet(ctx, network, opts)
		if err != nil {
			return err
		}
		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}
		fmt.Printf("Subnet added to network %d\n", network.ID)

		return nil
	},
}
View Source
var ChangeIPRangeCommand = 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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := client.Network().Get(ctx, 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 := client.Network().ChangeIPRange(ctx, network, opts)
		if err != nil {
			return err
		}

		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}
		fmt.Printf("IP range of network %d changed\n", network.ID)
		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(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return client.Network().Get(ctx, idOrName)
	},
	PrintText: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, resource interface{}) error {
		network := resource.(*hcloud.Network)

		fmt.Printf("ID:\t\t%d\n", network.ID)
		fmt.Printf("Name:\t\t%s\n", network.Name)
		fmt.Printf("Created:\t%s (%s)\n", util.Datetime(network.Created), humanize.Time(network.Created))
		fmt.Printf("IP Range:\t%s\n", network.IPRange.String())

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

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

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

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

		return nil
	},
}

DescribeCmd defines a command for describing a network.

View Source
var DisableProtectionCommand = 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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := client.Network().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		var unknown []string
		opts := hcloud.NetworkChangeProtectionOpts{}
		for _, arg := range args[1:] {
			switch strings.ToLower(arg) {
			case "delete":
				opts.Delete = hcloud.Bool(false)
			default:
				unknown = append(unknown, arg)
			}
		}
		if len(unknown) > 0 {
			return fmt.Errorf("unknown protection level: %s", strings.Join(unknown, ", "))
		}

		action, _, err := client.Network().ChangeProtection(ctx, network, opts)
		if err != nil {
			return err
		}

		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}

		fmt.Printf("Resource protection disabled for network %d\n", network.ID)
		return nil
	},
}
View Source
var EnableProtectionCommand = 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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		network, _, err := client.Network().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if network == nil {
			return fmt.Errorf("network not found: %s", idOrName)
		}

		var unknown []string
		opts := hcloud.NetworkChangeProtectionOpts{}
		for _, arg := range args[1:] {
			switch strings.ToLower(arg) {
			case "delete":
				opts.Delete = hcloud.Bool(true)
			default:
				unknown = append(unknown, arg)
			}
		}
		if len(unknown) > 0 {
			return fmt.Errorf("unknown protection level: %s", strings.Join(unknown, ", "))
		}

		action, _, err := client.Network().ChangeProtection(ctx, network, opts)
		if err != nil {
			return err
		}

		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}

		fmt.Printf("Resource protection enabled for network %d\n", network.ID)
		return nil
	},
}
View Source
var ListCmd = base.ListCmd{
	ResourceNamePlural: "networks",
	DefaultColumns:     []string{"id", "name", "ip_range", "servers", "age"},

	Fetch: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, listOpts hcloud.ListOpts, sorts []string) ([]interface{}, error) {
		opts := hcloud.NetworkListOpts{ListOpts: listOpts}
		if len(sorts) > 0 {
			opts.Sort = sorts
		}
		networks, err := client.Network().AllWithOpts(ctx, 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())
			}))
	},

	JSONSchema: func(resources []interface{}) interface{} {
		var networkSchemas []schema.Network
		for _, resource := range resources {
			network := resource.(*hcloud.Network)

			networkSchema := schema.Network{
				ID:         network.ID,
				Name:       network.Name,
				IPRange:    network.IPRange.String(),
				Protection: schema.NetworkProtection{Delete: network.Protection.Delete},
				Created:    network.Created,
				Labels:     network.Labels,
			}
			for _, subnet := range network.Subnets {
				networkSchema.Subnets = append(networkSchema.Subnets, schema.NetworkSubnet{
					Type:        string(subnet.Type),
					IPRange:     subnet.IPRange.String(),
					NetworkZone: string(subnet.NetworkZone),
					Gateway:     subnet.Gateway.String(),
				})
			}
			for _, route := range network.Routes {
				networkSchema.Routes = append(networkSchema.Routes, schema.NetworkRoute{
					Destination: route.Destination.String(),
					Gateway:     route.Gateway.String(),
				})
			}
			for _, server := range network.Servers {
				networkSchema.Servers = append(networkSchema.Servers, server.ID)
			}
			networkSchemas = append(networkSchemas, networkSchema)
		}
		return networkSchemas
	},
}
View Source
var RemoveRouteCommand = 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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		gateway, _ := cmd.Flags().GetIP("gateway")
		destination, _ := cmd.Flags().GetIPNet("destination")
		idOrName := args[0]
		network, _, err := client.Network().Get(ctx, 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 := client.Network().DeleteRoute(ctx, network, opts)
		if err != nil {
			return err
		}
		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}
		fmt.Printf("Route removed from network %d\n", network.ID)

		return nil
	},
}
View Source
var RemoveSubnetCommand = 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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		ipRange, _ := cmd.Flags().GetIPNet("ip-range")
		idOrName := args[0]
		network, _, err := client.Network().Get(ctx, 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 := client.Network().DeleteSubnet(ctx, network, opts)
		if err != nil {
			return err
		}
		if err := waiter.ActionProgress(ctx, action); err != nil {
			return err
		}
		fmt.Printf("Subnet %s removed from network %d\n", ipRange.String(), network.ID)

		return nil
	},
}

Functions

func NewCommand

func NewCommand(cli *state.State, client hcapi2.Client) *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