forked from saymedia/journald-cloudwatch-logs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
config.go
241 lines (206 loc) · 6.01 KB
/
config.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
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
package main
import (
"fmt"
"io/ioutil"
"os"
"reflect"
"strings"
"github.com/aws/aws-sdk-go/aws"
awsCredentials "github.com/aws/aws-sdk-go/aws/credentials"
"github.com/aws/aws-sdk-go/aws/credentials/ec2rolecreds"
"github.com/aws/aws-sdk-go/aws/ec2metadata"
awsSession "github.com/aws/aws-sdk-go/aws/session"
"github.com/hashicorp/hcl"
)
type Config struct {
AWSCredentials *awsCredentials.Credentials
AWSRegion string
EC2InstanceId string
LogGroupName string
LogStreamName string
LogPriority Priority
StateFilename string
JournalDir string
BufferSize int
}
type fileConfig struct {
AWSRegion string `hcl:"aws_region"`
EC2InstanceId string `hcl:"ec2_instance_id"`
LogGroupName string `hcl:"log_group"`
LogStreamName string `hcl:"log_stream"`
LogPriority string `hcl:"log_priority"`
StateFilename string `hcl:"state_file"`
JournalDir string `hcl:"journal_dir"`
BufferSize int `hcl:"buffer_size"`
}
func getLogLevel(priority string) (Priority, error) {
logLevels := map[Priority][]string{
EMERGENCY: {"0", "emerg"},
ALERT: {"1", "alert"},
CRITICAL: {"2", "crit"},
ERROR: {"3", "err"},
WARNING: {"4", "warning"},
NOTICE: {"5", "notice"},
INFO: {"6", "info"},
DEBUG: {"7", "debug"},
}
for i, s := range logLevels {
if s[0] == priority || s[1] == priority {
return i, nil
}
}
return DEBUG, fmt.Errorf("'%s' is unsupported log priority", priority)
}
func LoadConfig(filename string) (*Config, error) {
configBytes, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
var fConfig fileConfig
err = hcl.Decode(&fConfig, string(configBytes))
if err != nil {
return nil, err
}
if fConfig.LogGroupName == "" {
return nil, fmt.Errorf("log_group is required")
}
if fConfig.StateFilename == "" {
return nil, fmt.Errorf("state_file is required")
}
metaClient := ec2metadata.New(awsSession.New(&aws.Config{}))
expandFileConfig(&fConfig, metaClient)
config := &Config{}
if fConfig.AWSRegion != "" {
config.AWSRegion = fConfig.AWSRegion
} else {
region, err := metaClient.Region()
if err != nil {
return nil, fmt.Errorf("unable to detect AWS region: %s", err)
}
config.AWSRegion = region
}
if fConfig.EC2InstanceId != "" {
config.EC2InstanceId = fConfig.EC2InstanceId
} else {
instanceId, err := metaClient.GetMetadata("instance-id")
if err != nil {
return nil, fmt.Errorf("unable to detect EC2 instance id: %s", err)
}
config.EC2InstanceId = instanceId
}
if fConfig.LogPriority == "" {
// Log everything
config.LogPriority = DEBUG
} else {
config.LogPriority, err = getLogLevel(fConfig.LogPriority)
if err != nil {
return nil, fmt.Errorf("The provided log filtering '%s' is unsupported by systemd!", fConfig.LogPriority)
}
}
config.LogGroupName = fConfig.LogGroupName
if fConfig.LogStreamName != "" {
config.LogStreamName = fConfig.LogStreamName
} else {
// By default we use the instance id as the stream name.
config.LogStreamName = config.EC2InstanceId
}
config.StateFilename = fConfig.StateFilename
config.JournalDir = fConfig.JournalDir
if fConfig.BufferSize != 0 {
config.BufferSize = fConfig.BufferSize
} else {
config.BufferSize = 100
}
config.AWSCredentials = awsCredentials.NewChainCredentials([]awsCredentials.Provider{
&awsCredentials.EnvProvider{},
&ec2rolecreds.EC2RoleProvider{
Client: metaClient,
},
})
return config, nil
}
func (c *Config) NewAWSSession() *awsSession.Session {
config := &aws.Config{
Credentials: c.AWSCredentials,
Region: aws.String(c.AWSRegion),
MaxRetries: aws.Int(3),
}
return awsSession.New(config)
}
/*
* Expand variables of the form $Foo or ${Foo} in the user provided config
* from the EC2Metadata Instance Identity Document
* [ https://docs.aws.amazon.com/sdk-for-go/api/aws/ec2metadata/#EC2InstanceIdentityDocument ]
* or the environment
*/
func expandFileConfig(config *fileConfig, metaClient *ec2metadata.EC2Metadata) {
vars := make(map[string]string)
// If we can fetch the InstanceIdentityDocument then iterate over the
// struct extracting the string fields and their values into the vars map
data, err := metaClient.GetInstanceIdentityDocument()
if err == nil {
metadata := reflect.ValueOf( data )
for i := 0; i < metadata.NumField(); i++ {
field := metadata.Field(i)
ftype := metadata.Type().Field(i)
if (field.Type() != reflect.TypeOf("")) {
continue
}
vars[ftype.Name] = fmt.Sprintf("%v", field.Interface())
}
}
// Iterate over all the string fields in the fileConfig struct performing
// Variable expansion on them, with EC2 Instance Identity fields overriding
// the OS environment
rconfig := reflect.ValueOf(config)
for i := 0; i < rconfig.Elem().NumField(); i++ {
field := rconfig.Elem().Field(i)
if field.Type() != reflect.TypeOf("") {
continue
}
val := field.Interface().(string)
if val != "" {
field.SetString(
expandBraceVars(
val,
func(varname string) string {
if strings.HasPrefix(varname, "instance.") {
if val, exists := vars[strings.TrimPrefix(varname, "instance.")]; exists {
return val
}
// Unknown key => empty string
return ""
} else if (strings.HasPrefix(varname, "env.")) {
return os.Getenv(strings.TrimPrefix(varname, "env."))
} else {
// Unknown prefix => empty string
return ""
}
},
),
)
}
}
}
// Modified version of os.Expand() that only expands ${name} and not $name
func expandBraceVars(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+3 < len(s) && s[j+1] == '{' {
buf = append(buf, s[i:j]...)
idx := strings.Index(s[j+2:], "}")
if (idx >= 0) {
// We have a full ${name} string
buf = append(buf, mapping(s[j+2:j+2+idx])...)
j += 2+idx
} else {
// We ran out of string (unclosed ${)
return string(buf)
}
i = j + 1
}
}
return string(buf) + s[i:]
}