-
Notifications
You must be signed in to change notification settings - Fork 162
/
host.go
79 lines (67 loc) · 2.03 KB
/
host.go
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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
package ssh
import (
"strconv"
boshdir "github.com/cloudfoundry/bosh-cli/v7/director"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
)
// You only need **one** of these per package!
//go:generate go run github.com/maxbrunsfeld/counterfeiter/v6 -generate
//counterfeiter:generate . HostBuilder
type HostBuilder interface {
BuildHost(slug boshdir.AllOrInstanceGroupOrInstanceSlug, username string, deploymentFetcher DeploymentFetcher) (boshdir.Host, error)
}
type hostBuilder struct{}
func NewHostBuilder() HostBuilder {
return &hostBuilder{}
}
type DeploymentFetcher func() (boshdir.Deployment, error)
func (h *hostBuilder) BuildHost(slug boshdir.AllOrInstanceGroupOrInstanceSlug, username string, deploymentFetcher DeploymentFetcher) (boshdir.Host, error) {
var targetHost string
if slug.IP() == "" {
deployment, err := deploymentFetcher()
if err != nil {
return boshdir.Host{}, err
}
vms, err := deployment.VMInfos()
if err != nil {
return boshdir.Host{}, bosherr.WrapErrorf(err, "Finding VM for %s", slug)
}
var targetVM boshdir.VMInfo
indexOrId := slug.IndexOrID()
for _, vm := range vms {
if vm.Active == nil || !*vm.Active {
continue
}
if vm.JobName == slug.Name() {
if indexOrId == "" {
if targetVM.JobName != "" {
return boshdir.Host{}, bosherr.Errorf("Instance %s refers to more than 1 VM", slug)
} else {
targetVM = vm
}
} else if index, err := strconv.Atoi(indexOrId); err == nil && index == *vm.Index {
targetVM = vm
break
} else if indexOrId == vm.ID {
targetVM = vm
break
}
}
}
if targetVM.JobName == "" {
return boshdir.Host{}, bosherr.Errorf("Instance %s has no active VM", slug)
}
if targetVM.IPs == nil || len(targetVM.IPs) == 0 {
return boshdir.Host{}, bosherr.Errorf("VM %s has no IP address", targetVM.VMID)
}
targetHost = targetVM.IPs[0]
} else {
targetHost = slug.IP()
}
return boshdir.Host{
Job: slug.Name(),
IndexOrID: slug.IndexOrID(),
Username: username,
Host: targetHost,
}, nil
}