-
Notifications
You must be signed in to change notification settings - Fork 4.9k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Beats enrollment subcommand #7182
Changes from all commits
88e1fd2
a5ac0e5
36ac88c
24d00d9
30539fd
d0718e3
df24592
75893ce
2c9d937
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,55 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package cmd | ||
|
||
import ( | ||
"fmt" | ||
|
||
"github.com/pkg/errors" | ||
"github.com/spf13/cobra" | ||
|
||
"github.com/elastic/beats/libbeat/cmd/instance" | ||
"github.com/elastic/beats/libbeat/common/cli" | ||
"github.com/elastic/beats/x-pack/libbeat/management" | ||
) | ||
|
||
func getBeat(name, version string) (*instance.Beat, error) { | ||
b, err := instance.NewBeat(name, "", version) | ||
|
||
if err != nil { | ||
return nil, fmt.Errorf("error creating beat: %s", err) | ||
} | ||
|
||
if err = b.Init(); err != nil { | ||
return nil, fmt.Errorf("error initializing beat: %s", err) | ||
} | ||
|
||
return b, nil | ||
} | ||
|
||
func genEnrollCmd(name, version string) *cobra.Command { | ||
enrollCmd := cobra.Command{ | ||
Use: "enroll <kibana_url> <enrollment_token>", | ||
Short: "Enroll in Kibana for Central Management", | ||
Args: cobra.ExactArgs(2), | ||
Run: cli.RunWith(func(cmd *cobra.Command, args []string) error { | ||
beat, err := getBeat(name, version) | ||
kibanaURL := args[0] | ||
enrollmentToken := args[1] | ||
if err != nil { | ||
return err | ||
} | ||
|
||
if err = management.Enroll(beat, kibanaURL, enrollmentToken); err != nil { | ||
return errors.Wrap(err, "Error while enrolling") | ||
} | ||
|
||
fmt.Println("Enrolled and ready to retrieve settings from Kibana") | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. As we know the Kibana url, we could share it here directly (without passwords) There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. I would need to parse it to remove credentials, having that the user has just inputted it for the command I'm not sure this is worth it, wdyt? There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice to have, not a requirement :-) |
||
return nil | ||
}), | ||
} | ||
|
||
return &enrollCmd | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,12 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package cmd | ||
|
||
import "github.com/elastic/beats/libbeat/cmd" | ||
|
||
// AddXPack extends the given root folder with XPack features | ||
func AddXPack(root *cmd.BeatsRootCmd, name string) { | ||
root.AddCommand(genEnrollCmd(name, "")) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,95 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package api | ||
|
||
import ( | ||
"bytes" | ||
"encoding/json" | ||
"net/http" | ||
"net/url" | ||
"time" | ||
|
||
"github.com/pkg/errors" | ||
|
||
"github.com/elastic/beats/libbeat/common" | ||
"github.com/elastic/beats/libbeat/kibana" | ||
) | ||
|
||
const defaultTimeout = 10 * time.Second | ||
|
||
// Client to Central Management API | ||
type Client struct { | ||
client *kibana.Client | ||
} | ||
|
||
// ConfigFromURL generates a full kibana client config from an URL | ||
func ConfigFromURL(kibanaURL string) (*kibana.ClientConfig, error) { | ||
data, err := url.Parse(kibanaURL) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
var username, password string | ||
if data.User != nil { | ||
username = data.User.Username() | ||
password, _ = data.User.Password() | ||
} | ||
|
||
return &kibana.ClientConfig{ | ||
Protocol: data.Scheme, | ||
Host: data.Host, | ||
Path: data.Path, | ||
Username: username, | ||
Password: password, | ||
Timeout: defaultTimeout, | ||
IgnoreVersion: true, | ||
}, nil | ||
} | ||
|
||
// NewClient creates and returns a kibana client | ||
func NewClient(cfg *kibana.ClientConfig) (*Client, error) { | ||
client, err := kibana.NewClientWithConfig(cfg) | ||
if err != nil { | ||
return nil, err | ||
} | ||
return &Client{ | ||
client: client, | ||
}, nil | ||
} | ||
|
||
// do a request to the API and unmarshall the message, error if anything fails | ||
func (c *Client) request(method, extraPath string, | ||
params common.MapStr, headers http.Header, message interface{}) (int, error) { | ||
|
||
paramsJSON, err := json.Marshal(params) | ||
if err != nil { | ||
return 400, err | ||
} | ||
|
||
statusCode, result, err := c.client.Request(method, extraPath, nil, headers, bytes.NewBuffer(paramsJSON)) | ||
if err != nil { | ||
return statusCode, err | ||
} | ||
|
||
if statusCode >= 300 { | ||
err = extractError(result) | ||
} else { | ||
if err = json.Unmarshal(result, message); err != nil { | ||
return statusCode, errors.Wrap(err, "error unmarshaling Kibana response") | ||
} | ||
} | ||
|
||
return statusCode, err | ||
} | ||
|
||
func extractError(result []byte) error { | ||
var kibanaResult struct { | ||
Message string | ||
} | ||
if err := json.Unmarshal(result, &kibanaResult); err != nil { | ||
return errors.Wrap(err, "parsing Kibana response") | ||
} | ||
return errors.New(kibanaResult.Message) | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,33 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package api | ||
|
||
import ( | ||
"net/http" | ||
"net/http/httptest" | ||
"testing" | ||
) | ||
|
||
func newServerClientPair(t *testing.T, handler http.HandlerFunc) (*httptest.Server, *Client) { | ||
mux := http.NewServeMux() | ||
mux.Handle("/api/status", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
http.Error(w, "Unauthorized", 401) | ||
})) | ||
mux.Handle("/", handler) | ||
|
||
server := httptest.NewServer(mux) | ||
|
||
config, err := ConfigFromURL(server.URL) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
client, err := NewClient(config) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
return server, client | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,36 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package api | ||
|
||
import ( | ||
"net/http" | ||
|
||
uuid "github.com/satori/go.uuid" | ||
|
||
"github.com/elastic/beats/libbeat/common" | ||
) | ||
|
||
// Enroll a beat in central management, this call returns a valid access token to retrieve configurations | ||
func (c *Client) Enroll(beatType, beatVersion, hostname string, beatUUID uuid.UUID, enrollmentToken string) (string, error) { | ||
params := common.MapStr{ | ||
"type": beatType, | ||
"host_name": hostname, | ||
"version": beatVersion, | ||
} | ||
|
||
resp := struct { | ||
AccessToken string `json:"access_token"` | ||
}{} | ||
|
||
headers := http.Header{} | ||
headers.Set("kbn-beats-enrollment-token", enrollmentToken) | ||
|
||
_, err := c.request("POST", "/api/beats/agent/"+beatUUID.String(), params, headers, &resp) | ||
if err != nil { | ||
return "", err | ||
} | ||
|
||
return resp.AccessToken, err | ||
} |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,71 @@ | ||
// Copyright Elasticsearch B.V. and/or licensed to Elasticsearch B.V. under one | ||
// or more contributor license agreements. Licensed under the Elastic License; | ||
// you may not use this file except in compliance with the Elastic License. | ||
|
||
package api | ||
|
||
import ( | ||
"encoding/json" | ||
"fmt" | ||
"io/ioutil" | ||
"net/http" | ||
"testing" | ||
|
||
uuid "github.com/satori/go.uuid" | ||
"github.com/stretchr/testify/assert" | ||
) | ||
|
||
func TestEnrollValid(t *testing.T) { | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Nice test 👍 |
||
beatUUID := uuid.NewV4() | ||
|
||
server, client := newServerClientPair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
defer r.Body.Close() | ||
body, err := ioutil.ReadAll(r.Body) | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
// Check correct path is used | ||
assert.Equal(t, "/api/beats/agent/"+beatUUID.String(), r.URL.Path) | ||
|
||
// Check enrollment token is correct | ||
assert.Equal(t, "thisismyenrollmenttoken", r.Header.Get("kbn-beats-enrollment-token")) | ||
|
||
request := struct { | ||
Hostname string `json:"host_name"` | ||
Type string `json:"type"` | ||
Version string `json:"version"` | ||
}{} | ||
if err := json.Unmarshal(body, &request); err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
assert.Equal(t, "myhostname.lan", request.Hostname) | ||
assert.Equal(t, "metricbeat", request.Type) | ||
assert.Equal(t, "6.3.0", request.Version) | ||
|
||
fmt.Fprintf(w, `{"access_token": "fooo"}`) | ||
})) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Thanks for the test @exekias I used the same pattern for the License checker! 👍 |
||
defer server.Close() | ||
|
||
accessToken, err := client.Enroll("metricbeat", "6.3.0", "myhostname.lan", beatUUID, "thisismyenrollmenttoken") | ||
if err != nil { | ||
t.Fatal(err) | ||
} | ||
|
||
assert.Equal(t, "fooo", accessToken) | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Perhaps make |
||
} | ||
|
||
func TestEnrollError(t *testing.T) { | ||
beatUUID := uuid.NewV4() | ||
|
||
server, client := newServerClientPair(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { | ||
http.Error(w, `{"message": "Invalid enrollment token"}`, 400) | ||
})) | ||
defer server.Close() | ||
|
||
accessToken, err := client.Enroll("metricbeat", "6.3.0", "myhostname.lan", beatUUID, "thisismyenrollmenttoken") | ||
|
||
assert.NotNil(t, err) | ||
assert.Equal(t, "", accessToken) | ||
} |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
What happens if we don't have enough arguments?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
cobra library handles that: