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 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473
|
package logging
import (
"bufio"
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"maps"
"net/http"
"net/url"
"os"
"reflect"
"slices"
"sort"
"strconv"
"strings"
"sync"
"time"
"github.com/lxc/incus/v6/internal/server/state"
"github.com/lxc/incus/v6/shared/api"
localtls "github.com/lxc/incus/v6/shared/tls"
)
// This is a modified version of https://github.com/grafana/loki/blob/v1.6.1/pkg/promtail/client/.
const (
contentType = "application/json"
maxErrMsgLen = 1024
)
type config struct {
batchSize int
batchWait time.Duration
caCert string
username string
password string
labels []string
instance string
location string
retry int
timeout time.Duration
url *url.URL
}
type entry struct {
labels LabelSet
Entry
}
// LokiLogger represents a Loki client.
type LokiLogger struct {
common
cfg config
client *http.Client
ctx context.Context
quit chan struct{}
once sync.Once
entries chan entry
wg sync.WaitGroup
}
// NewLokiLogger returns a logger of loki type.
func NewLokiLogger(s *state.State, name string) (*LokiLogger, error) {
urlStr, username, password, caCert, instance, labels, retry := s.GlobalConfig.LoggingConfigForLoki(name)
// Set defaults.
if retry == 0 {
retry = 3
}
// Validate the URL.
u, err := url.Parse(urlStr)
if err != nil {
return nil, err
}
// Handle standalone systems.
var location string
if !s.ServerClustered {
hostname, err := os.Hostname()
if err != nil {
return nil, err
}
location = hostname
if instance == "" {
instance = hostname
}
} else if instance == "" {
instance = s.ServerName
}
loggerClient := LokiLogger{
common: newCommonLogger(name, s.GlobalConfig),
cfg: config{
batchSize: 10 * 1024,
batchWait: 1 * time.Second,
caCert: caCert,
username: username,
password: password,
instance: instance,
location: location,
labels: sliceFromString(labels),
retry: retry,
timeout: 10 * time.Second,
url: u,
},
client: &http.Client{},
ctx: s.ShutdownCtx,
entries: make(chan entry),
quit: make(chan struct{}),
}
if caCert != "" {
tlsConfig, err := localtls.GetTLSConfigMem("", "", caCert, "", false)
if err != nil {
return nil, err
}
loggerClient.client.Transport = &http.Transport{
TLSClientConfig: tlsConfig,
}
} else {
loggerClient.client = http.DefaultClient
}
return &loggerClient, nil
}
func (l *LokiLogger) run() {
batch := newBatch()
minWaitCheckFrequency := 10 * time.Millisecond
maxWaitCheckFrequency := max(l.cfg.batchWait/10, minWaitCheckFrequency)
maxWaitCheck := time.NewTicker(maxWaitCheckFrequency)
defer func() {
// Send all pending batches
l.sendBatch(batch)
l.wg.Done()
}()
for {
select {
case <-l.ctx.Done():
return
case <-l.quit:
return
case e := <-l.entries:
// If adding the entry to the batch will increase the size over the max
// size allowed, we do send the current batch and then create a new one
if batch.sizeBytesAfter(e) > l.cfg.batchSize {
l.sendBatch(batch)
batch = newBatch(e)
break
}
// The max size of the batch isn't reached, so we can add the entry
batch.add(e)
case <-maxWaitCheck.C:
// Send batch if max wait time has been reached
if batch.age() < l.cfg.batchWait {
break
}
l.sendBatch(batch)
batch = newBatch()
}
}
}
func (l *LokiLogger) sendBatch(batch *batch) {
if batch.empty() {
return
}
buf, _, err := batch.encode()
if err != nil {
return
}
var status int
for range l.cfg.retry {
select {
case <-l.quit:
return
default:
// Try to send the message.
status, err = l.send(l.ctx, buf)
if err == nil {
return
}
// Only retry 429s, 500s and connection-level errors.
if status > 0 && status != 429 && status/100 != 5 {
return
}
// Retry every 10s.
time.Sleep(10 * time.Second)
}
}
}
func (l *LokiLogger) send(ctx context.Context, buf []byte) (int, error) {
ctx, cancel := context.WithTimeout(ctx, l.cfg.timeout)
defer cancel()
req, err := http.NewRequest("POST", fmt.Sprintf("%s/loki/api/v1/push", l.cfg.url.String()), bytes.NewReader(buf))
if err != nil {
return -1, err
}
req = req.WithContext(ctx)
req.Header.Set("Content-Type", contentType)
if l.cfg.username != "" && l.cfg.password != "" {
req.SetBasicAuth(l.cfg.username, l.cfg.password)
}
resp, err := l.client.Do(req)
if err != nil {
return -1, err
}
if resp.StatusCode/100 != 2 {
scanner := bufio.NewScanner(io.LimitReader(resp.Body, maxErrMsgLen))
line := ""
if scanner.Scan() {
line = scanner.Text()
}
err = fmt.Errorf("server returned HTTP status %s (%d): %s", resp.Status, resp.StatusCode, line)
}
return resp.StatusCode, err
}
// Start starts the loki logger.
func (l *LokiLogger) Start() error {
l.wg.Add(1)
go l.run()
return nil
}
// Stop stops the client.
func (l *LokiLogger) Stop() {
l.once.Do(func() { close(l.quit) })
l.wg.Wait()
}
// Validate checks whether the logger configuration is correct.
func (l *LokiLogger) Validate() error {
if l.cfg.url.String() == "" {
return fmt.Errorf("%s: URL cannot be empty", l.name)
}
return nil
}
// HandleEvent handles the event received from the internal event listener.
func (l *LokiLogger) HandleEvent(event api.Event) {
if !l.processEvent(event) {
return
}
// Support overriding the location field (used on standalone systems).
location := event.Location
if l.cfg.location != "" {
location = l.cfg.location
}
entry := entry{
labels: LabelSet{
"app": "incus",
"type": event.Type,
"location": location,
"instance": l.cfg.instance,
},
Entry: Entry{
Timestamp: event.Timestamp,
},
}
ctx := make(map[string]string)
switch event.Type {
case api.EventTypeLifecycle:
lifecycleEvent := api.EventLifecycle{}
err := json.Unmarshal(event.Metadata, &lifecycleEvent)
if err != nil {
return
}
if lifecycleEvent.Name != "" {
entry.labels["name"] = lifecycleEvent.Name
}
if lifecycleEvent.Project != "" {
entry.labels["project"] = lifecycleEvent.Project
}
// Build map. These key-value pairs will either be added as labels, or be part of the
// log message itself.
ctx["action"] = lifecycleEvent.Action
ctx["source"] = lifecycleEvent.Source
maps.Copy(ctx, buildNestedContext("context", lifecycleEvent.Context))
if lifecycleEvent.Requestor != nil {
ctx["requester-address"] = lifecycleEvent.Requestor.Address
ctx["requester-protocol"] = lifecycleEvent.Requestor.Protocol
ctx["requester-username"] = lifecycleEvent.Requestor.Username
}
// Get a sorted list of context keys.
keys := make([]string, 0, len(ctx))
for k := range ctx {
keys = append(keys, k)
}
sort.Strings(keys)
// Add key-value pairs as labels but don't override any labels.
for _, k := range keys {
v := ctx[k]
if slices.Contains(l.cfg.labels, k) {
_, ok := entry.labels[k]
if !ok {
// Label names may not contain any hyphens.
entry.labels[strings.ReplaceAll(k, "-", "_")] = v
delete(ctx, k)
}
}
}
messagePrefix := ""
// Add the remaining context as the message prefix.
for k, v := range ctx {
messagePrefix += fmt.Sprintf("%s=\"%s\" ", k, v)
}
entry.Line = fmt.Sprintf("%s%s", messagePrefix, lifecycleEvent.Action)
case api.EventTypeLogging, api.EventTypeNetworkACL:
logEvent := api.EventLogging{}
err := json.Unmarshal(event.Metadata, &logEvent)
if err != nil {
return
}
tmpContext := map[string]any{}
// Convert map[string]string to map[string]any as buildNestedContext takes the latter type.
for k, v := range logEvent.Context {
tmpContext[k] = v
}
// Build map. These key-value pairs will either be added as labels, or be part of the
// log message itself.
ctx["level"] = logEvent.Level
maps.Copy(ctx, buildNestedContext("context", tmpContext))
// Add key-value pairs as labels but don't override any labels.
for k, v := range ctx {
if slices.Contains(l.cfg.labels, k) {
_, ok := entry.labels[k]
if !ok {
entry.labels[k] = v
delete(ctx, k)
}
}
}
keys := make([]string, 0, len(ctx))
for k := range ctx {
keys = append(keys, k)
}
sort.Strings(keys)
var message strings.Builder
// Add the remaining context as the message prefix. The keys are sorted alphabetically.
for _, k := range keys {
message.WriteString(fmt.Sprintf("%s=%q ", k, ctx[k]))
}
message.WriteString(logEvent.Message)
entry.Line = message.String()
}
l.entries <- entry
}
func buildNestedContext(prefix string, m map[string]any) map[string]string {
labels := map[string]string{}
for k, v := range m {
t := reflect.TypeOf(v)
if t != nil && t.Kind() == reflect.Map {
for k, v := range buildNestedContext(k, v.(map[string]any)) {
if prefix == "" {
labels[k] = v
} else {
labels[fmt.Sprintf("%s-%s", prefix, k)] = v
}
}
} else {
if prefix == "" {
labels[k] = fmt.Sprintf("%v", v)
} else {
labels[fmt.Sprintf("%s-%s", prefix, k)] = fmt.Sprintf("%v", v)
}
}
}
return labels
}
// MarshalJSON returns the JSON encoding of Entry.
func (e Entry) MarshalJSON() ([]byte, error) {
return fmt.Appendf(nil, "[\"%d\", %s]", e.Timestamp.UnixNano(), strconv.Quote(e.Line)), nil
}
// String implements the Stringer interface. It returns a formatted/sorted set of label key/value pairs.
func (l LabelSet) String() string {
var b strings.Builder
keys := make([]string, 0, len(l))
for k := range l {
keys = append(keys, k)
}
sort.Strings(keys)
b.WriteByte('{')
for i, k := range keys {
if i > 0 {
b.WriteByte(',')
b.WriteByte(' ')
}
b.WriteString(k)
b.WriteByte('=')
b.WriteString(strconv.Quote(l[k]))
}
b.WriteByte('}')
return b.String()
}
|