/
api.go
184 lines (156 loc) · 6.29 KB
/
api.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
package alertmanager
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/cortexproject/cortex/pkg/alertmanager/alerts"
"github.com/cortexproject/cortex/pkg/util"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
"github.com/prometheus/alertmanager/config"
"github.com/prometheus/alertmanager/template"
"github.com/weaveworks/common/user"
"gopkg.in/yaml.v2"
)
const (
errMarshallingYAML = "error marshalling YAML Alertmanager config"
errValidatingConfig = "error validating Alertmanager config"
errReadingConfiguration = "unable to read the Alertmanager config"
errStoringConfiguration = "unable to store the Alertmanager config"
errDeletingConfiguration = "unable to delete the Alertmanager config"
errNoOrgID = "unable to determine the OrgID"
)
// UserConfig is used to communicate a users alertmanager configs
type UserConfig struct {
TemplateFiles map[string]string `yaml:"template_files"`
AlertmanagerConfig string `yaml:"alertmanager_config"`
}
func (am *MultitenantAlertmanager) GetUserConfig(w http.ResponseWriter, r *http.Request) {
logger := util.WithContext(r.Context(), am.logger)
userID, err := user.ExtractOrgID(r.Context())
if err != nil {
level.Error(logger).Log("msg", errNoOrgID, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errNoOrgID, err.Error()), http.StatusUnauthorized)
return
}
cfg, err := am.store.GetAlertConfig(r.Context(), userID)
if err != nil {
if err == alerts.ErrNotFound {
http.Error(w, err.Error(), http.StatusNotFound)
} else {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return
}
d, err := yaml.Marshal(&UserConfig{
TemplateFiles: alerts.ParseTemplates(cfg),
AlertmanagerConfig: cfg.RawConfig,
})
if err != nil {
level.Error(logger).Log("msg", errMarshallingYAML, "err", err, "user", userID)
http.Error(w, fmt.Sprintf("%s: %s", errMarshallingYAML, err.Error()), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/yaml")
if _, err := w.Write(d); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
func (am *MultitenantAlertmanager) SetUserConfig(w http.ResponseWriter, r *http.Request) {
logger := util.WithContext(r.Context(), am.logger)
userID, err := user.ExtractOrgID(r.Context())
if err != nil {
level.Error(logger).Log("msg", errNoOrgID, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errNoOrgID, err.Error()), http.StatusUnauthorized)
return
}
payload, err := ioutil.ReadAll(r.Body)
if err != nil {
level.Error(logger).Log("msg", errReadingConfiguration, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errReadingConfiguration, err.Error()), http.StatusBadRequest)
return
}
cfg := &UserConfig{}
err = yaml.Unmarshal(payload, cfg)
if err != nil {
level.Error(logger).Log("msg", errMarshallingYAML, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errMarshallingYAML, err.Error()), http.StatusBadRequest)
return
}
cfgDesc := alerts.ToProto(cfg.AlertmanagerConfig, cfg.TemplateFiles, userID)
if err := validateUserConfig(logger, cfgDesc); err != nil {
level.Warn(logger).Log("msg", errValidatingConfig, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errValidatingConfig, err.Error()), http.StatusBadRequest)
return
}
err = am.store.SetAlertConfig(r.Context(), cfgDesc)
if err != nil {
level.Error(logger).Log("msg", errStoringConfiguration, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errStoringConfiguration, err.Error()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusCreated)
}
func (am *MultitenantAlertmanager) DeleteUserConfig(w http.ResponseWriter, r *http.Request) {
logger := util.WithContext(r.Context(), am.logger)
userID, err := user.ExtractOrgID(r.Context())
if err != nil {
level.Error(logger).Log("msg", errNoOrgID, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errNoOrgID, err.Error()), http.StatusUnauthorized)
return
}
err = am.store.DeleteAlertConfig(r.Context(), userID)
if err != nil {
level.Error(logger).Log("msg", errDeletingConfiguration, "err", err.Error())
http.Error(w, fmt.Sprintf("%s: %s", errDeletingConfiguration, err.Error()), http.StatusInternalServerError)
return
}
w.WriteHeader(http.StatusOK)
}
// Partially copied from: https://github.com/prometheus/alertmanager/blob/8e861c646bf67599a1704fc843c6a94d519ce312/cli/check_config.go#L65-L96
func validateUserConfig(logger log.Logger, cfg alerts.AlertConfigDesc) error {
// We don't have a valid use case for empty configurations. If a tenant does not have a
// configuration set and issue a request to the Alertmanager, we'll a) upload an empty
// config and b) immediately start an Alertmanager instance for them if a fallback
// configuration is provisioned.
if cfg.RawConfig == "" {
return fmt.Errorf("configuration provided is empty, if you'd like to remove your configuration please use the delete configuration endpoint")
}
amCfg, err := config.Load(cfg.RawConfig)
if err != nil {
return err
}
// Create templates on disk in a temporary directory.
// Note: This means the validation will succeed if we can write to tmp but
// not to configured data dir, and on the flipside, it'll fail if we can't write
// to tmpDir. Ignoring both cases for now as they're ultra rare but will revisit if
// we see this in the wild.
tmpDir, err := ioutil.TempDir("", "validate-config")
if err != nil {
return err
}
defer os.RemoveAll(tmpDir)
for _, tmpl := range cfg.Templates {
_, err := createTemplateFile(tmpDir, cfg.User, tmpl.Filename, tmpl.Body)
if err != nil {
level.Error(logger).Log("msg", "unable to create template file", "err", err, "user", cfg.User)
return fmt.Errorf("unable to create template file '%s'", tmpl.Filename)
}
}
templateFiles := make([]string, len(amCfg.Templates))
for i, t := range amCfg.Templates {
templateFiles[i] = filepath.Join(tmpDir, "templates", cfg.User, t)
}
_, err = template.FromGlobs(templateFiles...)
if err != nil {
return err
}
// Note: Not validating the MultitenantAlertmanager.transformConfig function as that
// that function shouldn't break configuration. Only way it can fail is if the base
// autoWebhookURL itself is broken. In that case, I would argue, we should accept the config
// not reject it.
return nil
}