-
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
Heartbeat: add support for pushed monitor source #31428
Merged
vigneshshanmugam
merged 8 commits into
elastic:main
from
vigneshshanmugam:pushed-source
May 16, 2022
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
82724e8
Heartbeat: add support for pushed monitors
vigneshshanmugam a54114f
link to global synthetics pkg
vigneshshanmugam 3e705d0
add tests and link global path
vigneshshanmugam fa43efa
fix lint issues
vigneshshanmugam 2e2f2dc
fix tests
vigneshshanmugam b19c031
add changelog
vigneshshanmugam 6a58346
use install instead of link
vigneshshanmugam d04a92a
handle zipslip vul
vigneshshanmugam File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,131 @@ | ||
// 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 source | ||
|
||
import ( | ||
"bytes" | ||
"encoding/base64" | ||
"encoding/json" | ||
"fmt" | ||
"io" | ||
"io/ioutil" | ||
"os" | ||
"os/exec" | ||
"path/filepath" | ||
"regexp" | ||
"strings" | ||
|
||
"github.com/elastic/elastic-agent-libs/mapstr" | ||
) | ||
|
||
type PushedSource struct { | ||
Content string `config:"content" json:"content"` | ||
TargetDirectory string | ||
} | ||
|
||
var ErrNoContent = fmt.Errorf("no 'content' value specified for pushed monitor source") | ||
|
||
func (p *PushedSource) Validate() error { | ||
if !regexp.MustCompile(`\S`).MatchString(p.Content) { | ||
return ErrNoContent | ||
} | ||
|
||
return nil | ||
} | ||
|
||
func (p *PushedSource) Fetch() error { | ||
decodedBytes, err := base64.StdEncoding.DecodeString(p.Content) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
tf, err := ioutil.TempFile("/tmp", "elastic-synthetics-zip-") | ||
if err != nil { | ||
return fmt.Errorf("could not create tmpfile for pushed monitor source: %w", err) | ||
} | ||
defer os.Remove(tf.Name()) | ||
|
||
// copy the encoded contents in to a temp file for unzipping later | ||
_, err = io.Copy(tf, bytes.NewReader(decodedBytes)) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
p.TargetDirectory, err = ioutil.TempDir("/tmp", "elastic-synthetics-unzip-") | ||
if err != nil { | ||
return fmt.Errorf("could not make temp dir for unzipping pushed source: %w", err) | ||
} | ||
|
||
err = unzip(tf, p.Workdir(), "") | ||
if err != nil { | ||
p.Close() | ||
return err | ||
} | ||
|
||
// Offline is not required for pushed resources as we are only linking | ||
// to the globally installed agent, but useful for testing purposes | ||
if !Offline() { | ||
// set up npm project and ensure synthetics is installed | ||
err = setupProjectDir(p.Workdir()) | ||
if err != nil { | ||
return fmt.Errorf("setting up project dir failed: %w", err) | ||
} | ||
} | ||
|
||
return nil | ||
} | ||
|
||
type PackageJSON struct { | ||
Name string `json:"name"` | ||
Private bool `json:"private"` | ||
Dependencies mapstr.M `json:"dependencies"` | ||
} | ||
|
||
// setupProjectDir sets ups the required package.json file and | ||
// links the synthetics dependency to the globally installed one that is | ||
// baked in to the Heartbeat image to maintain compatibility and | ||
// allows us to control the synthetics agent version | ||
func setupProjectDir(workdir string) error { | ||
fname, err := exec.LookPath("elastic-synthetics") | ||
if err == nil { | ||
fname, err = filepath.Abs(fname) | ||
} | ||
if err != nil { | ||
return fmt.Errorf("cannot resolve global synthetics library: %w", err) | ||
} | ||
|
||
globalPath := strings.Replace(fname, "bin/elastic-synthetics", "lib/node_modules/@elastic/synthetics", 1) | ||
symlinkPath := fmt.Sprintf("file:%s", globalPath) | ||
pkgJson := PackageJSON{ | ||
Name: "pushed-journey", | ||
Private: true, | ||
Dependencies: mapstr.M{ | ||
"@elastic/synthetics": symlinkPath, | ||
}, | ||
} | ||
pkgJsonContent, err := json.MarshalIndent(pkgJson, "", " ") | ||
if err != nil { | ||
return err | ||
} | ||
//nolint:gosec //for permission | ||
err = ioutil.WriteFile(filepath.Join(workdir, "package.json"), pkgJsonContent, 0755) | ||
if err != nil { | ||
return err | ||
} | ||
|
||
// setup the project linking to the global synthetics library | ||
return runSimpleCommand(exec.Command("npm", "install"), workdir) | ||
} | ||
|
||
func (p *PushedSource) Workdir() string { | ||
return p.TargetDirectory | ||
} | ||
|
||
func (p *PushedSource) Close() error { | ||
if p.TargetDirectory != "" { | ||
return os.RemoveAll(p.TargetDirectory) | ||
} | ||
return nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,98 @@ | ||
// 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 source | ||
|
||
import ( | ||
"os" | ||
"path" | ||
"testing" | ||
|
||
"github.com/stretchr/testify/assert" | ||
"github.com/stretchr/testify/require" | ||
"gopkg.in/yaml.v2" | ||
|
||
"github.com/elastic/elastic-agent-libs/config" | ||
"github.com/elastic/elastic-agent-libs/mapstr" | ||
) | ||
|
||
func setUpTests() func() { | ||
GoOffline() | ||
return func() { | ||
GoOnline() | ||
} | ||
} | ||
|
||
func TestPushedSource(t *testing.T) { | ||
teardown := setUpTests() | ||
defer teardown() | ||
|
||
type testCase struct { | ||
name string | ||
cfg mapstr.M | ||
wantErr bool | ||
} | ||
testCases := []testCase{ | ||
{ | ||
"decode pushed content", | ||
mapstr.M{ | ||
"content": "UEsDBBQACAAIAJ27qVQAAAAAAAAAAAAAAAAiAAAAZXhhbXBsZXMvdG9kb3MvYWR2YW5jZWQuam91cm5leS50c5VRPW/CMBDd+RWnLA0Sigt0KqJqpbZTN+iEGKzkIC6JbfkuiBTx3+uEEAGlgi7Rnf38viIESCLkR/FJ6Eis1VIjpanATBKrWFCpOUU/kcCNzG2GJNgkhoRM1lLHmERfpnAay4ipo3JrHMMWmjPYwcKZHILn33zBqIV3ADIjkxdrJ4y251eZJFNJq3b1Hh1XJx+KeKK+8XATpxiv3o07RidI7Ex5OOocTEQixcz6mF66MRgGXkmxMhqkTiA2VcJ6NQsgpZcZAnueoAfhFqxcYs9/ncwJdl0YP9XeY6OJgb3qFDcMYwhejb5jsAUDyYxBaSi9HmCJlfZJ2vCYNCpc1h2d5m8AB/r99cU+GmS/hpwXc4nmrKh/K917yK57VqZe1lU6zM26WvIiY2WbHunWIiusb3IWVBP0/bP9NGinYTC/qcqWLloY9ybjNAy5VbzYdP1sdz3+8FqJleqsP7/ONPjjp++TPgS3eaks/wBQSwcIVYIEHGwBAADRAwAAUEsDBBQACAAIAJ27qVQAAAAAAAAAAAAAAAAZAAAAZXhhbXBsZXMvdG9kb3MvaGVscGVycy50c5VUTYvbMBC9768YRGAVyKb0uktCu9CeektvpRCtM4nFKpKQxt2kwf+9I9lJ5cRb6MWW5+u9eTOW3nsXCE4QCf0M8OCxImhhG9wexCc0KpKuPsSjpRr5FMXTXeVsJDBObT57v+I8WID0aoczaIKZwmIJpzvIFaUwqrFVDcp7MQPFdSqQlxAA9aY0QUqe7xw5mQo8saflZ3uGUpvNdxVfh1DEliHWmuOyGSan9GrXY4hdSW19Q1yswJ9Ika1zi28P5DZOZCZnjp2Pjh5lhr71+YAxSvHFEgZx20UqGVdoWGAXGFo0Zp5sD0YnOXX+uMi71TY3nTh2PYy0HZCaYMsm0umrC2cYuWYpStwWlksgPNBC9CKJ9UDqGDFQAv7GrFb6N/aqD0hEtl9pX9VYvQLViroR5KZqFXmlVEXmyDNJWS0wkT1aiqPD6fZPynIsEznoYDqdG7Q7qqcs2DPKzOVG7EyHhSj25n0Zyw62PJvcwH2vzz1PN3czSrifwHlaZfUbThuMFNzxPyj1GVeE/rHWRr2guaz1e6wu0foSmhPTL3DwiuqFshVDu/D4aPSPjz/FIK1n9dwQOfu3gk7pL9k4jK+M5lk0LBRy9CB7nn2yD+cStfuFQQ5+riK9kJQ3JV9cbCmuh1n6HF3h5LleimS7GkoynWVL5+KWS6h/AFBLBwgvDHpj+wEAAC8FAABQSwECLQMUAAgACACdu6lUVYIEHGwBAADRAwAAIgAAAAAAAAAAACAApIEAAAAAZXhhbXBsZXMvdG9kb3MvYWR2YW5jZWQuam91cm5leS50c1BLAQItAxQACAAIAJ27qVQvDHpj+wEAAC8FAAAZAAAAAAAAAAAAIACkgbwBAABleGFtcGxlcy90b2Rvcy9oZWxwZXJzLnRzUEsFBgAAAAACAAIAlwAAAP4DAAAAAA==", | ||
}, | ||
false, | ||
}, | ||
{ | ||
"bad encoded content", | ||
mapstr.M{ | ||
"content": "12312edasd", | ||
}, | ||
true, | ||
}, | ||
} | ||
|
||
for _, tc := range testCases { | ||
t.Run(tc.name, func(t *testing.T) { | ||
psrc, err := dummyPSource(tc.cfg) | ||
if tc.wantErr { | ||
err = psrc.Fetch() | ||
require.Error(t, err) | ||
return | ||
} | ||
require.NoError(t, err) | ||
fetchAndValidate(t, psrc) | ||
}) | ||
} | ||
} | ||
|
||
func validateFileContents(t *testing.T, dir string) { | ||
expected := []string{ | ||
"examples/todos/helpers.ts", | ||
"examples/todos/advanced.journey.ts", | ||
} | ||
for _, file := range expected { | ||
_, err := os.Stat(path.Join(dir, file)) | ||
assert.NoError(t, err) | ||
} | ||
} | ||
|
||
func fetchAndValidate(t *testing.T, psrc *PushedSource) { | ||
err := psrc.Fetch() | ||
require.NoError(t, err) | ||
|
||
validateFileContents(t, psrc.Workdir()) | ||
// check if the working directory is deleted | ||
require.NoError(t, psrc.Close()) | ||
_, err = os.Stat(psrc.TargetDirectory) | ||
require.True(t, os.IsNotExist(err), "TargetDirectory %s should have been deleted", psrc.TargetDirectory) | ||
} | ||
|
||
func dummyPSource(conf map[string]interface{}) (*PushedSource, error) { | ||
psrc := &PushedSource{} | ||
y, _ := yaml.Marshal(conf) | ||
c, err := config.NewConfigWithYAML(y, string(y)) | ||
if err != nil { | ||
return nil, err | ||
} | ||
err = c.Unpack(psrc) | ||
return psrc, err | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
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.
Shouldn't we also
defer
theclose
of this file? Although we're already removing it the docs don't mentionRemove
closes the open handle.PS: I found it interesting to learn how these are made to be globally unique
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.
Its explicity handled after the monitor run to completion, we control the close using
p.Close()
on any error and remove these unzipped directories.