File: api_vcd.go

package info (click to toggle)
golang-github-hmrc-vmware-govcd 0.0.2%2Bgit20190404.eea2584-3
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, forky, sid, trixie
  • size: 516 kB
  • sloc: sh: 32; makefile: 2
file content (245 lines) | stat: -rw-r--r-- 6,088 bytes parent folder | download | duplicates (2)
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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
package govcd

import (
	"crypto/tls"
	"fmt"
	"net/http"
	"net/url"
	"os"
	"sync"
	"time"
)

type VCDClient struct {
	OrgHREF     url.URL // vCloud Director OrgRef
	Org         Org     // Org
	OrgVdc      Vdc     // Org vDC
	Client      Client  // Client for the underlying VCD instance
	sessionHREF url.URL // HREF for the session API
	QueryHREF   url.URL // HREF for the query API
	Mutex       sync.Mutex
}

type supportedVersions struct {
	VersionInfo struct {
		Version  string `xml:"Version"`
		LoginUrl string `xml:"LoginUrl"`
	} `xml:"VersionInfo"`
}

func (c *VCDClient) vcdloginurl() error {

	s := c.Client.VCDVDCHREF
	s.Path += "/versions"

	// No point in checking for errors here
	req := c.Client.NewRequest(map[string]string{}, "GET", s, nil)

	resp, err := checkResp(c.Client.Http.Do(req))
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	supportedVersions := new(supportedVersions)

	err = decodeBody(resp, supportedVersions)

	if err != nil {
		return fmt.Errorf("error decoding versions response: %s", err)
	}

	u, err := url.Parse(supportedVersions.VersionInfo.LoginUrl)
	if err != nil {
		return fmt.Errorf("couldn't find a LoginUrl in versions")
	}
	c.sessionHREF = *u
	return nil
}

func (c *VCDClient) vcdauthorize(user, pass, org string) error {

	if user == "" {
		user = os.Getenv("VCLOUD_USERNAME")
	}

	if pass == "" {
		pass = os.Getenv("VCLOUD_PASSWORD")
	}

	if org == "" {
		org = os.Getenv("VCLOUD_ORG")
	}

	// No point in checking for errors here
	req := c.Client.NewRequest(map[string]string{}, "POST", c.sessionHREF, nil)

	// Set Basic Authentication Header
	req.SetBasicAuth(user+"@"+org, pass)

	// Add the Accept header for vCA
	req.Header.Add("Accept", "application/*+xml;version=5.5")

	resp, err := checkResp(c.Client.Http.Do(req))
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	// Store the authentication header
	c.Client.VCDToken = resp.Header.Get("x-vcloud-authorization")
	c.Client.VCDAuthHeader = "x-vcloud-authorization"

	session := new(session)
	err = decodeBody(resp, session)

	if err != nil {
		fmt.Errorf("error decoding session response: %s", err)
	}

	org_found := false
	// Loop in the session struct to find the organization and query api.
	for _, s := range session.Link {
		if s.Type == "application/vnd.vmware.vcloud.org+xml" && s.Rel == "down" {
			u, err := url.Parse(s.HREF)
			if err != nil {
				return fmt.Errorf("couldn't find a Organization in current session, %v", err)
			}
			c.OrgHREF = *u
			org_found = true
		}
		if s.Type == "application/vnd.vmware.vcloud.query.queryList+xml" && s.Rel == "down" {
			u, err := url.Parse(s.HREF)
			if err != nil {
				return fmt.Errorf("couldn't find a Query API in current session, %v", err)
			}
			c.QueryHREF = *u
		}
	}
	if !org_found {
		return fmt.Errorf("couldn't find a Organization in current session")
	}

	// Loop in the session struct to find the session url.
	session_found := false
	for _, s := range session.Link {
		if s.Rel == "remove" {
			u, err := url.Parse(s.HREF)
			if err != nil {
				return fmt.Errorf("couldn't find a logout HREF in current session, %v", err)
			}
			c.sessionHREF = *u
			session_found = true
		}
	}
	if !session_found {
		return fmt.Errorf("couldn't find a logout HREF in current session")
	}
	return nil
}

func (c *VCDClient) RetrieveOrg(vcdname string) (Org, error) {

	req := c.Client.NewRequest(map[string]string{}, "GET", c.OrgHREF, nil)
	req.Header.Add("Accept", "vnd.vmware.vcloud.org+xml;version=5.5")

	// TODO: wrap into checkresp to parse error
	resp, err := checkResp(c.Client.Http.Do(req))
	if err != nil {
		return Org{}, fmt.Errorf("error retreiving org: %s", err)
	}

	org := NewOrg(&c.Client)

	if err = decodeBody(resp, org.Org); err != nil {
		return Org{}, fmt.Errorf("error decoding org response: %s", err)
	}

	// Get the VDC ref from the Org
	for _, s := range org.Org.Link {
		if s.Type == "application/vnd.vmware.vcloud.vdc+xml" && s.Rel == "down" {
			if vcdname != "" && s.Name != vcdname {
				continue
			}
			u, err := url.Parse(s.HREF)
			if err != nil {
				return Org{}, err
			}
			c.Client.VCDVDCHREF = *u
		}
	}

	if &c.Client.VCDVDCHREF == nil {
		return Org{}, fmt.Errorf("error finding the organization VDC HREF")
	}

	return *org, nil
}

func NewVCDClient(vcdEndpoint url.URL, insecure bool) *VCDClient {

	return &VCDClient{
		Client: Client{
			APIVersion: "5.5",
			VCDVDCHREF: vcdEndpoint,
			Http: http.Client{
				Transport: &http.Transport{
					TLSClientConfig: &tls.Config{
						InsecureSkipVerify: insecure,
					},
					Proxy:               http.ProxyFromEnvironment,
					TLSHandshakeTimeout: 120 * time.Second,
				},
			},
		},
	}
}

// Authenticate is an helper function that performs a login in vCloud Director.
func (c *VCDClient) Authenticate(username, password, org, vdcname string) (Org, Vdc, error) {

	// LoginUrl
	err := c.vcdloginurl()
	if err != nil {
		return Org{}, Vdc{}, fmt.Errorf("error finding LoginUrl: %s", err)
	}
	// Authorize
	err = c.vcdauthorize(username, password, org)
	if err != nil {
		return Org{}, Vdc{}, fmt.Errorf("error authorizing: %s", err)
	}

	// Get Org
	o, err := c.RetrieveOrg(vdcname)
	if err != nil {
		return Org{}, Vdc{}, fmt.Errorf("error acquiring Org: %s", err)
	}

	vdc, err := c.Client.retrieveVDC()

	if err != nil {
		return Org{}, Vdc{}, fmt.Errorf("error retrieving the organization VDC")
	}

	return o, vdc, nil
}

// Disconnect performs a disconnection from the vCloud Director API endpoint.
func (c *VCDClient) Disconnect() error {
	if c.Client.VCDToken == "" && c.Client.VCDAuthHeader == "" {
		return fmt.Errorf("cannot disconnect, client is not authenticated")
	}

	req := c.Client.NewRequest(map[string]string{}, "DELETE", c.sessionHREF, nil)

	// Add the Accept header for vCA
	req.Header.Add("Accept", "application/xml;version=5.5")

	// Set Authorization Header
	req.Header.Add(c.Client.VCDAuthHeader, c.Client.VCDToken)

	if _, err := checkResp(c.Client.Http.Do(req)); err != nil {
		return fmt.Errorf("error processing session delete for vCloud Director: %s", err)
	}
	return nil
}