-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathfile.go
142 lines (114 loc) · 2.54 KB
/
file.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
package outputs
import (
"context"
"fmt"
"os"
"strings"
yaml "gopkg.in/yaml.v1"
"github.com/camptocamp/prometheus-puppetdb-sd/internal/config"
"github.com/camptocamp/prometheus-puppetdb-sd/internal/types"
)
// FileOutput stores values needed by the File output
type FileOutput struct {
filename string
filenamePattern string
directory string
format config.OutputFormat
state struct {
oldPaths map[string]struct{}
}
}
func setupFileOutput(cfg *config.OutputConfig) (*FileOutput, error) {
err := os.MkdirAll(cfg.File.Directory, 0755)
return &FileOutput{
filename: cfg.File.Filename,
filenamePattern: cfg.File.FilenamePattern,
directory: cfg.File.Directory,
format: cfg.Format,
}, err
}
// WriteOutput writes Prometheus configuration to files
func (o *FileOutput) WriteOutput(ctx context.Context, scrapeConfigs []*types.ScrapeConfig) (err error) {
var c []byte
var mc []byte
switch o.format {
case config.ScrapeConfigs:
c, err = yaml.Marshal(scrapeConfigs)
if err != nil {
return
}
path := fmt.Sprintf("%s/%s", o.directory, o.filename)
err = writeFile(path, c)
if err != nil {
return
}
case config.StaticConfigs, config.MergedStaticConfigs:
paths := map[string]struct{}{}
for _, scrapeConfig := range scrapeConfigs {
c, err = yaml.Marshal(scrapeConfig.StaticConfigs)
if err != nil {
return
}
if o.format == config.MergedStaticConfigs {
mc = append(mc, c...)
} else {
path := fmt.Sprintf("%s/%s", o.directory, strings.Replace(o.filenamePattern, "*", scrapeConfig.JobName, 1))
err = writeFile(path, c)
if err != nil {
return
}
paths[path] = struct{}{}
delete(o.state.oldPaths, path)
}
}
if o.format == config.MergedStaticConfigs {
path := fmt.Sprintf("%s/%s", o.directory, o.filename)
err = writeFile(path, mc)
if err != nil {
return
}
} else {
for path := range o.state.oldPaths {
err = os.Remove(path)
if err != nil {
return
}
}
}
o.state.oldPaths = paths
default:
err = fmt.Errorf("unexpected output format '%s'", o.format)
return
}
return
}
func writeFile(path string, content []byte) (err error) {
tmpPath := path + ".tmp"
f, err := os.Create(tmpPath)
if err != nil {
return
}
defer func() {
if err != nil {
f.Close()
os.Remove(tmpPath)
}
}()
_, err = f.Write(content)
if err != nil {
return
}
err = f.Sync()
if err != nil {
return
}
err = f.Close()
if err != nil {
return
}
err = os.Rename(tmpPath, path)
if err != nil {
return
}
return
}