primaryip

package
v1.49.0 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2024 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 AssignCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "assign --server <server> <primary-ip>",
			Short: "Assign a Primary IP to an assignee (usually a server)",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.PrimaryIP().Names),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		cmd.Flags().String("server", "", "Name or ID of the server")
		_ = cmd.RegisterFlagCompletionFunc("server", cmpl.SuggestCandidatesF(client.Server().Names))
		_ = cmd.MarkFlagRequired("server")
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return err
		}
		if primaryIP == nil {
			return fmt.Errorf("Primary IP not found: %v", idOrName)
		}

		serverIDOrName, _ := cmd.Flags().GetString("server")

		server, _, err := s.Client().Server().Get(s, serverIDOrName)
		if err != nil {
			return err
		}
		if server == nil {
			return fmt.Errorf("server not found: %s", serverIDOrName)
		}
		opts := hcloud.PrimaryIPAssignOpts{
			ID:           primaryIP.ID,
			AssigneeType: "server",
			AssigneeID:   server.ID,
		}

		action, _, err := s.Client().PrimaryIP().Assign(s, opts)
		if err != nil {
			return err
		}

		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}

		cmd.Printf("Primary IP %d assigned to %s %d\n", opts.ID, opts.AssigneeType, opts.AssigneeID)
		return nil
	},
}
View Source
var CreateCmd = base.CreateCmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:                   "create [options] --type <ipv4|ipv6> --name <name>",
			Short:                 "Create a Primary IP",
			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("name", "", "Name (required)")
		_ = cmd.MarkFlagRequired("name")

		cmd.Flags().Int64("assignee-id", 0, "Assignee (usually a server) to assign Primary IP to")

		cmd.Flags().String("datacenter", "", "Datacenter (ID or name)")
		_ = cmd.RegisterFlagCompletionFunc("datacenter", cmpl.SuggestCandidatesF(client.Datacenter().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"))

		cmd.Flags().Bool("auto-delete", false, "Delete Primary IP if assigned resource is deleted")

		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, _ []string) (any, any, error) {
		typ, _ := cmd.Flags().GetString("type")
		name, _ := cmd.Flags().GetString("name")
		assigneeID, _ := cmd.Flags().GetInt64("assignee-id")
		datacenter, _ := cmd.Flags().GetString("datacenter")
		labels, _ := cmd.Flags().GetStringToString("label")
		protection, _ := cmd.Flags().GetStringSlice("enable-protection")
		autoDelete, _ := cmd.Flags().GetBool("auto-delete")

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

		createOpts := hcloud.PrimaryIPCreateOpts{
			Type:         hcloud.PrimaryIPType(typ),
			Name:         name,
			AssigneeType: "server",
			Datacenter:   datacenter,
			Labels:       labels,
		}
		if assigneeID != 0 {
			createOpts.AssigneeID = &assigneeID
		}
		if cmd.Flags().Changed("auto-delete") {
			createOpts.AutoDelete = &autoDelete
		}

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

		if result.Action != nil {
			if err := s.WaitForActions(s, cmd, result.Action); err != nil {
				return nil, nil, err
			}
		}

		cmd.Printf("Primary IP %d created\n", result.PrimaryIP.ID)

		if len(protection) > 0 {
			if err := changeProtection(s, cmd, result.PrimaryIP, true, protectionOpts); err != nil {
				return nil, nil, err
			}
		}

		return result.PrimaryIP, util.Wrap("primary_ip", hcloud.SchemaFromPrimaryIP(result.PrimaryIP)), nil
	},
	PrintResource: func(_ state.State, cmd *cobra.Command, resource any) {
		primaryIP := resource.(*hcloud.PrimaryIP)
		cmd.Printf("IP%s: %s\n", primaryIP.Type[2:], primaryIP.IP)
	},
}
View Source
var DeleteCmd = base.DeleteCmd{
	ResourceNameSingular: "Primary IP",
	ResourceNamePlural:   "Primary IPs",
	ShortDescription:     "Delete a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},
	Delete: func(s state.State, _ *cobra.Command, resource interface{}) (*hcloud.Action, error) {
		primaryIP := resource.(*hcloud.PrimaryIP)
		_, err := s.Client().PrimaryIP().Delete(s, primaryIP)
		return nil, err
	},
}
View Source
var DescribeCmd = base.DescribeCmd{
	ResourceNameSingular: "Primary IP",
	ShortDescription:     "Describe an Primary IP",
	JSONKeyGetByID:       "primary_ip",
	JSONKeyGetByName:     "primary_ips",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (interface{}, interface{}, error) {
		ip, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return nil, nil, err
		}
		return ip, hcloud.SchemaFromPrimaryIP(ip), nil
	},
	PrintText: func(_ state.State, cmd *cobra.Command, resource interface{}) error {
		primaryIP := resource.(*hcloud.PrimaryIP)

		cmd.Printf("ID:\t\t%d\n", primaryIP.ID)
		cmd.Printf("Name:\t\t%s\n", primaryIP.Name)
		cmd.Printf("Created:\t%s (%s)\n", util.Datetime(primaryIP.Created), humanize.Time(primaryIP.Created))
		cmd.Printf("Type:\t\t%s\n", primaryIP.Type)
		cmd.Printf("IP:\t\t%s\n", primaryIP.IP.String())
		cmd.Printf("Blocked:\t%s\n", util.YesNo(primaryIP.Blocked))
		cmd.Printf("Auto delete:\t%s\n", util.YesNo(primaryIP.AutoDelete))
		if primaryIP.AssigneeID != 0 {
			cmd.Printf("Assignee:\n")
			cmd.Printf("  ID:\t%d\n", primaryIP.AssigneeID)
			cmd.Printf("  Type:\t%s\n", primaryIP.AssigneeType)
		} else {
			cmd.Print("Assignee:\n  Not assigned\n")
		}
		cmd.Print("DNS:\n")
		if len(primaryIP.DNSPtr) == 0 {
			cmd.Print("  No reverse DNS entries\n")
		} else {
			for ip, dns := range primaryIP.DNSPtr {
				cmd.Printf("  %s: %s\n", ip, dns)
			}
		}

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

		cmd.Print("Labels:\n")
		if len(primaryIP.Labels) == 0 {
			cmd.Print("  No labels\n")
		} else {
			for key, value := range primaryIP.Labels {
				cmd.Printf("  %s: %s\n", key, value)
			}
		}
		cmd.Printf("Datacenter:\n")
		cmd.Printf("  ID:\t\t%d\n", primaryIP.Datacenter.ID)
		cmd.Printf("  Name:\t\t%s\n", primaryIP.Datacenter.Name)
		cmd.Printf("  Description:\t%s\n", primaryIP.Datacenter.Description)
		cmd.Printf("  Location:\n")
		cmd.Printf("    Name:\t\t%s\n", primaryIP.Datacenter.Location.Name)
		cmd.Printf("    Description:\t%s\n", primaryIP.Datacenter.Location.Description)
		cmd.Printf("    Country:\t\t%s\n", primaryIP.Datacenter.Location.Country)
		cmd.Printf("    City:\t\t%s\n", primaryIP.Datacenter.Location.City)
		cmd.Printf("    Latitude:\t\t%f\n", primaryIP.Datacenter.Location.Latitude)
		cmd.Printf("    Longitude:\t\t%f\n", primaryIP.Datacenter.Location.Longitude)
		return nil
	},
}
View Source
var DisableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "disable-protection <primary-ip> [<protection-level>...]",
			Args:  util.ValidateLenient,
			Short: "Disable Protection for a Primary IP",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.PrimaryIP().Names),
				cmpl.SuggestCandidates("delete"),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return err
		}
		if primaryIP == nil {
			return fmt.Errorf("Primary IP not found: %v", idOrName)
		}

		if len(args) < 2 {
			args = append(args, "delete")
		}

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

		return changeProtection(s, cmd, primaryIP, false, opts)
	},
}
View Source
var EnableProtectionCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "enable-protection <primary-ip> [<protection-level>...]",
			Args:  util.ValidateLenient,
			Short: "Enable Protection for a Primary IP",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.PrimaryIP().Names),
				cmpl.SuggestCandidates("delete"),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return err
		}
		if primaryIP == nil {
			return fmt.Errorf("Primary IP not found: %v", idOrName)
		}

		if len(args) < 2 {
			args = append(args, "delete")
		}

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

		return changeProtection(s, cmd, primaryIP, true, opts)
	},
}
View Source
var LabelCmds = base.LabelCmds{
	ResourceNameSingular:   "primary-ip",
	ShortDescriptionAdd:    "Add a label to a Primary IP",
	ShortDescriptionRemove: "Remove a label from a Primary IP",
	NameSuggestions:        func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names },
	LabelKeySuggestions:    func(c hcapi2.Client) func(idOrName string) []string { return c.PrimaryIP().LabelKeys },
	FetchLabels: func(s state.State, idOrName string) (map[string]string, int64, error) {
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return nil, 0, err
		}
		if primaryIP == nil {
			return nil, 0, fmt.Errorf("primaryIP not found: %s", idOrName)
		}
		return primaryIP.Labels, primaryIP.ID, nil
	},
	SetLabels: func(s state.State, id int64, labels map[string]string) error {
		opts := hcloud.PrimaryIPUpdateOpts{
			Labels: &labels,
		}
		_, _, err := s.Client().PrimaryIP().Update(s, &hcloud.PrimaryIP{ID: id}, opts)
		return err
	},
}
View Source
var ListCmd = base.ListCmd{
	ResourceNamePlural: "Primary IPs",
	JSONKeyGetByName:   "primary_ips",
	DefaultColumns:     []string{"id", "type", "name", "ip", "assignee", "dns", "auto_delete", "age"},
	SortOption:         config.OptionSortPrimaryIP,

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

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

	OutputTable: func(t *output.Table, client hcapi2.Client) {
		t.
			AddAllowedFields(hcloud.PrimaryIP{}).
			AddFieldFn("ip", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)

				if primaryIP.Network != nil {
					return primaryIP.Network.String()
				}
				return primaryIP.IP.String()
			})).
			AddFieldFn("dns", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				var dns string
				if len(primaryIP.DNSPtr) == 1 {
					for _, v := range primaryIP.DNSPtr {
						dns = v
					}
				}
				if len(primaryIP.DNSPtr) > 1 {
					dns = fmt.Sprintf("%d entries", len(primaryIP.DNSPtr))
				}
				return util.NA(dns)
			})).
			AddFieldFn("assignee", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				assignee := ""
				if primaryIP.AssigneeID != 0 {
					switch primaryIP.AssigneeType {
					case "server":
						assignee = fmt.Sprintf("Server %s", client.Server().ServerName(primaryIP.AssigneeID))
					}
				}
				return util.NA(assignee)
			})).
			AddFieldFn("protection", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				var protection []string
				if primaryIP.Protection.Delete {
					protection = append(protection, "delete")
				}
				return strings.Join(protection, ", ")
			})).
			AddFieldFn("auto_delete", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				return util.YesNo(primaryIP.AutoDelete)
			})).
			AddFieldFn("labels", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				return util.LabelsToString(primaryIP.Labels)
			})).
			AddFieldFn("created", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				return util.Datetime(primaryIP.Created)
			})).
			AddFieldFn("age", output.FieldFn(func(obj interface{}) string {
				primaryIP := obj.(*hcloud.PrimaryIP)
				return util.Age(primaryIP.Created, time.Now())
			}))
	},

	Schema: func(resources []interface{}) interface{} {
		primaryIPsSchema := make([]schema.PrimaryIP, 0, len(resources))
		for _, resource := range resources {
			primaryIP := resource.(*hcloud.PrimaryIP)
			primaryIPsSchema = append(primaryIPsSchema, hcloud.SchemaFromPrimaryIP(primaryIP))
		}
		return primaryIPsSchema
	},
}
View Source
var SetRDNSCmd = base.SetRdnsCmd{
	ResourceNameSingular: "Primary IP",
	ShortDescription:     "Change reverse DNS of a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},
	GetDefaultIP: func(resource interface{}) net.IP {
		primaryIP := resource.(*hcloud.PrimaryIP)
		return primaryIP.IP
	},
}
View Source
var UnAssignCmd = base.Cmd{
	BaseCobraCommand: func(client hcapi2.Client) *cobra.Command {
		cmd := &cobra.Command{
			Use:   "unassign <primary-ip>",
			Short: "Unassign a Primary IP from an assignee (usually a server)",
			ValidArgsFunction: cmpl.SuggestArgs(
				cmpl.SuggestCandidatesF(client.PrimaryIP().Names),
			),
			TraverseChildren:      true,
			DisableFlagsInUseLine: true,
		}
		return cmd
	},
	Run: func(s state.State, cmd *cobra.Command, args []string) error {
		idOrName := args[0]
		primaryIP, _, err := s.Client().PrimaryIP().Get(s, idOrName)
		if err != nil {
			return err
		}
		if primaryIP == nil {
			return fmt.Errorf("Primary IP not found: %v", idOrName)
		}

		action, _, err := s.Client().PrimaryIP().Unassign(s, primaryIP.ID)
		if err != nil {
			return err
		}

		if err := s.WaitForActions(s, cmd, action); err != nil {
			return err
		}

		cmd.Printf("Primary IP %d was unassigned successfully\n", primaryIP.ID)
		return nil
	},
}
View Source
var UpdateCmd = base.UpdateCmd{
	ResourceNameSingular: "Primary IP",
	ShortDescription:     "Update a Primary IP",
	NameSuggestions:      func(c hcapi2.Client) func() []string { return c.PrimaryIP().Names },
	Fetch: func(s state.State, _ *cobra.Command, idOrName string) (interface{}, *hcloud.Response, error) {
		return s.Client().PrimaryIP().Get(s, idOrName)
	},
	DefineFlags: func(cmd *cobra.Command) {
		cmd.Flags().String("name", "", "Primary IP name")
		cmd.Flags().Bool("auto-delete", false, "Delete this Primary IP when the resource it is assigned to is deleted")
	},
	Update: func(s state.State, cmd *cobra.Command, resource interface{}, flags map[string]pflag.Value) error {
		primaryIP := resource.(*hcloud.PrimaryIP)
		updOpts := hcloud.PrimaryIPUpdateOpts{
			Name: flags["name"].String(),
		}

		if cmd.Flags().Changed("auto-delete") {
			autoDelete, _ := cmd.Flags().GetBool("auto-delete")
			updOpts.AutoDelete = hcloud.Ptr(autoDelete)
		}

		_, _, err := s.Client().PrimaryIP().Update(s, primaryIP, 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