summaryrefslogtreecommitdiffstats
path: root/src/go/collectors/go.d.plugin/modules/vcsa/client/client.go
blob: 64f53ff44719991426a2c01d988d46fe91513f6b (plain)
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
// SPDX-License-Identifier: GPL-3.0-or-later

package client

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
	"sync"

	"github.com/netdata/netdata/go/go.d.plugin/pkg/web"
)

//  Session: https://vmware.github.io/vsphere-automation-sdk-rest/vsphere/index.html#SVC_com.vmware.cis.session
//  Health: https://vmware.github.io/vsphere-automation-sdk-rest/vsphere/index.html#SVC_com.vmware.appliance.health

const (
	pathCISSession             = "/rest/com/vmware/cis/session"
	pathHealthSystem           = "/rest/appliance/health/system"
	pathHealthSwap             = "/rest/appliance/health/swap"
	pathHealthStorage          = "/rest/appliance/health/storage"
	pathHealthSoftwarePackager = "/rest/appliance/health/software-packages"
	pathHealthMem              = "/rest/appliance/health/mem"
	pathHealthLoad             = "/rest/appliance/health/load"
	pathHealthDatabaseStorage  = "/rest/appliance/health/database-storage"
	pathHealthApplMgmt         = "/rest/appliance/health/applmgmt"

	apiSessIDKey = "vmware-api-session-id"
)

type sessionToken struct {
	m  *sync.RWMutex
	id string
}

func (s *sessionToken) set(id string) {
	s.m.Lock()
	defer s.m.Unlock()
	s.id = id
}

func (s *sessionToken) get() string {
	s.m.RLock()
	defer s.m.RUnlock()
	return s.id
}

func New(httpClient *http.Client, url, username, password string) *Client {
	if httpClient == nil {
		httpClient = &http.Client{}
	}
	return &Client{
		httpClient: httpClient,
		url:        url,
		username:   username,
		password:   password,
		token:      &sessionToken{m: new(sync.RWMutex)},
	}
}

type Client struct {
	httpClient *http.Client

	url      string
	username string
	password string

	token *sessionToken
}

// Login creates a session with the API. This operation exchanges user credentials supplied in the security context
// for a session identifier that is to be used for authenticating subsequent calls.
func (c *Client) Login() error {
	req := web.Request{
		URL:      fmt.Sprintf("%s%s", c.url, pathCISSession),
		Username: c.username,
		Password: c.password,
		Method:   http.MethodPost,
	}
	s := struct{ Value string }{}

	err := c.doOKWithDecode(req, &s)
	if err == nil {
		c.token.set(s.Value)
	}
	return err
}

// Logout terminates the validity of a session token.
func (c *Client) Logout() error {
	req := web.Request{
		URL:     fmt.Sprintf("%s%s", c.url, pathCISSession),
		Method:  http.MethodDelete,
		Headers: map[string]string{apiSessIDKey: c.token.get()},
	}

	resp, err := c.doOK(req)
	closeBody(resp)
	c.token.set("")
	return err
}

// Ping sent a request to VCSA server to ensure the link is operating.
// In case of 401 error Ping tries to re authenticate.
func (c *Client) Ping() error {
	req := web.Request{
		URL:     fmt.Sprintf("%s%s?~action=get", c.url, pathCISSession),
		Method:  http.MethodPost,
		Headers: map[string]string{apiSessIDKey: c.token.get()},
	}
	resp, err := c.doOK(req)
	defer closeBody(resp)
	if resp != nil && resp.StatusCode == http.StatusUnauthorized {
		return c.Login()
	}
	return err
}

func (c *Client) health(urlPath string) (string, error) {
	req := web.Request{
		URL:     fmt.Sprintf("%s%s", c.url, urlPath),
		Headers: map[string]string{apiSessIDKey: c.token.get()},
	}
	s := struct{ Value string }{}
	err := c.doOKWithDecode(req, &s)
	return s.Value, err
}

// ApplMgmt provides health status of applmgmt services.
func (c *Client) ApplMgmt() (string, error) {
	return c.health(pathHealthApplMgmt)
}

// DatabaseStorage provides health status of database storage health.
func (c *Client) DatabaseStorage() (string, error) {
	return c.health(pathHealthDatabaseStorage)
}

// Load provides health status of load health.
func (c *Client) Load() (string, error) {
	return c.health(pathHealthLoad)
}

// Mem provides health status of memory health.
func (c *Client) Mem() (string, error) {
	return c.health(pathHealthMem)
}

// SoftwarePackages provides information on available software updates available in remote VUM repository.
// Red indicates that security updates are available.
// Orange indicates that non-security updates are available.
// Green indicates that there are no updates available.
// Gray indicates that there was an error retrieving information on software updates.
func (c *Client) SoftwarePackages() (string, error) {
	return c.health(pathHealthSoftwarePackager)
}

// Storage provides health status of storage health.
func (c *Client) Storage() (string, error) {
	return c.health(pathHealthStorage)
}

// Swap provides health status of swap health.
func (c *Client) Swap() (string, error) {
	return c.health(pathHealthSwap)
}

// System provides overall health of system.
func (c *Client) System() (string, error) {
	return c.health(pathHealthSystem)
}

func (c *Client) do(req web.Request) (*http.Response, error) {
	httpReq, err := web.NewHTTPRequest(req)
	if err != nil {
		return nil, fmt.Errorf("error on creating http request to %s : %v", req.URL, err)
	}
	return c.httpClient.Do(httpReq)
}

func (c *Client) doOK(req web.Request) (*http.Response, error) {
	resp, err := c.do(req)
	if err != nil {
		return nil, err
	}

	if resp.StatusCode != http.StatusOK {
		return resp, fmt.Errorf("%s returned %d", req.URL, resp.StatusCode)
	}
	return resp, nil
}

func (c *Client) doOKWithDecode(req web.Request, dst interface{}) error {
	resp, err := c.doOK(req)
	defer closeBody(resp)
	if err != nil {
		return err
	}

	err = json.NewDecoder(resp.Body).Decode(dst)
	if err != nil {
		return fmt.Errorf("error on decoding response from %s : %v", req.URL, err)
	}
	return nil
}

func closeBody(resp *http.Response) {
	if resp != nil && resp.Body != nil {
		_, _ = io.Copy(io.Discard, resp.Body)
		_ = resp.Body.Close()
	}
}