-
Notifications
You must be signed in to change notification settings - Fork 74
/
Copy pathfiles.go
85 lines (78 loc) · 2.56 KB
/
files.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
// Copyright 2020 Google LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package confgenerator
import (
"context"
"fmt"
"os"
"path/filepath"
)
// ReadUnifiedConfigFromFile reads the user config file and returns a UnifiedConfig.
// If the user config file does not exist, it returns nil.
func ReadUnifiedConfigFromFile(ctx context.Context, path string) (*UnifiedConfig, error) {
if _, err := os.Stat(path); err != nil {
if os.IsNotExist(err) {
// If the user config file does not exist, we don't want any overrides.
return nil, nil
}
return nil, fmt.Errorf("failed to retrieve the user config file %q: %w \n", path, err)
}
data, err := os.ReadFile(path)
if err != nil {
return nil, err
}
uc, err := UnmarshalYamlToUnifiedConfig(ctx, data)
if err != nil {
return nil, err
}
return uc, nil
}
func (uc *UnifiedConfig) GenerateFilesFromConfig(ctx context.Context, service, logsDir, stateDir, outDir string) error {
switch service {
case "": // Validate-only.
return nil
case "fluentbit":
files, err := uc.GenerateFluentBitConfigs(ctx, logsDir, stateDir)
if err != nil {
return fmt.Errorf("can't parse configuration: %w", err)
}
for name, contents := range files {
if err = WriteConfigFile([]byte(contents), filepath.Join(outDir, name)); err != nil {
return err
}
}
case "otel":
otelConfig, err := uc.GenerateOtelConfig(ctx, outDir)
if err != nil {
return fmt.Errorf("can't parse configuration: %w", err)
}
if err = WriteConfigFile([]byte(otelConfig), filepath.Join(outDir, "otel.yaml")); err != nil {
return err
}
default:
return fmt.Errorf("unknown service %q", service)
}
return nil
}
func WriteConfigFile(content []byte, path string) error {
// Make sure the directory exists before writing the file.
if err := os.MkdirAll(filepath.Dir(path), 0755); err != nil {
return fmt.Errorf("failed to create directory for %q: %w", path, err)
}
content = append(content, []byte("\n")...)
if err := os.WriteFile(path, content, 0644); err != nil {
return fmt.Errorf("failed to write file to %q: %w", path, err)
}
return nil
}