Skip to content

Commit 5a0293c

Browse files
authored
Merging ingestmanager client into generic kibana client (#210)
* Merging ingestmanager client into generic kibana client * Refactoring: using helper get method on kibana client * Formatting * Fixing path construction in URLs * Extracting API prefixes to consts * Removing unused field * Fixing sprintf arg * Remove t.Log call * Rename URL prefix definitions file
1 parent d81ff0c commit 5a0293c

File tree

9 files changed

+116
-189
lines changed

9 files changed

+116
-189
lines changed

internal/fields/validate_test.go

Lines changed: 0 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -184,9 +184,6 @@ func Test_parseElementValue(t *testing.T) {
184184

185185
t.Run(test.key, func(t *testing.T) {
186186
err := parseElementValue(test.key, test.definition, test.value)
187-
if err != nil {
188-
t.Log(err)
189-
}
190187
if test.fail {
191188
require.Error(t, err)
192189
} else {

internal/kibana/ingestmanager/client_agents.go renamed to internal/kibana/agents.go

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// or more contributor license agreements. Licensed under the Elastic License;
33
// you may not use this file except in compliance with the Elastic License.
44

5-
package ingestmanager
5+
package kibana
66

77
import (
88
"encoding/json"
@@ -23,7 +23,7 @@ type Agent struct {
2323

2424
// ListAgents returns the list of agents enrolled with Fleet.
2525
func (c *Client) ListAgents() ([]Agent, error) {
26-
statusCode, respBody, err := c.get("agents")
26+
statusCode, respBody, err := c.get(fmt.Sprintf("%s/agents", FleetAPI))
2727
if err != nil {
2828
return nil, errors.Wrap(err, "could not list agents")
2929
}
@@ -47,7 +47,7 @@ func (c *Client) ListAgents() ([]Agent, error) {
4747
func (c *Client) AssignPolicyToAgent(a Agent, p Policy) error {
4848
reqBody := `{ "policy_id": "` + p.ID + `" }`
4949

50-
path := fmt.Sprintf("agents/%s/reassign", a.ID)
50+
path := fmt.Sprintf("%s/agents/%s/reassign", FleetAPI, a.ID)
5151
statusCode, respBody, err := c.put(path, []byte(reqBody))
5252
if err != nil {
5353
return errors.Wrap(err, "could not assign policy to agent")
@@ -66,7 +66,7 @@ func (c *Client) AssignPolicyToAgent(a Agent, p Policy) error {
6666

6767
func (c *Client) getTotalAgentForPolicy(p Policy) (int, error) {
6868
kuery := url.QueryEscape(fmt.Sprintf("fleet-agents.policy_id:\"%s\"", p.ID))
69-
path := fmt.Sprintf("agents?kuery=%s", kuery)
69+
path := fmt.Sprintf("%s/agents?kuery=%s", FleetAPI, kuery)
7070
statusCode, respBody, err := c.get(path)
7171
if err != nil {
7272
return 0, errors.Wrapf(err, "could not check agent status; API status code = %d; policy ID = %s; response body = %s", statusCode, p.ID, string(respBody))
@@ -94,7 +94,7 @@ func (c *Client) waitUntilPolicyAssigned(p Policy) error {
9494
var assigned bool
9595
for !assigned {
9696
kuery := url.QueryEscape(fmt.Sprintf("fleet-agents.policy_id:\"%s\" and fleet-agents.policy_revision:*", p.ID))
97-
path := fmt.Sprintf("agents?kuery=%s", kuery)
97+
path := fmt.Sprintf("%s/agents?kuery=%s", FleetAPI, kuery)
9898
statusCode, respBody, err := c.get(path)
9999
if err != nil {
100100
return errors.Wrapf(err, "could not check agent status; API status code = %d; policy ID = %s; response body = %s", statusCode, p.ID, string(respBody))

internal/kibana/client.go

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,15 @@
55
package kibana
66

77
import (
8+
"bytes"
9+
"io/ioutil"
10+
"net/http"
11+
"net/url"
812
"os"
913

14+
"github.com/pkg/errors"
15+
16+
"github.com/elastic/elastic-package/internal/logger"
1017
"github.com/elastic/elastic-package/internal/stack"
1118
)
1219

@@ -33,3 +40,56 @@ func NewClient() (*Client, error) {
3340
password: password,
3441
}, nil
3542
}
43+
44+
func (c *Client) get(resourcePath string) (int, []byte, error) {
45+
return c.sendRequest(http.MethodGet, resourcePath, nil)
46+
}
47+
48+
func (c *Client) post(resourcePath string, body []byte) (int, []byte, error) {
49+
return c.sendRequest(http.MethodPost, resourcePath, body)
50+
}
51+
52+
func (c *Client) put(resourcePath string, body []byte) (int, []byte, error) {
53+
return c.sendRequest(http.MethodPut, resourcePath, body)
54+
}
55+
56+
func (c *Client) sendRequest(method, resourcePath string, body []byte) (int, []byte, error) {
57+
reqBody := bytes.NewReader(body)
58+
base, err := url.Parse(c.host)
59+
if err != nil {
60+
return 0, nil, errors.Wrapf(err, "could not create base URL from host: %v", c.host)
61+
}
62+
63+
rel, err := url.Parse(resourcePath)
64+
if err != nil {
65+
return 0, nil, errors.Wrapf(err, "could not create relative URL from resource path: %v", resourcePath)
66+
}
67+
68+
u := base.ResolveReference(rel)
69+
70+
logger.Debugf("%s %s", method, u)
71+
logger.Debugf("%s", body)
72+
73+
req, err := http.NewRequest(method, u.String(), reqBody)
74+
if err != nil {
75+
return 0, nil, errors.Wrapf(err, "could not create %v request to Kibana API resource: %s", method, resourcePath)
76+
}
77+
78+
req.SetBasicAuth(c.username, c.password)
79+
req.Header.Add("content-type", "application/json")
80+
req.Header.Add("kbn-xsrf", stack.DefaultVersion)
81+
82+
client := http.Client{}
83+
resp, err := client.Do(req)
84+
if err != nil {
85+
return 0, nil, errors.Wrap(err, "could not send request to Kibana API")
86+
}
87+
88+
defer resp.Body.Close()
89+
body, err = ioutil.ReadAll(resp.Body)
90+
if err != nil {
91+
return resp.StatusCode, nil, errors.Wrap(err, "could not read response body")
92+
}
93+
94+
return resp.StatusCode, body, nil
95+
}

internal/kibana/dashboards.go

Lines changed: 6 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,7 @@ package kibana
66

77
import (
88
"encoding/json"
9-
"io/ioutil"
10-
"net/http"
9+
"fmt"
1110
"strings"
1211

1312
"github.com/pkg/errors"
@@ -33,27 +32,16 @@ func (c *Client) Export(dashboardIDs []string) ([]common.MapStr, error) {
3332
query.WriteByte('&')
3433
}
3534

36-
request, err := http.NewRequest(http.MethodGet, c.host+"/api/kibana/dashboards/export"+query.String(), nil)
35+
path := fmt.Sprintf("%s/dashboards/export%s", CoreAPI, query.String())
36+
statusCode, respBody, err := c.get(path)
3737
if err != nil {
38-
return nil, errors.Wrap(err, "building HTTP request failed")
39-
}
40-
request.SetBasicAuth(c.username, c.password)
41-
42-
response, err := http.DefaultClient.Do(request)
43-
if err != nil {
44-
return nil, errors.Wrap(err, "sending HTTP request failed")
45-
}
46-
defer response.Body.Close()
47-
48-
body, err := ioutil.ReadAll(response.Body)
49-
if err != nil {
50-
return nil, errors.Wrap(err, "reading response body failed")
38+
return nil, errors.Wrapf(err, "could not export dashboards; API status code = %d; response body = %s", statusCode, string(respBody))
5139
}
5240

5341
var exported exportedType
54-
err = json.Unmarshal(body, &exported)
42+
err = json.Unmarshal(respBody, &exported)
5543
if err != nil {
56-
return nil, errors.Wrapf(err, "unmarshalling response failed (body: \n%s)", string(body))
44+
return nil, errors.Wrapf(err, "unmarshalling response failed (body: \n%s)", string(respBody))
5745
}
5846

5947
var multiErr multierror.Error

internal/kibana/ingestmanager/client.go

Lines changed: 0 additions & 98 deletions
This file was deleted.

internal/kibana/ingestmanager/client_policies.go renamed to internal/kibana/policies.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22
// or more contributor license agreements. Licensed under the Elastic License;
33
// you may not use this file except in compliance with the Elastic License.
44

5-
package ingestmanager
5+
package kibana
66

77
import (
88
"encoding/json"
@@ -28,7 +28,7 @@ func (c *Client) CreatePolicy(p Policy) (*Policy, error) {
2828
return nil, errors.Wrap(err, "could not convert policy (request) to JSON")
2929
}
3030

31-
statusCode, respBody, err := c.post("agent_policies", reqBody)
31+
statusCode, respBody, err := c.post(fmt.Sprintf("%s/agent_policies", FleetAPI), reqBody)
3232
if err != nil {
3333
return nil, errors.Wrap(err, "could not create policy")
3434
}
@@ -52,7 +52,7 @@ func (c *Client) CreatePolicy(p Policy) (*Policy, error) {
5252
func (c *Client) DeletePolicy(p Policy) error {
5353
reqBody := `{ "agentPolicyId": "` + p.ID + `" }`
5454

55-
statusCode, respBody, err := c.post("agent_policies/delete", []byte(reqBody))
55+
statusCode, respBody, err := c.post(fmt.Sprintf("%s/agent_policies/delete", FleetAPI), []byte(reqBody))
5656
if err != nil {
5757
return errors.Wrap(err, "could not delete policy")
5858
}
@@ -122,7 +122,7 @@ func (c *Client) AddPackageDataStreamToPolicy(r PackageDataStream) error {
122122
return errors.Wrap(err, "could not convert policy-package (request) to JSON")
123123
}
124124

125-
statusCode, respBody, err := c.post("package_policies", reqBody)
125+
statusCode, respBody, err := c.post(fmt.Sprintf("%s/package_policies", FleetAPI), reqBody)
126126
if err != nil {
127127
return errors.Wrap(err, "could not add package to policy")
128128
}

internal/kibana/saved_objects.go

Lines changed: 4 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,8 +7,6 @@ package kibana
77
import (
88
"encoding/json"
99
"fmt"
10-
"io/ioutil"
11-
"net/http"
1210
"sort"
1311
"strings"
1412

@@ -93,25 +91,14 @@ func (c *Client) FindDashboards() (DashboardSavedObjects, error) {
9391
}
9492

9593
func (c *Client) findDashboardsNextPage(page int) (*savedObjectsResponse, error) {
96-
request, err := http.NewRequest(http.MethodGet, fmt.Sprintf("%s%s%d", c.host, fmt.Sprintf("/api/saved_objects/_find?type=dashboard&fields=title&per_page=%d&page=", findDashboardsPerPage), page), nil)
94+
path := fmt.Sprintf("%s/_find?type=dashboard&fields=title&per_page=%d&page=%d", SavedObjectsAPI, findDashboardsPerPage, page)
95+
statusCode, respBody, err := c.get(path)
9796
if err != nil {
98-
return nil, errors.Wrap(err, "building HTTP request failed")
99-
}
100-
request.SetBasicAuth(c.username, c.password)
101-
102-
response, err := http.DefaultClient.Do(request)
103-
if err != nil {
104-
return nil, errors.Wrap(err, "sending HTTP request failed")
105-
}
106-
defer response.Body.Close()
107-
108-
body, err := ioutil.ReadAll(response.Body)
109-
if err != nil {
110-
return nil, errors.Wrap(err, "reading response body failed")
97+
return nil, errors.Wrapf(err, "could not find dashboards; API status code = %d; response body = %s", statusCode, string(respBody))
11198
}
11299

113100
var r savedObjectsResponse
114-
err = json.Unmarshal(body, &r)
101+
err = json.Unmarshal(respBody, &r)
115102
if err != nil {
116103
return nil, errors.Wrap(err, "unmarshalling response failed")
117104
}

internal/kibana/url_prefixes.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one
2+
// or more contributor license agreements. Licensed under the Elastic License;
3+
// you may not use this file except in compliance with the Elastic License.
4+
5+
package kibana
6+
7+
const (
8+
// CoreAPI is the prefix for all Kibana Core API resources.
9+
CoreAPI = "/api/kibana"
10+
11+
// SavedObjectsAPI is the prefix for all Kibana Saved Objects API resources.
12+
SavedObjectsAPI = "/api/saved_objects"
13+
14+
// FleetAPI is the prefix for all Kibana Fleet API resources.
15+
FleetAPI = "/api/fleet"
16+
)

0 commit comments

Comments
 (0)