Skip to content

Commit

Permalink
use a global method for the logs
Browse files Browse the repository at this point in the history
Signed-off-by: Thomas Labarussias <issif_github@gadz.org>
  • Loading branch information
Issif committed Jan 27, 2025
1 parent b1f3b1a commit c8c54ca
Show file tree
Hide file tree
Showing 68 changed files with 566 additions and 484 deletions.
41 changes: 20 additions & 21 deletions config.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ package main

import (
"fmt"
"log"
"net"
"os"
"path"
Expand All @@ -16,11 +15,11 @@ import (
"text/template"
"time"

"github.com/falcosecurity/falcosidekick/outputs/otlpmetrics"

kingpin "github.com/alecthomas/kingpin/v2"
"github.com/spf13/viper"

"github.com/falcosecurity/falcosidekick/internal/pkg/utils"
"github.com/falcosecurity/falcosidekick/outputs/otlpmetrics"
"github.com/falcosecurity/falcosidekick/types"
)

Expand Down Expand Up @@ -425,7 +424,7 @@ func init() {

// Merge http outputs defaults with other outputs defaults
if _, ok := outputDefaults[name]; ok {
panic(fmt.Sprintf("key %v already set in the output defaults", name))
utils.Log(utils.FatalLvl, "", fmt.Sprintf("key %v already set in the output defaults", name))
}
outputDefaults[name] = dst
}
Expand Down Expand Up @@ -599,7 +598,7 @@ func getConfig() *types.Configuration {
v.AddConfigPath(d)
err := v.ReadInConfig()
if err != nil {
log.Printf("[ERROR] : Error when reading config file : %v\n", err)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("Error when reading config file : %v", err))
}
}
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
Expand All @@ -622,7 +621,7 @@ func getConfig() *types.Configuration {
c.Elasticsearch.CustomHeaders = v.GetStringMapString("Elasticsearch.CustomHeaders")

if err := v.Unmarshal(c); err != nil {
log.Printf("[ERROR] : Error unmarshalling config : %s", err)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("Error unmarshalling config : %s", err))
}

if value, present := os.LookupEnv("TLSSERVER_NOTLSPATHS"); present {
Expand All @@ -642,7 +641,7 @@ func getConfig() *types.Configuration {
if s := os.Getenv(tagkeys[1][1:]); s != "" {
c.Customfields[tagkeys[0]] = s
} else {
log.Printf("[ERROR] : Can't find env var %v for custom fields", tagkeys[1][1:])
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("Can't find env var %v for custom fields", tagkeys[1][1:]))
}
} else {
c.Customfields[tagkeys[0]] = tagkeys[1]
Expand All @@ -657,7 +656,7 @@ func getConfig() *types.Configuration {
tagkeys := strings.Split(label, ":")
if len(tagkeys) == 2 {
if _, err := template.New("").Parse(tagkeys[1]); err != nil {
log.Printf("[ERROR] : Error parsing templated fields %v : %s", tagkeys[0], err)
utils.Log(utils.ErrorPrefix, "", fmt.Sprintf("Error parsing templated fields %v : %s", tagkeys[0], err))
} else {
c.Templatedfields[tagkeys[0]] = tagkeys[1]
}
Expand Down Expand Up @@ -693,7 +692,7 @@ func getConfig() *types.Configuration {
labelName, labelValue, found := strings.Cut(labelData, ":")
labelName, labelValue = strings.TrimSpace(labelName), strings.TrimSpace(labelValue)
if !promKVNameRegex.MatchString(labelName) {
log.Printf("[ERROR] : AlertManager - Extra label name '%v' is not valid", labelName)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("AlertManager - Extra label name '%v' is not valid", labelName))
} else if found {
c.Alertmanager.ExtraLabels[labelName] = labelValue
} else {
Expand All @@ -708,7 +707,7 @@ func getConfig() *types.Configuration {
annotationName, annotationValue, found := strings.Cut(annotationData, ":")
annotationName, annotationValue = strings.TrimSpace(annotationName), strings.TrimSpace(annotationValue)
if !promKVNameRegex.MatchString(annotationName) {
log.Printf("[ERROR] : AlertManager - Extra annotation name '%v' is not valid", annotationName)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("AlertManager - Extra annotation name '%v' is not valid", annotationName))
} else if found {
c.Alertmanager.ExtraAnnotations[annotationName] = annotationValue
} else {
Expand All @@ -723,12 +722,12 @@ func getConfig() *types.Configuration {
priorityString, severityValue, found := strings.Cut(severitymatch, ":")
priority := types.Priority(priorityString)
if priority == types.Default {
log.Printf("[ERROR] : AlertManager - Priority '%v' is not a valid falco priority level", priorityString)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("AlertManager - Priority '%v' is not a valid falco priority level", priorityString))
continue
} else if found {
c.Alertmanager.CustomSeverityMap[priority] = strings.TrimSpace(severityValue)
} else {
log.Printf("[ERROR] : AlertManager - No severity given to '%v' (tuple extracted: '%v')", priorityString, severitymatch)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("AlertManager - No severity given to '%v' (tuple extracted: '%v')", priorityString, severitymatch))
}
}
}
Expand Down Expand Up @@ -763,7 +762,7 @@ func getConfig() *types.Configuration {
envName, envValue, found := strings.Cut(extraEnvVarData, ":")
envName, envValue = strings.TrimSpace(envName), strings.TrimSpace(envValue)
if !promKVNameRegex.MatchString(envName) {
log.Printf("[ERROR] : OTLPTraces - Extra Env Var name '%v' is not valid", envName)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("OTLPTraces - Extra Env Var name '%v' is not valid", envName))
} else if found {
c.OTLP.Traces.ExtraEnvVars[envName] = envValue
} else {
Expand All @@ -778,7 +777,7 @@ func getConfig() *types.Configuration {
envName, envValue, found := strings.Cut(extraEnvVarData, ":")
envName, envValue = strings.TrimSpace(envName), strings.TrimSpace(envValue)
if !promKVNameRegex.MatchString(envName) {
log.Printf("[ERROR] : OTLPMetrics - Extra Env Var name '%v' is not valid", envName)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("OTLPMetrics - Extra Env Var name '%v' is not valid", envName))
} else if found {
c.OTLP.Metrics.ExtraEnvVars[envName] = envValue
} else {
Expand All @@ -795,15 +794,15 @@ func getConfig() *types.Configuration {
}

if c.ListenPort == 0 || c.ListenPort > 65536 {
log.Fatalf("[ERROR] : Bad listening port number\n")
utils.Log(utils.FatalLvl, "", "Bad listening port number")
}

if c.TLSServer.NoTLSPort == 0 || c.TLSServer.NoTLSPort > 65536 {
log.Fatalf("[ERROR] : Bad noTLS server port number\n")
utils.Log(utils.FatalLvl, "", "Bad noTLS server port number")
}

if ip := net.ParseIP(c.ListenAddress); c.ListenAddress != "" && ip == nil {
log.Fatalf("[ERROR] : Failed to parse ListenAddress")
utils.Log(utils.FatalLvl, "", "Failed to parse ListenAddress")
}

if c.Loki.ExtraLabels != "" {
Expand Down Expand Up @@ -840,17 +839,17 @@ func getConfig() *types.Configuration {
for _, threshold := range thresholds {
values := strings.SplitN(threshold, ":", 2)
if len(values) != 2 {
log.Printf("[ERROR] : AlertManager - Fail to parse threshold - No priority given for threshold %v", threshold)
utils.Log(utils.ErrorLvl, "AlertManager", fmt.Sprintf("Fail to parse threshold - No priority given for threshold %v", threshold))
continue
}
valueString := strings.TrimSpace(values[0])
valueInt, err := strconv.ParseInt(valueString, 10, 64)
if len(values) != 2 || err != nil {
log.Printf("[ERROR] : AlertManager - Fail to parse threshold - Atoi fail %v", threshold)
utils.Log(utils.ErrorLvl, "AlertManager", fmt.Sprintf("Fail to parse threshold - Atoi fail %v", threshold))
continue
}
if p := strings.TrimSpace(values[1]); p == "" {
log.Printf("[ERROR] : AlertManager - Priority '%v' is not a valid falco priority level", p)
utils.Log(utils.ErrorLvl, "AlertManager", fmt.Sprintf("Priority '%v' is not a valid falco priority level", p))
continue
}
priority := types.Priority(strings.TrimSpace(values[1]))
Expand Down Expand Up @@ -949,7 +948,7 @@ func getMessageFormatTemplate(output, temp string) *template.Template {
var err error
t, err := template.New(output).Parse(temp)
if err != nil {
log.Fatalf("[ERROR] : Error compiling %v message template : %v\n", output, err)
utils.Log(utils.FatalLvl, "", fmt.Sprintf("Error compiling %v message template : %v", output, err))
}
return t
}
Expand Down
15 changes: 8 additions & 7 deletions handlers.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,20 +6,21 @@ import (
"bytes"
"encoding/json"
"fmt"
"go.opentelemetry.io/otel/attribute"
"io"
"log"
"net/http"
"sort"
"strconv"
"strings"
"text/template"
"time"

"github.com/falcosecurity/falcosidekick/types"
"github.com/google/uuid"
"go.opentelemetry.io/otel/attribute"
"golang.org/x/text/cases"
"golang.org/x/text/language"

"github.com/falcosecurity/falcosidekick/internal/pkg/utils"
"github.com/falcosecurity/falcosidekick/types"
)

const (
Expand Down Expand Up @@ -90,7 +91,7 @@ func healthHandler(w http.ResponseWriter, r *http.Request) {

// testHandler sends a test event to all enabled outputs.
func testHandler(w http.ResponseWriter, r *http.Request) {
r.Body = io.NopCloser(bytes.NewReader([]byte(`{"output":"This is a test from falcosidekick","priority":"Debug","hostname": "falcosidekick", "rule":"Test rule", "time":"` + time.Now().UTC().Format(time.RFC3339) + `","output_fields": {"proc.name":"falcosidekick","user.name":"falcosidekick"}, "tags":["test","example"]}`)))
r.Body = io.NopCloser(bytes.NewReader([]byte(`{"output":"This is a test from falcosidekick","source":"debug","priority":"Debug","hostname":"falcosidekick", "rule":"Test rule","time":"` + time.Now().UTC().Format(time.RFC3339) + `","output_fields":{"proc.name":"falcosidekick","user.name":"falcosidekick"},"tags":["test","example"]}`)))
mainHandler(w, r)
}

Expand Down Expand Up @@ -148,12 +149,12 @@ func newFalcoPayload(payload io.Reader) (types.FalcoPayload, error) {
for key, value := range config.Templatedfields {
tmpl, err := template.New("").Parse(value)
if err != nil {
log.Printf("[ERROR] : Parsing error for templated field '%v': %v\n", key, err)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("Parsing error for templated field '%v': %v", key, err))
continue
}
v := new(bytes.Buffer)
if err := tmpl.Execute(v, falcopayload.OutputFields); err != nil {
log.Printf("[ERROR] : Parsing error for templated field '%v': %v\n", key, err)
utils.Log(utils.ErrorLvl, "", fmt.Sprintf("Parsing error for templated field '%v': %v", key, err))
}
templatedFields += key + "=" + v.String() + " "
falcopayload.OutputFields[key] = v.String()
Expand Down Expand Up @@ -281,7 +282,7 @@ func newFalcoPayload(payload io.Reader) (types.FalcoPayload, error) {
}

if config.Debug {
log.Printf("[DEBUG] : Falco's payload : %v\n", falcopayload.String())
utils.Log(utils.DebugLvl, "", fmt.Sprintf("Falco's payload : %v", falcopayload.String()))
}

return falcopayload, nil
Expand Down
4 changes: 2 additions & 2 deletions internal/pkg/batcher/batcher_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"testing"
"time"

"github.com/falcosecurity/falcosidekick/types"

"github.com/google/go-cmp/cmp"
"github.com/google/uuid"

"github.com/falcosecurity/falcosidekick/types"
)

func TestElasticsearchBatcher(t *testing.T) {
Expand Down
37 changes: 37 additions & 0 deletions internal/pkg/utils/utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
// SPDX-License-Identifier: MIT OR Apache-2.0

package utils

import "fmt"

const (
InfoLvl string = "info"
InfoPrefix string = "[INFO] "
ErrorLvl string = "error"
ErrorPrefix string = "[ERROR]"
DebugLvl string = "debug"
DebugPrefix string = "[DEBUG]"
WarningLvl string = "warning"
WarningPrefix string = "[WARN] "
FatalLvl string = "fatal"
FatalPrefix string = "[FATAL]"
)

func Log(level, output, msg string) {
var prefix string
switch level {
case InfoLvl:
prefix = InfoPrefix
case ErrorLvl:
prefix = ErrorPrefix
case DebugLvl:
prefix = DebugPrefix
case WarningLvl:
prefix = WarningPrefix
}
if output != "" {
fmt.Printf("%v : %v - %v", prefix, output, msg)
} else {
fmt.Printf("%v : %v", prefix, msg)
}
}
Loading

0 comments on commit c8c54ca

Please sign in to comment.