-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathwebhook.go
More file actions
171 lines (155 loc) · 4.5 KB
/
Copy pathwebhook.go
File metadata and controls
171 lines (155 loc) · 4.5 KB
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
// Package webhook implements an output.Sink that POSTs each event as
// JSON to a configured URL.
//
// Configuration (YAML keys):
//
// plugin: webhook
// config:
// url: https://ops.example.com/pg-hardstorage
// method: POST # default POST; PUT also accepted
// auth_header: "Bearer eyJ..." # optional; sent as Authorization
// content_type: application/json # default; override only for niche endpoints
// min_severity: warning # default: notice
// timeout: 10s # default
//
// The body is the same Event JSON the dispatcher renders (schema =
// pg_hardstorage.v1) — operators wanting a different shape can put a
// transformer in front. Same-shape-everywhere keeps the data plane
// boring on purpose.
package webhook
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net/http"
"strings"
"sync"
"time"
"github.com/cybertec-postgresql/pg_hardstorage/internal/airgap"
"github.com/cybertec-postgresql/pg_hardstorage/internal/output"
)
func init() {
output.DefaultSinkRegistry.Register("webhook", NewFromSpec)
}
// Sink POSTs JSON-encoded events to a fixed URL.
type Sink struct {
name string
url string
method string
authHeader string
contentType string
minSeverity output.Severity
httpClient *http.Client
mu sync.Mutex
closed bool
}
// NewFromSpec is the SinkBuilder.
func NewFromSpec(spec output.SinkSpec) (output.Sink, error) {
url, err := output.SinkConfigString(spec.Config, "url")
if err != nil {
return nil, err
}
if url == "" {
return nil, errors.New("webhook: config.url is required")
}
if err := airgap.Default().EndpointAllowed(url); err != nil {
return nil, fmt.Errorf("webhook: %w", err)
}
method, err := output.SinkConfigStringDefault(spec.Config, "method", http.MethodPost)
if err != nil {
return nil, err
}
method = strings.ToUpper(method)
switch method {
case http.MethodPost, http.MethodPut:
default:
return nil, fmt.Errorf("webhook: unsupported method %q (allowed: POST, PUT)", method)
}
authHeader, err := output.SinkConfigString(spec.Config, "auth_header")
if err != nil {
return nil, err
}
contentType, err := output.SinkConfigStringDefault(spec.Config, "content_type", "application/json")
if err != nil {
return nil, err
}
minSevStr, err := output.SinkConfigStringDefault(spec.Config, "min_severity", "notice")
if err != nil {
return nil, err
}
minSev, perr := output.ParseSeverity(minSevStr)
if perr != nil {
return nil, fmt.Errorf("webhook: %w", perr)
}
timeoutStr, err := output.SinkConfigStringDefault(spec.Config, "timeout", "10s")
if err != nil {
return nil, err
}
timeout, perr := time.ParseDuration(timeoutStr)
if perr != nil {
return nil, fmt.Errorf("webhook: parse timeout %q: %w", timeoutStr, perr)
}
return &Sink{
name: spec.Name,
url: url,
method: method,
authHeader: authHeader,
contentType: contentType,
minSeverity: minSev,
httpClient: &http.Client{Timeout: timeout},
}, nil
}
// Name implements output.Sink.
func (s *Sink) Name() string { return s.name }
// Open implements output.Sink. No-op (each Emit owns its request).
func (s *Sink) Open(_ context.Context, _ map[string]any) error { return nil }
// Emit implements output.Sink.
func (s *Sink) Emit(ctx context.Context, ev *output.Event) error {
s.mu.Lock()
if s.closed {
s.mu.Unlock()
return errors.New("webhook: sink closed")
}
s.mu.Unlock()
if !ev.Severity.AtLeast(s.minSeverity) {
return nil
}
// Pre-Emit ctx check (consistent with syslog / email / opsgenie /
// pagerduty / slack). Already-cancelled ctx bails before any
// network work.
if err := ctx.Err(); err != nil {
return err
}
body, err := json.Marshal(ev)
if err != nil {
return fmt.Errorf("webhook: marshal: %w", err)
}
req, err := http.NewRequestWithContext(ctx, s.method, s.url, bytes.NewReader(body))
if err != nil {
return fmt.Errorf("webhook: build request: %w", err)
}
req.Header.Set("Content-Type", s.contentType)
if s.authHeader != "" {
req.Header.Set("Authorization", s.authHeader)
}
resp, err := s.httpClient.Do(req)
if err != nil {
return fmt.Errorf("webhook: post: %w", err)
}
defer resp.Body.Close()
if resp.StatusCode/100 != 2 {
body, _ := io.ReadAll(io.LimitReader(resp.Body, 512))
return fmt.Errorf("webhook: status %d: %s", resp.StatusCode, strings.TrimSpace(string(body)))
}
return nil
}
// Close implements output.Sink.
func (s *Sink) Close() error {
s.mu.Lock()
defer s.mu.Unlock()
s.closed = true
return nil
}