floatingip

package
v1.40.0 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2023 License: MIT Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var AssignCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "assign [FLAGS] FLOATINGIP SERVER",
			Short: "Assign a Floating IP to a server",
			Args:  cobra.ExactArgs(2),
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.FloatingIP().Names),
				cmpl.SuggestCandidatesF(client.Server().Names),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		floatingIP, _, err := client.FloatingIP().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if floatingIP == nil {
			return fmt.Errorf("Floating IP not found: %v", idOrName)
		}

		serverIDOrName := args[1]
		server, _, err := client.Server().Get(ctx, serverIDOrName)
		if err != nil {
			return err
		}
		if server == nil {
			return fmt.Errorf("server not found: %s", serverIDOrName)
		}

		action, _, err := client.FloatingIP().Assign(ctx, floatingIP, server)
		if err != nil {
			return err
		}

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

		cmd.Printf("Floating IP %d assigned to server %d\n", floatingIP.ID, server.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 Floating IP",
			Args:                  cobra.NoArgs,
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("type", "", "Type (ipv4 or ipv6) (required)")
		cmd.RegisterFlagCompletionFunc("type", cmpl.SuggestCandidates("ipv4", "ipv6"))
		cmd.MarkFlagRequired("type")

		cmd.Flags().String("description", "", "Description")

		cmd.Flags().String("name", "", "Name")

		cmd.Flags().String("home-location", "", "Home location")
		cmd.RegisterFlagCompletionFunc("home-location", cmpl.SuggestCandidatesF(client.Location().Names))

		cmd.Flags().String("server", "", "Server to assign Floating IP to")
		cmd.RegisterFlagCompletionFunc("server", cmpl.SuggestCandidatesF(client.Server().Names))

		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(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) (*hcloud.Response, any, error) {
		typ, _ := cmd.Flags().GetString("type")
		if typ == "" {
			return nil, nil, errors.New("type is required")
		}

		homeLocation, _ := cmd.Flags().GetString("home-location")
		server, _ := cmd.Flags().GetString("server")
		if homeLocation == "" && server == "" {
			return nil, nil, errors.New("one of --home-location or --server is required")
		}

		name, _ := cmd.Flags().GetString("name")
		description, _ := cmd.Flags().GetString("description")
		serverNameOrID, _ := cmd.Flags().GetString("server")
		labels, _ := cmd.Flags().GetStringToString("label")
		protection, _ := cmd.Flags().GetStringSlice("enable-protection")

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

		createOpts := hcloud.FloatingIPCreateOpts{
			Type:        hcloud.FloatingIPType(typ),
			Description: &description,
			Labels:      labels,
		}
		if name != "" {
			createOpts.Name = &name
		}
		if homeLocation != "" {
			createOpts.HomeLocation = &hcloud.Location{Name: homeLocation}
		}
		if serverNameOrID != "" {
			server, _, err := client.Server().Get(ctx, serverNameOrID)
			if err != nil {
				return nil, nil, err
			}
			if server == nil {
				return nil, nil, fmt.Errorf("server not found: %s", serverNameOrID)
			}
			createOpts.Server = server
		}

		result, response, err := client.FloatingIP().Create(ctx, createOpts)
		if err != nil {
			return nil, nil, err
		}

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

		cmd.Printf("Floating IP %d created\n", result.FloatingIP.ID)

		if err := changeProtection(ctx, client, waiter, cmd, result.FloatingIP, true, protectionOps); err != nil {
			return nil, nil, err
		}

		return response, result.FloatingIP, nil
	},

	PrintResource: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, resource any) {
		floatingIP := resource.(*hcloud.FloatingIP)
		cmd.Printf("IP%s: %s\n", floatingIP.Type[2:], floatingIP.IP)
	},
}
View Source
var DeleteCmd = base.DeleteCmd{
	ResourceNameSingular: "Floating IP",
	ShortDescription:     "Delete a Floating IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.FloatingIP().Names },
	Fetch: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return client.FloatingIP().Get(ctx, idOrName)
	},
	Delete: func(ctx context.Context, client hcapi2.Client, _ state.ActionWaiter, cmd *cobra.Command, resource interface{}) error {
		floatingIP := resource.(*hcloud.FloatingIP)
		if _, err := client.FloatingIP().Delete(ctx, floatingIP); err != nil {
			return err
		}
		return nil
	},
}
View Source
var DescribeCmd = base.DescribeCmd{
	ResourceNameSingular: "Floating IP",
	ShortDescription:     "Describe an Floating IP",
	JSONKeyGetByID:       "floating_ip",
	JSONKeyGetByName:     "floating_ips",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.FloatingIP().Names },
	Fetch: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return client.FloatingIP().Get(ctx, idOrName)
	},
	PrintText: func(_ context.Context, client hcapi2.Client, cmd *cobra.Command, resource interface{}) error {
		floatingIP := resource.(*hcloud.FloatingIP)

		cmd.Printf("ID:\t\t%d\n", floatingIP.ID)
		cmd.Printf("Type:\t\t%s\n", floatingIP.Type)
		cmd.Printf("Name:\t\t%s\n", floatingIP.Name)
		cmd.Printf("Description:\t%s\n", util.NA(floatingIP.Description))
		cmd.Printf("Created:\t%s (%s)\n", util.Datetime(floatingIP.Created), humanize.Time(floatingIP.Created))
		if floatingIP.Network != nil {
			cmd.Printf("IP:\t\t%s\n", floatingIP.Network.String())
		} else {
			cmd.Printf("IP:\t\t%s\n", floatingIP.IP.String())
		}
		cmd.Printf("Blocked:\t%s\n", util.YesNo(floatingIP.Blocked))
		cmd.Printf("Home Location:\t%s\n", floatingIP.HomeLocation.Name)
		if floatingIP.Server != nil {
			cmd.Printf("Server:\n")
			cmd.Printf("  ID:\t%d\n", floatingIP.Server.ID)
			cmd.Printf("  Name:\t%s\n", client.Server().ServerName(floatingIP.Server.ID))
		} else {
			cmd.Print("Server:\n  Not assigned\n")
		}
		cmd.Print("DNS:\n")
		if len(floatingIP.DNSPtr) == 0 {
			cmd.Print("  No reverse DNS entries\n")
		} else {
			for ip, dns := range floatingIP.DNSPtr {
				cmd.Printf("  %s: %s\n", ip, dns)
			}
		}

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

		cmd.Print("Labels:\n")
		if len(floatingIP.Labels) == 0 {
			cmd.Print("  No labels\n")
		} else {
			for key, value := range floatingIP.Labels {
				cmd.Printf("  %s: %s\n", key, value)
			}
		}
		return nil
	},
}
View Source
var DisableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "disable-protection [FLAGS] FLOATINGIP PROTECTIONLEVEL [PROTECTIONLEVEL...]",
			Short: "Disable resource protection for a Floating IP",
			Args:  cobra.MinimumNArgs(2),
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.FloatingIP().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]
		floatingIP, _, err := client.FloatingIP().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if floatingIP == nil {
			return fmt.Errorf("Floating IP not found: %v", idOrName)
		}

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

		return changeProtection(ctx, client, waiter, cmd, floatingIP, false, opts)
	},
}
View Source
var EnableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:   "enable-protection [FLAGS] FLOATINGIP PROTECTIONLEVEL [PROTECTIONLEVEL...]",
			Short: "Enable resource protection for a Floating IP",
			Args:  cobra.MinimumNArgs(2),
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.FloatingIP().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]
		floatingIP, _, err := client.FloatingIP().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if floatingIP == nil {
			return fmt.Errorf("Floating IP not found: %v", idOrName)
		}

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

		return changeProtection(ctx, client, waiter, cmd, floatingIP, true, opts)
	},
}
View Source
var LabelCmds = base.LabelCmds{
	ResourceNameSingular:   "Floating IP",
	ShortDescriptionAdd:    "Add a label to an Floating IP",
	ShortDescriptionRemove: "Remove a label from an Floating IP",
	NameSuggestions:        func(c hcapi2.Client) func() []string { return c.FloatingIP().Names },
	LabelKeySuggestions:    func(c hcapi2.Client) func(idOrName string) []string { return c.FloatingIP().LabelKeys },
	FetchLabels: func(ctx context.Context, client hcapi2.Client, idOrName string) (map[string]string, int64, error) {
		floatingIP, _, err := client.FloatingIP().Get(ctx, idOrName)
		if err != nil {
			return nil, 0, err
		}
		if floatingIP == nil {
			return nil, 0, fmt.Errorf("floating IP not found: %s", idOrName)
		}
		return floatingIP.Labels, floatingIP.ID, nil
	},
	SetLabels: func(ctx context.Context, client hcapi2.Client, id int64, labels map[string]string) error {
		opts := hcloud.FloatingIPUpdateOpts{
			Labels: labels,
		}
		_, _, err := client.FloatingIP().Update(ctx, &hcloud.FloatingIP{ID: id}, opts)
		return err
	},
}
View Source
var ListCmd = base.ListCmd{
	ResourceNamePlural: "Floating IPs",
	JSONKeyGetByName:   "floating_ips",
	DefaultColumns:     []string{"id", "type", "name", "description", "ip", "home", "server", "dns", "age"},

	Fetch: func(ctx context.Context, client hcapi2.Client, _ *pflag.FlagSet, listOpts hcloud.ListOpts, sorts []string) ([]interface{}, error) {
		opts := hcloud.FloatingIPListOpts{ListOpts: listOpts}
		if len(sorts) > 0 {
			opts.Sort = sorts
		}
		floatingIPs, err := client.FloatingIP().AllWithOpts(ctx, opts)

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

	OutputTable: func(client hcapi2.Client) *output.Table {
		return output.NewTable().
			AddAllowedFields(hcloud.FloatingIP{}).
			AddFieldFn("dns", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				var dns string
				if len(floatingIP.DNSPtr) == 1 {
					for _, v := range floatingIP.DNSPtr {
						dns = v
					}
				}
				if len(floatingIP.DNSPtr) > 1 {
					dns = fmt.Sprintf("%d entries", len(floatingIP.DNSPtr))
				}
				return util.NA(dns)
			})).
			AddFieldFn("server", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				var server string
				if floatingIP.Server != nil {
					return client.Server().ServerName(floatingIP.Server.ID)
				}
				return util.NA(server)
			})).
			AddFieldFn("home", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				return floatingIP.HomeLocation.Name
			})).
			AddFieldFn("ip", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)

				if floatingIP.Network != nil {
					return floatingIP.Network.String()
				}
				return floatingIP.IP.String()
			})).
			AddFieldFn("protection", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				var protection []string
				if floatingIP.Protection.Delete {
					protection = append(protection, "delete")
				}
				return strings.Join(protection, ", ")
			})).
			AddFieldFn("labels", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				return util.LabelsToString(floatingIP.Labels)
			})).
			AddFieldFn("created", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				return util.Datetime(floatingIP.Created)
			})).
			AddFieldFn("age", output.FieldFn(func(obj interface{}) string {
				floatingIP := obj.(*hcloud.FloatingIP)
				return util.Age(floatingIP.Created, time.Now())
			}))
	},

	JSONSchema: func(resources []interface{}) interface{} {
		floatingIPSchemas := make([]schema.FloatingIP, 0, len(resources))
		for _, resource := range resources {
			floatingIP := resource.(*hcloud.FloatingIP)
			floatingIPSchema := schema.FloatingIP{
				ID:           floatingIP.ID,
				Name:         floatingIP.Name,
				Description:  hcloud.String(floatingIP.Description),
				IP:           floatingIP.IP.String(),
				Created:      floatingIP.Created,
				Type:         string(floatingIP.Type),
				HomeLocation: util.LocationToSchema(*floatingIP.HomeLocation),
				Blocked:      floatingIP.Blocked,
				Protection:   schema.FloatingIPProtection{Delete: floatingIP.Protection.Delete},
				Labels:       floatingIP.Labels,
			}
			for ip, dnsPtr := range floatingIP.DNSPtr {
				floatingIPSchema.DNSPtr = append(floatingIPSchema.DNSPtr, schema.FloatingIPDNSPtr{
					IP:     ip,
					DNSPtr: dnsPtr,
				})
			}
			if floatingIP.Server != nil {
				floatingIPSchema.Server = hcloud.Ptr(floatingIP.Server.ID)
			}
			floatingIPSchemas = append(floatingIPSchemas, floatingIPSchema)
		}
		return floatingIPSchemas
	},
}
View Source
var SetRDNSCmd = base.SetRdnsCmd{
	ResourceNameSingular: "Floating IP",
	ShortDescription:     "Change reverse DNS of a Floating IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.FloatingIP().Names },
	Fetch: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return client.FloatingIP().Get(ctx, idOrName)
	},
	GetDefaultIP: func(resource interface{}) net.IP {
		floatingIP := resource.(*hcloud.FloatingIP)
		return floatingIP.IP
	},
}
View Source
var UnassignCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		return &cobra.Command{
			Use:                   "unassign [FLAGS] FLOATINGIP",
			Short:                 "Unassign a Floating IP",
			Args:                  cobra.ExactArgs(1),
			ValidArgsFunction:     cmpl.SuggestArgs(cmpl.SuggestCandidatesF(client.FloatingIP().Names)),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
	},
	Run: func(ctx context.Context, client hcapi2.Client, waiter state.ActionWaiter, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		floatingIP, _, err := client.FloatingIP().Get(ctx, idOrName)
		if err != nil {
			return err
		}
		if floatingIP == nil {
			return fmt.Errorf("Floating IP not found: %v", idOrName)
		}

		action, _, err := client.FloatingIP().Unassign(ctx, floatingIP)
		if err != nil {
			return err
		}

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

		cmd.Printf("Floating IP %d unassigned\n", floatingIP.ID)
		return nil
	},
}
View Source
var UpdateCmd = base.UpdateCmd{
	ResourceNameSingular: "Floating IP",
	ShortDescription:     "Update a Floating IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.FloatingIP().Names },
	Fetch: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return client.FloatingIP().Get(ctx, idOrName)
	},
	DefineFlags: func(cmd *cobra.Command) {
		cmd.Flags().String("name", "", "Floating IP name")
		cmd.Flags().String("description", "", "Floating IP description")
	},
	Update: func(ctx context.Context, client hcapi2.Client, cmd *cobra.Command, resource interface{}, flags map[string]pflag.Value) error {
		floatingIP := resource.(*hcloud.FloatingIP)
		updOpts := hcloud.FloatingIPUpdateOpts{
			Name:        flags["name"].String(),
			Description: flags["description"].String(),
		}
		_, _, err := client.FloatingIP().Update(ctx, floatingIP, updOpts)
		if err != nil {
			return err
		}
		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