Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Gitlab Target Reconciliation #44

Merged
merged 32 commits into from
Dec 18, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
533e81e
docs: fixed docstring
puffitos Dec 12, 2023
da1a983
feat: added TargetManager to handle global targets
puffitos Dec 12, 2023
d2899c1
refactor: added gitlab interface to handle interaction with the API
puffitos Dec 12, 2023
8327b34
chore: feat all gitlab functions
puffitos Dec 13, 2023
e19ccd4
tests: test post & put methods
puffitos Dec 13, 2023
97a48e2
test: added more tests and implemented mocks
puffitos Dec 14, 2023
7a29916
feat: added shutdown for the target manager
puffitos Dec 14, 2023
fa12911
chore: globaltarget docs
puffitos Dec 14, 2023
37de074
Merge remote-tracking branch 'origin/main' into feat/registration-config
puffitos Dec 14, 2023
f0b6b31
fix: fixed block on shutdown && removed With() logs
puffitos Dec 14, 2023
6a1d041
debug: added variables to make the sparrow testable after building
puffitos Dec 14, 2023
6fcea50
chore: remove generate of moq files for tests
puffitos Dec 15, 2023
037b30c
Merge branch 'main' into feat/registration-config
puffitos Dec 15, 2023
89f799f
System testing changes implemented:
puffitos Dec 15, 2023
72d4775
chore: info -> debug
puffitos Dec 15, 2023
bb80bea
chore: merge conflicts solved
puffitos Dec 15, 2023
a71ae1b
chore: licencing
puffitos Dec 15, 2023
7b29f0e
docs: added target manager configuration
puffitos Dec 15, 2023
2a7fb02
feat: read target manager cfg from file
puffitos Dec 15, 2023
c9ca548
chore: added vs code testing opts
puffitos Dec 15, 2023
2d6366d
docs: typo fixed
puffitos Dec 15, 2023
7594c82
chore: removed fullstop from logs
puffitos Dec 18, 2023
495150d
chore: moved defer close before error return
puffitos Dec 18, 2023
395c980
chore: logger with file name
puffitos Dec 18, 2023
6e36545
chore: merged from main
puffitos Dec 18, 2023
f8cdaa6
chore: ignore test_sast config
puffitos Dec 18, 2023
efce1a0
chore: added gosec on each push
puffitos Dec 18, 2023
c556271
chore: gosec conf
puffitos Dec 18, 2023
69f3974
debug: possibly fixed config path
puffitos Dec 18, 2023
0987302
fix: folder renamed to .github
puffitos Dec 18, 2023
c3f252b
chore: ignore nosec for the target manager loading
puffitos Dec 18, 2023
fa30913
fix: removed gosec config
puffitos Dec 18, 2023
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .github/workflows/test_sast.yml
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
name: Test - SAST

on:
push:
pull_request:

permissions:
Expand Down
2 changes: 1 addition & 1 deletion .github/workflows/test_unit.yml
Original file line number Diff line number Diff line change
Expand Up @@ -23,4 +23,4 @@ jobs:
- name: Test
run: |
go mod download
go test --race --coverprofile cover.out -v ./...
go test --race --count=1 --coverprofile cover.out -v ./...
2 changes: 1 addition & 1 deletion .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ repos:
hooks:
- id: go-mod-tidy-repo
- id: go-test-repo-mod
args: [ -race ]
args: [ -race, -count=1 ]
puffitos marked this conversation as resolved.
Show resolved Hide resolved
- id: go-vet-repo-mod
- id: go-fumpt-repo
args: [ -l, -w ]
Expand Down
3 changes: 2 additions & 1 deletion .vscode/settings.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
{
"go.testFlags": [
"-race",
"-cover"
"-cover",
"-count=1"
]
}
49 changes: 40 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,16 +8,17 @@

- [About this component](#about-this-component)
- [Installation](#installation)
- [Binary](#binary)
- [Container Image](#container-image)
- [Helm](#helm)
- [Binary](#binary)
- [Container Image](#container-image)
- [Helm](#helm)
- [Usage](#usage)
- [Container Image](#container-image-1)
- [Container Image](#container-image-1)
- [Configuration](#configuration)
- [Startup](#startup)
- [Loader](#loader)
- [Runtime](#runtime)
- [Check: Health](#check-health)
- [Startup](#startup)
- [Loader](#loader)
- [Runtime](#runtime)
- [TargetManager](#targetmanager)
- [Check: Health](#check-health)
- [Health Metrics](#health-metrics)
- [Check: Latency](#check-latency)
- [Latency Metrics](#latency-metrics)
Expand All @@ -38,7 +39,8 @@ The `sparrow` performs several checks to monitor the health of the infrastructur
The following checks are available:

1. Health check - `health`: The `sparrow` is able to perform an HTTP-based (HTTP/1.1) health check to the provided
endpoints. The `sparrow` will expose its own health check endpoint as well.
endpoints.
The `sparrow` will expose its own health check endpoint as well.

2. Latency check - `latency`: The `sparrow` is able to communicate with other `sparrow` instances to calculate the time
a request takes to the target and back. The check is http (HTTP/1.1) based as well.
Expand Down Expand Up @@ -168,6 +170,35 @@ checks:
enabled: true
```

### Target Manager

The `sparrow` is able to manage the targets for the checks and register the `sparrow` as target on a (remote) backend.
This is done via a `TargetManager` interface, which can be configured on startup. The available configuration options
are listed below and can be set in a startup YAML configuration file (per default `tmconfig.yaml` in the current
directory).

| Type | Description | Default |
|--------------------------------------|--------------------------------------------------------------------------------------|----------------------|
| `targetManager.checkInterval` | The interval in seconds to check for new targets. | `300` |
| `targetManager.unhealthyThreshold` | The threshold in seconds to mark a target as unhealthy and remove it from the state. | `600` |
| `targetManager.registrationInterval` | The interval in seconds to register the current sparrow at the targets backend. | `300` |
| `targetManager.gitlab.token` | The token to authenticate against the gitlab instance. | `""` |
| `targetManager.gitlab.baseUrl` | The base URL of the gitlab instance. | `https://gitlab.com` |
| `targetManager.gitlab.projectId` | The project ID of the gitlab project to use as a remote state backend. | `""` |

Currently, only one target manager exists: the Gitlab target manager. It uses a gitlab project as the remote state
backend. The various `sparrow` instances will
register themselves as targets in the project. The `sparrow` instances will also check the project for new targets and
add them to the local state. The registration is done by committing a "state" file in the main branch of the repository,
which is named after the DNS name of the `sparrow`. The state file contains the following information:

```json
{
"url": "https://<SPARROW_DNS_NAME>",
"lastSeen": "2021-09-30T12:00:00Z"
}
```

### Check: Health

Available configuration options:
Expand Down
2 changes: 1 addition & 1 deletion cmd/gen-docs.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ import (
"github.com/spf13/cobra/doc"
)

// NewCmdRun creates a new gen-docs command
// NewCmdGenDocs creates a new gen-docs command
func NewCmdGenDocs(rootCmd *cobra.Command) *cobra.Command {
var docPath string

Expand Down
4 changes: 4 additions & 0 deletions cmd/run.go
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,7 @@ func NewCmdRun() *cobra.Command {
LoaderHttpRetryCount: "loaderHttpRetryCount",
LoaderHttpRetryDelay: "loaderHttpRetryDelay",
LoaderFilePath: "loaderFilePath",
TargetManagerConfig: "tmconfig",
}

cmd := &cobra.Command{
Expand All @@ -67,6 +68,7 @@ func NewCmdRun() *cobra.Command {
cmd.PersistentFlags().Int(flagMapping.LoaderHttpRetryCount, defaultHttpRetryCount, "http loader: Amount of retries trying to load the configuration")
cmd.PersistentFlags().Int(flagMapping.LoaderHttpRetryDelay, defaultHttpRetryDelay, "http loader: The initial delay between retries in seconds")
cmd.PersistentFlags().String(flagMapping.LoaderFilePath, "config.yaml", "file loader: The path to the file to read the runtime config from")
cmd.PersistentFlags().String(flagMapping.TargetManagerConfig, "tmconfig.yaml", "target manager: The path to the file to read the target manager config from")

_ = viper.BindPFlag(flagMapping.ApiAddress, cmd.PersistentFlags().Lookup(flagMapping.ApiAddress))
_ = viper.BindPFlag(flagMapping.LoaderType, cmd.PersistentFlags().Lookup(flagMapping.LoaderType))
Expand All @@ -77,6 +79,7 @@ func NewCmdRun() *cobra.Command {
_ = viper.BindPFlag(flagMapping.LoaderHttpRetryCount, cmd.PersistentFlags().Lookup(flagMapping.LoaderHttpRetryCount))
_ = viper.BindPFlag(flagMapping.LoaderHttpRetryDelay, cmd.PersistentFlags().Lookup(flagMapping.LoaderHttpRetryDelay))
_ = viper.BindPFlag(flagMapping.LoaderFilePath, cmd.PersistentFlags().Lookup(flagMapping.LoaderFilePath))
_ = viper.BindPFlag(flagMapping.TargetManagerConfig, cmd.PersistentFlags().Lookup(flagMapping.TargetManagerConfig))

return cmd
}
Expand All @@ -88,6 +91,7 @@ func run(fm *config.RunFlagsNameMapping) func(cmd *cobra.Command, args []string)
ctx := logger.IntoContext(context.Background(), log)

cfg := config.NewConfig()
cfg.SetTargetManagerConfig(config.NewTargetManagerConfig(viper.GetString(fm.TargetManagerConfig)))

cfg.SetApiAddress(viper.GetString(fm.ApiAddress))

Expand Down
1 change: 1 addition & 0 deletions docs/sparrow_run.md
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@ sparrow run [flags]
--loaderHttpUrl string http loader: The url where to get the remote configuration
--loaderInterval int defines the interval the loader reloads the configuration in seconds (default 300)
-l, --loaderType string defines the loader type that will load the checks configuration during the runtime. The fallback is the fileLoader (default "http")
--tmconfig string target manager: The path to the file to read the target manager config from (default "tmconfig.yaml")
```

### Options inherited from parent commands
Expand Down
1 change: 1 addition & 0 deletions go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ go 1.21
require (
github.com/getkin/kin-openapi v0.120.0
github.com/go-chi/chi/v5 v5.0.10
github.com/go-test/deep v1.0.8
github.com/jarcoal/httpmock v1.3.1
github.com/mitchellh/mapstructure v1.5.0
github.com/spf13/cobra v1.8.0
Expand Down
7 changes: 7 additions & 0 deletions pkg/checks/checks.go
Original file line number Diff line number Diff line change
Expand Up @@ -77,6 +77,13 @@ type Result struct {
Err string `json:"error"`
}

// GlobalTarget includes the basic information regarding
// other Sparrow instances, which this Sparrow can communicate with.
type GlobalTarget struct {
Url string `json:"url"`
LastSeen time.Time `json:"lastSeen"`
}

type ResultDTO struct {
Name string
Result *Result
Expand Down
45 changes: 42 additions & 3 deletions pkg/config/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,15 +19,32 @@
package config

import (
"os"
"time"

"gopkg.in/yaml.v3"

"github.com/caas-team/sparrow/internal/helper"
)

type GitlabTargetManagerConfig struct {
BaseURL string `yaml:"baseUrl"`
Token string `yaml:"token"`
ProjectID int `yaml:"projectId"`
}

type TargetManagerConfig struct {
CheckInterval time.Duration `yaml:"checkInterval"`
RegistrationInterval time.Duration `yaml:"registrationInterval"`
UnhealthyThreshold time.Duration `yaml:"unhealthyThreshold"`
Gitlab GitlabTargetManagerConfig `yaml:"gitlab"`
}

type Config struct {
Checks map[string]any
Loader LoaderConfig
Api ApiConfig
Checks map[string]any
Loader LoaderConfig
Api ApiConfig
TargetManager TargetManagerConfig
}

// ApiConfig is the configuration for the data API
Expand Down Expand Up @@ -56,6 +73,23 @@ type FileLoaderConfig struct {
path string
}

// NewTargetManagerConfig creates a new TargetManagerConfig
// from the passed file
func NewTargetManagerConfig(path string) TargetManagerConfig {
var res TargetManagerConfig
f, err := os.ReadFile(path) //#nosec G304
if err != nil {
panic("failed to read config file " + err.Error())
}

err = yaml.Unmarshal(f, &res)
if err != nil {
panic("failed to parse config file: " + err.Error())
}

return res
}

// NewConfig creates a new Config
func NewConfig() *Config {
return &Config{
Expand Down Expand Up @@ -108,3 +142,8 @@ func (c *Config) SetLoaderHttpRetryCount(retryCount int) {
func (c *Config) SetLoaderHttpRetryDelay(retryDelay int) {
c.Loader.http.retryCfg.Delay = time.Duration(retryDelay) * time.Second
}

// SetTargetManagerConfig sets the target manager config
func (c *Config) SetTargetManagerConfig(config TargetManagerConfig) {
c.TargetManager = config
}
26 changes: 26 additions & 0 deletions pkg/config/config_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
package config

import (
"testing"
"time"

"github.com/go-test/deep"
)

func Test_NewTargetManagerConfig_Gitlab(t *testing.T) {
got := NewTargetManagerConfig("testdata/tmconfig.yaml")
want := TargetManagerConfig{
CheckInterval: 300 * time.Second,
RegistrationInterval: 600 * time.Second,
UnhealthyThreshold: 900 * time.Second,
Gitlab: GitlabTargetManagerConfig{
BaseURL: "https://gitlab.devops.telekom.de",
ProjectID: 666,
Token: "gitlab-token",
},
}

if diff := deep.Equal(got, want); diff != nil {
t.Error(diff)
}
}
2 changes: 2 additions & 0 deletions pkg/config/flags.go
Original file line number Diff line number Diff line change
Expand Up @@ -29,4 +29,6 @@ type RunFlagsNameMapping struct {
LoaderHttpRetryCount string
LoaderHttpRetryDelay string
LoaderFilePath string

TargetManagerConfig string
}
2 changes: 1 addition & 1 deletion pkg/config/http.go
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,7 @@ func NewHttpLoader(cfg *Config, cCfgChecks chan<- map[string]any) *HttpLoader {
}
}

// GetRuntimeConfig gets the runtime configuration
// Run gets the runtime configuration
// from the http remote endpoint.
// The config is will be loaded periodically defined by the
// loader interval configuration. A failed request will be retried defined
Expand Down
7 changes: 7 additions & 0 deletions pkg/config/testdata/tmconfig.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
checkInterval: 300s
registrationInterval: 600s
unhealthyThreshold: 900s
gitlab:
token: gitlab-token
baseUrl: https://gitlab.devops.telekom.de
projectId: 666
Loading