-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathgo_jolokia.go
387 lines (348 loc) · 11.6 KB
/
go_jolokia.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
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
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
// Maintainer Swarvanu Sengupta <[email protected]>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.
package go_jolokia
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"sort"
"strings"
)
/* Jolokia Client properties connecting a Jolokia agent */
type JolokiaClient struct {
// The url of the jolokia agent
url string
// The user name for the jolokia agent
user string
// The password for the jolokia agent (required if user is specified)
pass string
// The target host in a jolokia proxy setup
target string
// The target host jmx username
targetUser string
// The target host jmx password (required if target user is specified)
targetPass string
}
/* Jolokia Request properties */
type JolokiaRequest struct {
// The type of the operation (LIST, READ)
opType string
// The domain (mbean name)
mbean string
// The bean selection key
properties []string
// The attribute name (property name)
attribute string
// The path to access node of json tree
path string
}
/* Jolokia Response for Generic request */
type JolokiaResponse struct {
// Status of the request
Status uint32
// Timestamp value
Timestamp uint32
// Request
Request map[string]interface{}
// Result value
Value map[string]interface{}
// Error
Error string
}
/* Jolokia Response for Read request */
type JolokiaReadResponse struct {
// Status of the request
Status uint32
// Timestamp value
Timestamp uint32
// Request
Request map[string]interface{}
// Result value
Value interface{}
// Error
Error string
}
type Target struct {
Url string `json:"url"`
Password string `json:"password"`
User string `json:"user"`
}
/* The wrapper structure for json request */
type RequestData struct {
Type string `json:"type"`
Mbean string `json:"mbean"`
Path string `json:"path"`
//Attribute string `json:"attribute"` -- Attribute get added manually
Target `json:"target"`
}
/* The wrapper structure for an EXEC json request */
type ExecRequestData struct {
Type string `json:"type"`
Mbean string `json:"mbean"`
Operation string `json:"operation"`
Arguments interface{} `json:"arguments"`
Target `json:"target"`
}
/* ENUM to be used */
const (
// READ for read operation
READ = "READ"
// LIST for list operation
LIST = "LIST"
// EXEC for exec operation
EXEC = "EXEC"
)
/* Http request param */
type httpRequest struct {
Url string
Body []byte
}
/* Http response param */
type httpResponse struct {
Status string
StatusCode int
Body []byte
}
func performPostRequest(request *httpRequest, user, pass string) (*httpResponse, error) {
var url = request.Url
var req *http.Request
var newReqErr error
if request.Body != nil {
var jsonStr = request.Body
req, newReqErr = http.NewRequest("POST", url, bytes.NewBuffer(jsonStr))
if newReqErr != nil {
return nil, newReqErr
}
req.Header.Set("Content-Type", "application/json")
} else {
req, newReqErr = http.NewRequest("POST", url, nil)
if newReqErr != nil {
return nil, newReqErr
}
}
if user != "" || pass != "" {
req.SetBasicAuth(user, pass)
}
client := &http.Client{}
resp, reqErr := client.Do(req)
if reqErr != nil {
fmt.Printf("Request Could not be send")
return nil, reqErr
}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
response := &httpResponse{}
response.Status = resp.Status
response.StatusCode = resp.StatusCode
response.Body = body
return response, nil
}
/* Internal function used to make the Json request string using the structure */
func wrapRequestData(opType, mbeanName string, properties []string, path, attribute, targetUrl, targerUser, targetPass string) ([]byte, error) {
mbean := buildMbeanName(mbeanName, properties)
target := buildTargetUrl(targetUrl)
requestData := RequestData{Type: opType, Mbean: mbean, Path: path, Target: Target{Url: target, Password: targetPass, User: targerUser}}
// Marshal to the json string
jsbyte, err := json.Marshal(requestData)
if err != nil {
return nil, err
}
jsString := string(jsbyte)
if attribute != "" {
last := len(jsString)
jsString = jsString[:last-1]
attributeString := "\"attribute\":\"" + attribute + "\""
jsString = jsString + ", " + attributeString + "}"
}
jsbyte = []byte(jsString)
return jsbyte, nil
}
func wrapExecData(mbeanName string, properties []string, operation string, arguments interface{}, targetUrl, targerUser, targetPass string) ([]byte, error) {
mbean := buildMbeanName(mbeanName, properties)
target := buildTargetUrl(targetUrl)
requestData := ExecRequestData{Type: EXEC, Mbean: mbean, Operation: operation, Arguments: arguments, Target: Target{Url: target, Password: targetPass, User: targerUser}}
jsbyte, err := json.Marshal(requestData)
if err != nil {
return nil, err
}
return jsbyte, nil
}
func buildMbeanName(mbeanName string, properties []string) string {
mbean := mbeanName
if properties != nil {
for pos := range properties {
mbean = mbean + ":" + properties[pos]
}
}
return mbean
}
func buildTargetUrl(targetUrl string) string {
target := ""
if targetUrl != "" {
if strings.HasPrefix(targetUrl, "service:jmx:") {
target = targetUrl
} else {
target = "service:jmx:rmi:///jndi/rmi://" + targetUrl + "/jmxrmi"
}
}
return target
}
/* Creates a Jolokia Client for a specific url e.g. "http://127.0.0.1:8080/jolokia" */
func NewJolokiaClient(jolokiaUrl string) *JolokiaClient {
jolokiaClient := &JolokiaClient{url: jolokiaUrl}
return jolokiaClient
}
/* Set access credential to Jolokia client */
func (jolokiaClient *JolokiaClient) SetCredential(userName string, pass string) {
jolokiaClient.user = userName
jolokiaClient.pass = pass
}
/* Set target host when jolokia agent working in proxy architecture e.g. "10.0.1.96:7911"
(see: https://jolokia.org/reference/html/proxy.html) */
func (jolokiaClient *JolokiaClient) SetTarget(targetHost string) {
jolokiaClient.target = targetHost
}
/* Set target host access credential to Jolokia client */
func (jolokiaClient *JolokiaClient) SetTargetCredential(userName string, pass string) {
jolokiaClient.targetUser = userName
jolokiaClient.targetPass = pass
}
/* Creates a new Jolokia request */
func NewJolokiaRequest(requestType, mbeanName string, properties []string, attribute string) *JolokiaRequest {
jolokiaRequest := &JolokiaRequest{opType: requestType, mbean: mbeanName, attribute: attribute}
if properties != nil {
jolokiaRequest.properties = make([]string, len(properties))
for pos := range properties {
jolokiaRequest.properties[pos] = properties[pos]
}
}
return jolokiaRequest
}
/* Set path to access tree node of json response */
func (jolokiaRequest *JolokiaRequest) SetPath(path string) {
jolokiaRequest.path = path
}
/* Executes a jolokia request using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) executePostRequestCallback(pattern string, wrapper func() ([]byte, error)) (string, error) {
jsonReq, wrapError := wrapper()
if wrapError != nil {
return "", fmt.Errorf("JSON Wrap Failed: %v", wrapError)
}
requestUrl := jolokiaClient.url
if pattern != "" {
requestUrl = requestUrl + "/?" + pattern
}
request := &httpRequest{Url: requestUrl, Body: jsonReq}
response, httpErr := performPostRequest(request, jolokiaClient.user, jolokiaClient.pass)
if httpErr != nil {
return "", fmt.Errorf("HTTP Request Failed: %v", httpErr)
}
if response.StatusCode != 200 {
return "", fmt.Errorf("HTTP Request Error Code: %v", response.Status)
}
jolokiaResponse := string(response.Body)
return jolokiaResponse, nil
}
/* Executes a jolokia request using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) executePostRequest(jolokiaRequest *JolokiaRequest, pattern string) (string, error) {
return jolokiaClient.executePostRequestCallback(pattern, func() ([]byte, error) {
return wrapRequestData(jolokiaRequest.opType, jolokiaRequest.mbean, jolokiaRequest.properties, jolokiaRequest.path, jolokiaRequest.attribute, jolokiaClient.target, jolokiaClient.targetUser, jolokiaClient.targetPass)
})
}
/* Executes a jolokia operation execution request using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) ExecuteOperation(mBean, operation string, arguments interface{}, pattern string) (*JolokiaReadResponse, error) {
resp, requestErr := jolokiaClient.executePostRequestCallback(pattern, func() ([]byte, error) {
return wrapExecData(mBean, nil, operation, arguments, jolokiaClient.target, jolokiaClient.targetUser, jolokiaClient.targetPass)
})
if requestErr != nil {
return nil, requestErr
}
var respJ JolokiaReadResponse
decodeErr := json.Unmarshal([]byte(resp), &respJ)
if decodeErr != nil {
return nil, fmt.Errorf("Failed to decode Jolokia resp : %v", decodeErr)
}
return &respJ, nil
}
/* Executes a jolokia request using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) ExecuteRequest(jolokiaRequest *JolokiaRequest, pattern string) (*JolokiaResponse, error) {
resp, requestErr := jolokiaClient.executePostRequest(jolokiaRequest, pattern)
if requestErr != nil {
return nil, requestErr
}
var respJ JolokiaResponse
decodeErr := json.Unmarshal([]byte(resp), &respJ)
if decodeErr != nil {
return nil, fmt.Errorf("Failed to decode Jolokia resp : %v", decodeErr)
}
return &respJ, nil
}
/* Executes a jolokia read request using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) ExecuteReadRequest(jolokiaRequest *JolokiaRequest) (*JolokiaReadResponse, error) {
resp, requestErr := jolokiaClient.executePostRequest(jolokiaRequest, "")
if requestErr != nil {
return nil, requestErr
}
var respJ JolokiaReadResponse
decodeErr := json.Unmarshal([]byte(resp), &respJ)
if decodeErr != nil {
return nil, fmt.Errorf("Failed to decode Jolokia resp : %v", decodeErr)
}
return &respJ, nil
}
/* List the domains using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) ListDomains() ([]string, error) {
request := NewJolokiaRequest(LIST, "", nil, "")
resp, requestErr := jolokiaClient.ExecuteRequest(request, "maxDepth=1")
if requestErr != nil {
return nil, requestErr
}
ret := make([]string, 0, len(resp.Value))
for key, _ := range resp.Value {
ret = append(ret, key)
}
sort.Strings(ret)
return ret, nil
}
/* List the beans of a specific domain using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) ListBeans(domain string) ([]string, error) {
request := NewJolokiaRequest(LIST, "", nil, "")
request.SetPath(domain)
resp, requestErr := jolokiaClient.ExecuteRequest(request, "maxDepth=1")
if requestErr != nil {
return nil, requestErr
}
ret := make([]string, 0, len(resp.Value))
for key, _ := range resp.Value {
ret = append(ret, key)
}
sort.Strings(ret)
return ret, nil
}
/* List the properties of a specific bean and domain using a jolokia client and return response */
func (jolokiaClient *JolokiaClient) ListProperties(domain string, properties []string) ([]string, error) {
request := NewJolokiaRequest(READ, domain, properties, "")
resp, requestErr := jolokiaClient.ExecuteRequest(request, "")
if requestErr != nil {
return nil, requestErr
}
ret := make([]string, 0, len(resp.Value))
for key, _ := range resp.Value {
ret = append(ret, key)
}
sort.Strings(ret)
return ret, nil
}
/* Get a attribute value of a specific property of an bean and a domain using a jolokia client */
func (jolokiaClient *JolokiaClient) GetAttr(domain string, properties []string, attribute string) (interface{}, error) {
request := NewJolokiaRequest(READ, domain, properties, attribute)
resp, requestErr := jolokiaClient.ExecuteReadRequest(request)
if requestErr != nil {
return nil, requestErr
}
return resp.Value, nil
}