File: common.go

package info (click to toggle)
incus 6.0.5-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 24,392 kB
  • sloc: sh: 16,313; ansic: 3,121; python: 457; makefile: 337; ruby: 51; sql: 50; lisp: 6
file content (97 lines) | stat: -rw-r--r-- 2,383 bytes parent folder | download | duplicates (3)
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
package logging

import (
	"encoding/json"

	"github.com/sirupsen/logrus"

	clusterConfig "github.com/lxc/incus/v6/internal/server/cluster/config"
	"github.com/lxc/incus/v6/shared/api"
)

// Logger is an interface that must be implemented by all loggers.
type Logger interface {
	HandleEvent(event api.Event)
	Start() error
	Stop()
	Validate() error
}

// common embeds shared configuration fields for all logger types.
type common struct {
	lifecycleProjects []string
	lifecycleTypes    []string
	loggingLevel      string
	name              string
	types             []string
}

// newCommonLogger instantiates a new common logger.
func newCommonLogger(name string, cfg *clusterConfig.Config) common {
	lifecycleProjects, lifecycleTypes, loggingLevel, types := cfg.LoggingCommonConfig(name)

	return common{
		loggingLevel:      loggingLevel,
		lifecycleProjects: sliceFromString(lifecycleProjects),
		lifecycleTypes:    sliceFromString(lifecycleTypes),
		name:              name,
		types:             sliceFromString(types),
	}
}

// processEvent verifies whether the event should be processed for the specific logger.
func (c *common) processEvent(event api.Event) bool {
	switch event.Type {
	case api.EventTypeLifecycle:
		if !contains(c.types, "lifecycle") {
			return false
		}

		lifecycleEvent := api.EventLifecycle{}

		err := json.Unmarshal(event.Metadata, &lifecycleEvent)
		if err != nil {
			return false
		}

		if lifecycleEvent.Project != "" && len(c.lifecycleProjects) > 0 {
			if !contains(c.lifecycleProjects, lifecycleEvent.Project) {
				return false
			}
		}

		if len(c.lifecycleTypes) > 0 && !hasAnyPrefix(c.lifecycleTypes, lifecycleEvent.Action) {
			return false
		}

		return true
	case api.EventTypeLogging, api.EventTypeNetworkACL:
		if !contains(c.types, "logging") && event.Type == api.EventTypeLogging {
			return false
		}

		if !contains(c.types, "network-acl") && event.Type == api.EventTypeNetworkACL {
			return false
		}

		logEvent := api.EventLogging{}

		err := json.Unmarshal(event.Metadata, &logEvent)
		if err != nil {
			return false
		}

		// The errors can be ignored as the values are validated elsewhere.
		l1, _ := logrus.ParseLevel(logEvent.Level)
		l2, _ := logrus.ParseLevel(c.loggingLevel)

		// Only consider log messages with a certain log level.
		if l2 < l1 {
			return false
		}

		return true
	default:
		return false
	}
}