This repository has been archived by the owner on Dec 21, 2019. It is now read-only.
forked from elastic/beats
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cfgfile.go
169 lines (147 loc) · 4.78 KB
/
cfgfile.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
package cfgfile
import (
"flag"
"fmt"
"io/ioutil"
"os"
"path/filepath"
"strings"
"github.com/elastic/beats/libbeat/common"
"github.com/elastic/beats/libbeat/logp"
)
// Command line flags.
var (
// The default config cannot include the beat name as it is not initialized
// when this variable is created. See ChangeDefaultCfgfileFlag which should
// be called prior to flags.Parse().
configfile = flag.String("c", "beat.yml", "Configuration file")
testConfig = flag.Bool("configtest", false, "Test configuration and exit.")
)
// ChangeDefaultCfgfileFlag replaces the value and default value for the `-c`
// flag so that it reflects the beat name.
func ChangeDefaultCfgfileFlag(beatName string) error {
cliflag := flag.Lookup("c")
if cliflag == nil {
return fmt.Errorf("Flag -c not found")
}
path, err := filepath.Abs(filepath.Dir(os.Args[0]))
if err != nil {
return fmt.Errorf("Failed to set default config file location because "+
"the absolute path to %s could not be obtained. %v",
os.Args[0], err)
}
cliflag.DefValue = filepath.Join(path, beatName+".yml")
return cliflag.Value.Set(cliflag.DefValue)
}
// Deprecated: Please use Load().
//
// Read reads the configuration from a YAML file into the given interface
// structure. If path is empty this method reads from the configuration
// file specified by the '-c' command line flag.
func Read(out interface{}, path string) error {
config, err := Load(path)
if err != nil {
return nil
}
return config.Unpack(out)
}
// Load reads the configuration from a YAML file structure. If path is empty
// this method reads from the configuration file specified by the '-c' command
// line flag.
func Load(path string) (*common.Config, error) {
if path == "" {
path = *configfile
}
fileContent, err := ioutil.ReadFile(path)
if err != nil {
return nil, fmt.Errorf("failed to read %s: %v", path, err)
}
fileContent = expandEnv(fileContent)
config, err := common.NewConfigWithYAML(fileContent, path)
if err != nil {
return nil, fmt.Errorf("YAML config parsing failed on %s: %v", path, err)
}
return config, nil
}
// IsTestConfig returns whether or not this is configuration used for testing
func IsTestConfig() bool {
return *testConfig
}
// expandEnv replaces ${var} in config according to the values of the current
// environment variables. The replacement is case-sensitive. References to
// undefined variables are replaced by the empty string. A default value can be
// given by using the form ${var:default value}.
func expandEnv(config []byte) []byte {
return []byte(expand(string(config), func(key string) string {
keyAndDefault := strings.SplitN(key, ":", 2)
key = keyAndDefault[0]
v := os.Getenv(key)
if v == "" && len(keyAndDefault) == 2 {
// Set value to the default.
v = keyAndDefault[1]
logp.Info("Replacing config environment variable '${%s}' with "+
"default '%s'", key, keyAndDefault[1])
} else {
logp.Info("Replacing config environment variable '${%s}' with '%s'",
key, v)
}
return v
}))
}
// The following methods were copied from the os package of the stdlib. The
// expand method was modified to only expand variables defined with braces and
// ignore $var.
// Expand replaces ${var} in the string based on the mapping function.
func expand(s string, mapping func(string) string) string {
buf := make([]byte, 0, 2*len(s))
// ${} is all ASCII, so bytes are fine for this operation.
i := 0
for j := 0; j < len(s); j++ {
if s[j] == '$' && j+2 < len(s) && s[j+1] == '{' {
buf = append(buf, s[i:j]...)
name, w := getShellName(s[j+1:])
buf = append(buf, mapping(name)...)
j += w
i = j + 1
}
}
return string(buf) + s[i:]
}
// isShellSpecialVar reports whether the character identifies a special
// shell variable such as $*.
func isShellSpecialVar(c uint8) bool {
switch c {
case '*', '#', '$', '@', '!', '?', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9':
return true
}
return false
}
// isAlphaNum reports whether the byte is an ASCII letter, number, or underscore
func isAlphaNum(c uint8) bool {
return c == '_' || '0' <= c && c <= '9' || 'a' <= c && c <= 'z' || 'A' <= c && c <= 'Z'
}
// getShellName returns the name that begins the string and the number of bytes
// consumed to extract it. If the name is enclosed in {}, it's part of a ${}
// expansion and two more bytes are needed than the length of the name.
func getShellName(s string) (string, int) {
switch {
case s[0] == '{':
if len(s) > 2 && isShellSpecialVar(s[1]) && s[2] == '}' {
return s[1:2], 3
}
// Scan to closing brace
for i := 1; i < len(s); i++ {
if s[i] == '}' {
return s[1:i], i + 1
}
}
return "", 1 // Bad syntax; just eat the brace.
case isShellSpecialVar(s[0]):
return s[0:1], 1
}
// Scan alphanumerics.
var i int
for i = 0; i < len(s) && isAlphaNum(s[i]); i++ {
}
return s[:i], i
}