File: utils.go

package info (click to toggle)
golang-github-gophercloud-utils 0.0~git20231010.80377ec-2
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 816 kB
  • sloc: sh: 20; makefile: 7
file content (50 lines) | stat: -rw-r--r-- 1,286 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package servers

import (
	"fmt"

	"github.com/gophercloud/gophercloud"
	"github.com/gophercloud/gophercloud/openstack/compute/v2/servers"
)

// IDFromName is a convenience function that returns a server's ID given its
// name. Errors when the number of items found is not one.
func IDFromName(client *gophercloud.ServiceClient, name string) (string, error) {
	IDs, err := IDsFromName(client, name)
	if err != nil {
		return "", err
	}

	switch count := len(IDs); count {
	case 0:
		return "", gophercloud.ErrResourceNotFound{Name: name, ResourceType: "server"}
	case 1:
		return IDs[0], nil
	default:
		return "", gophercloud.ErrMultipleResourcesFound{Name: name, Count: count, ResourceType: "server"}
	}
}

// IDsFromName returns zero or more IDs corresponding to a name. The returned
// error is only non-nil in case of failure.
func IDsFromName(client *gophercloud.ServiceClient, name string) ([]string, error) {
	pages, err := servers.List(client, servers.ListOpts{
		// nova list uses a name field as a regexp
		Name: fmt.Sprintf("^%s$", name),
	}).AllPages()
	if err != nil {
		return nil, err
	}

	all, err := servers.ExtractServers(pages)
	if err != nil {
		return nil, err
	}

	IDs := make([]string, len(all))
	for i := range all {
		IDs[i] = all[i].ID
	}

	return IDs, nil
}