Fix reading config files starting with http: (#9275)

This commit is contained in:
Alexander Krantz 2021-05-26 09:13:50 -07:00 committed by GitHub
parent 9ab2ea5ee2
commit 58479fdb05
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
2 changed files with 31 additions and 9 deletions

View File

@ -50,6 +50,10 @@ var (
`\`, `\\`, `\`, `\\`,
) )
httpLoadConfigRetryInterval = 10 * time.Second httpLoadConfigRetryInterval = 10 * time.Second
// fetchURLRe is a regex to determine whether the requested file should
// be fetched from a remote or read from the filesystem.
fetchURLRe = regexp.MustCompile(`^\w+://`)
) )
// Config specifies the URL/user/password for the database that telegraf // Config specifies the URL/user/password for the database that telegraf
@ -902,6 +906,7 @@ func escapeEnv(value string) string {
} }
func loadConfig(config string) ([]byte, error) { func loadConfig(config string) ([]byte, error) {
if fetchURLRe.MatchString(config) {
u, err := url.Parse(config) u, err := url.Parse(config)
if err != nil { if err != nil {
return nil, err return nil, err
@ -911,8 +916,11 @@ func loadConfig(config string) ([]byte, error) {
case "https", "http": case "https", "http":
return fetchConfig(u) return fetchConfig(u)
default: default:
// If it isn't a https scheme, try it as a file. return nil, fmt.Errorf("scheme %q not supported", u.Scheme)
} }
}
// If it isn't a https scheme, try it as a file
return ioutil.ReadFile(config) return ioutil.ReadFile(config)
} }

View File

@ -5,6 +5,7 @@ import (
"net/http" "net/http"
"net/http/httptest" "net/http/httptest"
"os" "os"
"runtime"
"strings" "strings"
"testing" "testing"
"time" "time"
@ -323,6 +324,19 @@ func TestConfig_URLRetries3FailsThenPasses(t *testing.T) {
require.Equal(t, 4, responseCounter) require.Equal(t, 4, responseCounter)
} }
func TestConfig_URLLikeFileName(t *testing.T) {
c := NewConfig()
err := c.LoadConfig("http:##www.example.com.conf")
require.Error(t, err)
if runtime.GOOS == "windows" {
// The error file not found error message is different on windows
require.Equal(t, "Error loading config file http:##www.example.com.conf: open http:##www.example.com.conf: The system cannot find the file specified.", err.Error())
} else {
require.Equal(t, "Error loading config file http:##www.example.com.conf: open http:##www.example.com.conf: no such file or directory", err.Error())
}
}
/*** Mockup INPUT plugin for testing to avoid cyclic dependencies ***/ /*** Mockup INPUT plugin for testing to avoid cyclic dependencies ***/
type MockupInputPlugin struct { type MockupInputPlugin struct {
Servers []string `toml:"servers"` Servers []string `toml:"servers"`