Compare commits

...

21 commits

Author SHA1 Message Date
Sebastien Blot
12ce5e3fc1
add more required fields in models 2024-04-23 13:22:54 +02:00
Sebastien Blot
e36d2cb6b8
up 2024-04-22 17:59:03 +02:00
blotus
3169343526
Merge branch 'master' into lapi-detailed-metrics 2024-04-22 17:54:23 +02:00
Sebastien Blot
538ab0bc62
up 2024-04-22 17:44:42 +02:00
Sebastien Blot
18b8ddb49a
add missing file 2024-04-22 17:02:07 +02:00
Sebastien Blot
7b093b925e
add lapi metrics in swagger and models 2024-04-22 16:08:26 +02:00
Sebastien Blot
f0853188ce
update swagger and models 2024-04-22 14:25:23 +02:00
Sebastien Blot
c6ebd7ae04
handle 422 error from CAPI 2024-04-22 11:40:13 +02:00
Sebastien Blot
2b940a45f8
up 2024-04-22 09:58:48 +02:00
Sebastien Blot
be64f619f2
set pushed_at after sending metrics 2024-04-19 18:33:46 +02:00
Sebastien Blot
0be7cc3cfc
store more payload 2024-04-19 18:02:19 +02:00
Sebastien Blot
33778ca87f
wip 2024-03-22 14:19:05 +01:00
Sebastien Blot
dbdf3ad1bb
wip 2024-03-21 10:27:52 +01:00
Sebastien Blot
11499c8d9e
display more LP information in cscli 2024-03-21 10:27:37 +01:00
marco
95f38d97d8 explicit message for 404 2024-03-19 15:33:55 +01:00
marco
b00e553ce9 interval messages 2024-03-19 15:33:55 +01:00
marco
876c33945d lint 2024-03-19 15:33:55 +01:00
marco
d9a3819ef5 ignore duplicate data points 2024-03-19 15:33:55 +01:00
marco
c325c2765d (wip) lp metrics 2024-03-19 15:33:55 +01:00
marco
76c04fdd82 regenerate pkg/models 2024-03-19 15:33:55 +01:00
Sebastien Blot
d1f62263ef add /usage-metrics endpoint definition 2024-03-19 15:33:55 +01:00
102 changed files with 6945 additions and 1098 deletions

View file

@ -1,6 +1,7 @@
package main
import (
"fmt"
"io"
"time"
@ -10,11 +11,20 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/emoji"
)
var tableHeaders = []string{"Name", "IP Address", "Last Update", "Status", "Version", "OS", "Auth Type", "Feature Flags", "Last Heartbeat"}
func getAgentsTable(out io.Writer, machines []*ent.Machine) {
t := newLightTable(out)
t.SetHeaders("Name", "IP Address", "Last Update", "Status", "Version", "Auth Type", "Last Heartbeat")
t.SetHeaderAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetAlignment(table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft, table.AlignLeft)
t.SetHeaders(tableHeaders...)
alignment := []table.Alignment{}
for i := 0; i < len(tableHeaders); i++ {
alignment = append(alignment, table.AlignLeft)
}
t.SetHeaderAlignment(alignment...)
t.SetAlignment(alignment...)
for _, m := range machines {
validated := emoji.Prohibited
@ -27,7 +37,7 @@ func getAgentsTable(out io.Writer, machines []*ent.Machine) {
hb = emoji.Warning + " " + hb
}
t.AddRow(m.MachineId, m.IpAddress, m.UpdatedAt.Format(time.RFC3339), validated, m.Version, m.AuthType, hb)
t.AddRow(m.MachineId, m.IpAddress, m.UpdatedAt.Format(time.RFC3339), validated, m.Version, fmt.Sprintf("%s/%s", m.Osname, m.Osversion), m.AuthType, m.Featureflags, hb)
}
t.Render()

View file

@ -9,6 +9,7 @@ import (
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
"gopkg.in/yaml.v2"
"github.com/crowdsecurity/go-cs-lib/trace"
@ -146,6 +147,22 @@ func runCrowdsec(cConfig *csconfig.Config, parsers *parser.Parsers, hub *cwhub.H
})
outputWg.Wait()
mp := NewMetricsProvider(
apiClient,
*cConfig.Crowdsec.MetricsInterval,
log.WithField("service", "lpmetrics"),
cConfig.API.Server.ConsoleConfig.EnabledOptions(),
datasources,
hub,
)
lpMetricsTomb := tomb.Tomb{}
lpMetricsTomb.Go(func() error {
// XXX: context?
return mp.Run(context.Background(), &lpMetricsTomb)
})
if cConfig.Prometheus != nil && cConfig.Prometheus.Enabled {
aggregated := false
if cConfig.Prometheus.Level == configuration.CFG_METRICS_AGGREGATE {

187
cmd/crowdsec/lpmetrics.go Normal file
View file

@ -0,0 +1,187 @@
package main
import (
"context"
"errors"
"net/http"
"time"
"github.com/blackfireio/osinfo"
"github.com/sirupsen/logrus"
"gopkg.in/tomb.v2"
"github.com/crowdsecurity/go-cs-lib/ptr"
"github.com/crowdsecurity/go-cs-lib/trace"
"github.com/crowdsecurity/crowdsec/pkg/acquisition"
"github.com/crowdsecurity/crowdsec/pkg/apiclient"
"github.com/crowdsecurity/crowdsec/pkg/cwhub"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/fflag"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// MetricsProvider collects metrics from the LP and sends them to the LAPI
type MetricsProvider struct {
apic *apiclient.ApiClient
interval time.Duration
static staticMetrics
logger *logrus.Entry
}
type staticMetrics struct {
osName string
osVersion string
startupTS int64
featureFlags []string
consoleOptions []string
datasourceMap map[string]int64
hubState models.HubItems
}
func getHubState(hub *cwhub.Hub) models.HubItems {
ret := models.HubItems{}
for _, itemType := range cwhub.ItemTypes {
items, _ := hub.GetInstalledItems(itemType)
for _, item := range items {
status := "official"
if item.State.IsLocal() {
status = "custom"
}
if item.State.Tainted {
status = "tainted"
}
ret[item.FQName()] = models.HubItem{
Version: item.Version,
Status: status,
}
}
}
return ret
}
// newStaticMetrics is called when the process starts, or reloads the configuration
func newStaticMetrics(consoleOptions []string, datasources []acquisition.DataSource, hub *cwhub.Hub) staticMetrics {
datasourceMap := map[string]int64{}
for _, ds := range datasources {
datasourceMap[ds.GetName()] += 1
}
osName, osVersion := detectOS()
return staticMetrics{
osName: osName,
osVersion: osVersion,
startupTS: time.Now().Unix(),
featureFlags: fflag.Crowdsec.GetEnabledFeatures(),
consoleOptions: consoleOptions,
datasourceMap: datasourceMap,
hubState: getHubState(hub),
}
}
func detectOS() (string, string) {
if cwversion.System == "docker" {
return "docker", ""
}
osInfo, err := osinfo.GetOSInfo()
if err != nil {
return cwversion.System, "???"
}
return osInfo.Name, osInfo.Version
}
func NewMetricsProvider(apic *apiclient.ApiClient, interval time.Duration, logger *logrus.Entry,
consoleOptions []string, datasources []acquisition.DataSource, hub *cwhub.Hub) *MetricsProvider {
return &MetricsProvider{
apic: apic,
interval: interval,
logger: logger,
static: newStaticMetrics(consoleOptions, datasources, hub),
}
}
func (m *MetricsProvider) metricsPayload() *models.AllMetrics {
meta := &models.MetricsMeta{
UtcStartupTimestamp: m.static.startupTS,
WindowSizeSeconds: int64(m.interval.Seconds()),
}
os := &models.OSversion{
Name: m.static.osName,
Version: m.static.osVersion,
}
base := models.BaseMetrics{
Meta: meta,
Os: os,
Version: ptr.Of(cwversion.VersionStr()),
FeatureFlags: m.static.featureFlags,
}
met := &models.LogProcessorsMetrics{
BaseMetrics: base,
ConsoleOptions: m.static.consoleOptions,
Datasources: m.static.datasourceMap,
HubItems: m.static.hubState,
}
// TODO: more metric details... ?
return &models.AllMetrics{
LogProcessors: []*models.LogProcessorsMetrics{met},
}
}
func (m *MetricsProvider) Run(ctx context.Context, myTomb *tomb.Tomb) error {
defer trace.CatchPanic("crowdsec/MetricsProvider.Run")
if m.interval == time.Duration(0) {
return nil
}
met := m.metricsPayload()
ticker := time.NewTicker(1) //Send on start
for {
select {
case <-ticker.C:
met.LogProcessors[0].Meta.UtcNowTimestamp = time.Now().Unix()
ctxTime, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
_, resp, err := m.apic.UsageMetrics.Add(ctxTime, met)
switch {
case errors.Is(err, context.DeadlineExceeded):
m.logger.Warnf("timeout sending lp metrics")
continue
case err != nil && resp != nil && resp.Response.StatusCode == http.StatusNotFound:
m.logger.Warnf("metrics endpoint not found, older LAPI?")
continue
case err != nil:
m.logger.Warnf("failed to send lp metrics: %s", err)
continue
}
if resp.Response.StatusCode != http.StatusCreated {
m.logger.Warnf("failed to send lp metrics: %s", resp.Response.Status)
continue
}
ticker.Reset(m.interval)
m.logger.Tracef("lp usage metrics sent")
case <-myTomb.Dying():
ticker.Stop()
return nil
}
}
}

View file

@ -39,6 +39,7 @@ type ApiClient struct {
Metrics *MetricsService
Signal *SignalService
HeartBeat *HeartBeatService
UsageMetrics *UsageMetricsService
}
func (a *ApiClient) GetClient() *http.Client {
@ -101,6 +102,7 @@ func NewClient(config *Config) (*ApiClient, error) {
c.Signal = (*SignalService)(&c.common)
c.DecisionDelete = (*DecisionDeleteService)(&c.common)
c.HeartBeat = (*HeartBeatService)(&c.common)
c.UsageMetrics = (*UsageMetricsService)(&c.common)
return c, nil
}
@ -137,6 +139,7 @@ func NewDefaultClient(URL *url.URL, prefix string, userAgent string, client *htt
c.Signal = (*SignalService)(&c.common)
c.DecisionDelete = (*DecisionDeleteService)(&c.common)
c.HeartBeat = (*HeartBeatService)(&c.common)
c.UsageMetrics = (*UsageMetricsService)(&c.common)
return c, nil
}

View file

@ -34,12 +34,18 @@ func CheckResponse(r *http.Response) error {
data, err := io.ReadAll(r.Body)
if err != nil || len(data) == 0 {
ret.Message = ptr.Of(fmt.Sprintf("http code %d, no error message", r.StatusCode))
ret.Message = ptr.Of(fmt.Sprintf("http code %d, no response body", r.StatusCode))
return ret
}
if err := json.Unmarshal(data, ret); err != nil {
return fmt.Errorf("http code %d, invalid body: %w", r.StatusCode, err)
switch r.StatusCode {
case 422:
ret.Message = ptr.Of(fmt.Sprintf("http code %d, invalid request: %s", r.StatusCode, string(data)))
default:
if err := json.Unmarshal(data, ret); err != nil {
ret.Message = ptr.Of(fmt.Sprintf("http code %d, invalid body: %s", r.StatusCode, string(data)))
return ret
}
}
return ret

View file

@ -0,0 +1,28 @@
package apiclient
import (
"context"
"fmt"
"net/http"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
type UsageMetricsService service
func (s *UsageMetricsService) Add(ctx context.Context, metrics *models.AllMetrics) (interface{}, *Response, error) {
u := fmt.Sprintf("%s/usage-metrics", s.client.URLPrefix)
req, err := s.client.NewRequest(http.MethodPost, u, &metrics)
if err != nil {
return nil, nil, err
}
var response interface{}
resp, err := s.client.Do(ctx, req, &response)
if err != nil {
return nil, resp, err
}
return &response, resp, nil
}

View file

@ -2,18 +2,170 @@ package apiserver
import (
"context"
"encoding/json"
"strings"
"time"
log "github.com/sirupsen/logrus"
"slices"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/go-cs-lib/ptr"
"github.com/crowdsecurity/go-cs-lib/trace"
"github.com/crowdsecurity/go-cs-lib/version"
"github.com/crowdsecurity/crowdsec/pkg/cwversion"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/fflag"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
func (a *apic) GetUsageMetrics() (*models.AllMetrics, []int, error) {
lpsMetrics, err := a.dbClient.GetLPsUsageMetrics()
metricsIds := make([]int, 0)
if err != nil {
return nil, nil, err
}
//spew.Dump(lpsMetrics)
bouncersMetrics, err := a.dbClient.GetBouncersUsageMetrics()
if err != nil {
return nil, nil, err
}
//spew.Dump(bouncersMetrics)
allMetrics := &models.AllMetrics{}
lpsCache := make(map[string]*ent.Machine)
bouncersCache := make(map[string]*ent.Bouncer)
for _, lpsMetric := range lpsMetrics {
lpName := lpsMetric.GeneratedBy
metrics := models.LogProcessorsMetrics{}
err := json.Unmarshal([]byte(lpsMetric.Payload), &metrics)
if err != nil {
log.Errorf("unable to unmarshal LPs metrics (%s)", err)
continue
}
var lp *ent.Machine
if _, ok := lpsCache[lpName]; !ok {
lp, err = a.dbClient.QueryMachineByID(lpName)
if err != nil {
log.Errorf("unable to get LP information for %s: %s", lpName, err)
continue
}
} else {
lp = lpsCache[lpName]
}
if lp.Hubstate != nil {
metrics.HubItems = *lp.Hubstate
}
metrics.Os = &models.OSversion{
Name: lp.Osname,
Version: lp.Osversion,
}
metrics.FeatureFlags = strings.Split(lp.Featureflags, ",")
metrics.Version = &lp.Version
metrics.Name = lpName
metrics.LastPush = lp.LastPush.UTC().Unix()
metrics.LastUpdate = lp.UpdatedAt.UTC().Unix()
//To prevent marshalling a nil slice to null, which gets rejected by the API
if metrics.Metrics == nil {
metrics.Metrics = make([]*models.MetricsDetailItem, 0)
}
allMetrics.LogProcessors = append(allMetrics.LogProcessors, &metrics)
metricsIds = append(metricsIds, lpsMetric.ID)
}
for _, bouncersMetric := range bouncersMetrics {
bouncerName := bouncersMetric.GeneratedBy
metrics := models.RemediationComponentsMetrics{}
err := json.Unmarshal([]byte(bouncersMetric.Payload), &metrics)
if err != nil {
log.Errorf("unable to unmarshal bouncers metrics (%s)", err)
continue
}
var bouncer *ent.Bouncer
if _, ok := bouncersCache[bouncerName]; !ok {
bouncer, err = a.dbClient.SelectBouncerByName(bouncerName)
if err != nil {
log.Errorf("unable to get bouncer information for %s: %s", bouncerName, err)
continue
}
} else {
bouncer = bouncersCache[bouncerName]
}
metrics.Os = &models.OSversion{
Name: bouncer.Osname,
Version: bouncer.Osversion,
}
metrics.Type = bouncer.Type
metrics.FeatureFlags = strings.Split(bouncer.Featureflags, ",")
metrics.Version = &bouncer.Version
metrics.Name = bouncerName
metrics.LastPull = bouncer.LastPull.UTC().Unix()
//To prevent marshalling a nil slice to null, which gets rejected by the API
if metrics.Metrics == nil {
metrics.Metrics = make([]*models.MetricsDetailItem, 0)
}
allMetrics.RemediationComponents = append(allMetrics.RemediationComponents, &metrics)
metricsIds = append(metricsIds, bouncersMetric.ID)
}
//FIXME: all of this should only be done once on startup/reload
allMetrics.Lapi = &models.LapiMetrics{
ConsoleOptions: models.ConsoleOptions{
"FIXME",
},
}
allMetrics.Lapi.Os = &models.OSversion{
Name: "FIXME",
Version: "FIXME",
}
allMetrics.Lapi.Version = ptr.Of(cwversion.VersionStr())
allMetrics.Lapi.FeatureFlags = fflag.Crowdsec.GetEnabledFeatures()
allMetrics.Lapi.Meta = &models.MetricsMeta{
UtcStartupTimestamp: time.Now().UTC().Unix(),
UtcNowTimestamp: time.Now().UTC().Unix(),
WindowSizeSeconds: int64(a.metricsInterval.Seconds()),
}
allMetrics.Lapi.Metrics = make([]*models.MetricsDetailItem, 0)
if allMetrics.RemediationComponents == nil {
allMetrics.RemediationComponents = make([]*models.RemediationComponentsMetrics, 0)
}
if allMetrics.LogProcessors == nil {
allMetrics.LogProcessors = make([]*models.LogProcessorsMetrics, 0)
}
return allMetrics, metricsIds, nil
}
func (a *apic) MarkUsageMetricsAsSent(ids []int) error {
return a.dbClient.MarkUsageMetricsAsSent(ids)
}
func (a *apic) GetMetrics() (*models.Metrics, error) {
machines, err := a.dbClient.ListMachines()
if err != nil {
@ -160,3 +312,37 @@ func (a *apic) SendMetrics(stop chan (bool)) {
}
}
}
func (a *apic) SendUsageMetrics() {
defer trace.CatchPanic("lapi/usageMetricsToAPIC")
ticker := time.NewTicker(5 * time.Second)
for {
select {
case <-a.metricsTomb.Dying():
//The normal metrics routine also kills push/pull tombs, does that make sense ?
ticker.Stop()
return
case <-ticker.C:
metrics, metricsId, err := a.GetUsageMetrics()
if err != nil {
log.Errorf("unable to get usage metrics: %s", err)
continue
}
_, _, err = a.apiClient.UsageMetrics.Add(context.Background(), metrics)
if err != nil {
log.Errorf("unable to send usage metrics: %s", err)
continue
}
err = a.MarkUsageMetricsAsSent(metricsId)
if err != nil {
log.Errorf("unable to mark usage metrics as sent: %s", err)
continue
}
log.Infof("Usage metrics sent")
}
}
}

View file

@ -25,6 +25,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/csplugin"
"github.com/crowdsecurity/crowdsec/pkg/database"
"github.com/crowdsecurity/crowdsec/pkg/fflag"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
@ -360,6 +361,15 @@ func (s *APIServer) Run(apiReady chan bool) error {
s.apic.SendMetrics(make(chan bool))
return nil
})
if fflag.CAPIUsageMetrics.IsEnabled() {
log.Infof("CAPI_USAGE_METRICS flag is enabled, starting usage metrics routine")
s.apic.metricsTomb.Go(func() error {
s.apic.SendUsageMetrics()
return nil
})
}
}
s.httpServerTomb.Go(func() error {
@ -368,7 +378,7 @@ func (s *APIServer) Run(apiReady chan bool) error {
if err := s.httpServerTomb.Wait(); err != nil {
return fmt.Errorf("local API server stopped with error: %w", err)
}
}
return nil
}

View file

@ -59,6 +59,17 @@ func serveHealth() http.HandlerFunc {
return health.NewHandler(checker)
}
func eitherAuthMiddleware(jwtMiddleware gin.HandlerFunc, apiKeyMiddleware gin.HandlerFunc) gin.HandlerFunc {
return func(c *gin.Context) {
// XXX: what when there's no api key for a RC?
if c.GetHeader("X-Api-Key") != "" {
apiKeyMiddleware(c)
} else {
jwtMiddleware(c)
}
}
}
func (c *Controller) NewV1() error {
var err error
@ -117,6 +128,12 @@ func (c *Controller) NewV1() error {
apiKeyAuth.HEAD("/decisions/stream", c.HandlerV1.StreamDecision)
}
eitherAuth := groupV1.Group("")
eitherAuth.Use(eitherAuthMiddleware(c.HandlerV1.Middlewares.JWT.Middleware.MiddlewareFunc(), c.HandlerV1.Middlewares.APIKey.MiddlewareFunc()))
{
eitherAuth.POST("/usage-metrics", c.HandlerV1.UsageMetrics)
}
return nil
}

View file

@ -0,0 +1,144 @@
package v1
import (
"encoding/json"
"fmt"
"net/http"
"time"
"github.com/gin-gonic/gin"
"github.com/go-openapi/strfmt"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// updateBaseMetrics updates the base metrics for a machine or bouncer
func (c *Controller) updateBaseMetrics(machineID string, bouncer *ent.Bouncer, baseMetrics *models.BaseMetrics, hubItems *models.HubItems) error {
switch {
case machineID != "":
c.DBClient.MachineUpdateBaseMetrics(machineID, baseMetrics, hubItems)
case bouncer != nil:
c.DBClient.BouncerUpdateBaseMetrics(bouncer.Name, bouncer.Type, baseMetrics)
default:
return fmt.Errorf("no machineID or bouncerName set")
}
return nil
}
// UsageMetrics receives metrics from log processors and remediation components
func (c *Controller) UsageMetrics(gctx *gin.Context) {
var input models.AllMetrics
// parse the payload
if err := gctx.ShouldBindJSON(&input); err != nil {
log.Errorf("Failed to bind json: %s", err)
gctx.JSON(http.StatusBadRequest, gin.H{"message": err.Error()})
return
}
if err := input.Validate(strfmt.Default); err != nil {
log.Errorf("Failed to validate usage metrics: %s", err)
c.HandleDBErrors(gctx, err)
return
}
// TODO: validate payload with the right type, depending on auth context
var (
generatedType metric.GeneratedType
generatedBy string
collectedAt time.Time
)
bouncer, _ := getBouncerFromContext(gctx)
if bouncer != nil {
log.Tracef("Received usage metris for bouncer: %s", bouncer.Name)
generatedType = metric.GeneratedTypeRC
generatedBy = bouncer.Name
}
machineID, _ := getMachineIDFromContext(gctx)
if machineID != "" {
log.Tracef("Received usage metrics for log processor: %s", machineID)
generatedType = metric.GeneratedTypeLP
generatedBy = machineID
}
// TODO: if both or none are set, which error should we return?
var (
payload map[string]any
baseMetrics models.BaseMetrics
hubItems models.HubItems
)
switch len(input.LogProcessors) {
case 0:
break
case 1:
// the final slice can't have more than one item,
// guaranteed by the swagger schema
item0 := input.LogProcessors[0]
payload = map[string]any{
"console_options": item0.ConsoleOptions,
"datasources": item0.Datasources,
"metrics": item0.Metrics,
"meta": item0.Meta,
}
baseMetrics = item0.BaseMetrics
hubItems = item0.HubItems
default:
log.Errorf("Payload has more than one log processor")
// this is not checked in the swagger schema
gctx.JSON(http.StatusBadRequest, gin.H{"message": "Payload has more than one log processor"})
return
}
switch len(input.RemediationComponents) {
case 0:
break
case 1:
item0 := input.RemediationComponents[0]
payload = map[string]any{
"type": item0.Type,
"metrics": item0.Metrics,
"meta": item0.Meta,
}
baseMetrics = item0.BaseMetrics
default:
gctx.JSON(http.StatusBadRequest, gin.H{"message": "Payload has more than one remediation component"})
return
}
err := c.updateBaseMetrics(machineID, bouncer, &baseMetrics, &hubItems)
if err != nil {
log.Errorf("Failed to update base metrics: %s", err)
c.HandleDBErrors(gctx, err)
return
}
collectedAt = time.Unix(baseMetrics.Meta.UtcNowTimestamp, 0).UTC()
jsonPayload, err := json.Marshal(payload)
if err != nil {
log.Errorf("Failed to marshal usage metrics: %s", err)
c.HandleDBErrors(gctx, err)
return
}
if _, err := c.DBClient.CreateMetric(generatedType, generatedBy, collectedAt, string(jsonPayload)); err != nil {
log.Error(err)
c.HandleDBErrors(gctx, err)
return
}
// if CreateMetrics() returned nil, the metric was already there, we're good
// and don't split hair about 201 vs 200/204
gctx.Status(http.StatusCreated)
}

View file

@ -4,6 +4,7 @@ import (
"fmt"
"os"
"path/filepath"
"time"
log "github.com/sirupsen/logrus"
"gopkg.in/yaml.v3"
@ -11,6 +12,11 @@ import (
"github.com/crowdsecurity/go-cs-lib/ptr"
)
const (
defaultMetricsInterval = 30 * time.Minute
minimumMetricsInterval = 15 * time.Minute
)
// CrowdsecServiceCfg contains the location of parsers/scenarios/... and acquisition files
type CrowdsecServiceCfg struct {
Enable *bool `yaml:"enable"`
@ -26,6 +32,7 @@ type CrowdsecServiceCfg struct {
BucketStateFile string `yaml:"state_input_file,omitempty"` // if we need to unserialize buckets at start
BucketStateDumpDir string `yaml:"state_output_dir,omitempty"` // if we need to unserialize buckets on shutdown
BucketsGCEnabled bool `yaml:"-"` // we need to garbage collect buckets when in forensic mode
MetricsInterval *time.Duration `yaml:"metrics_interval,omitempty"`
SimulationFilePath string `yaml:"-"`
ContextToSend map[string][]string `yaml:"-"`
@ -132,6 +139,8 @@ func (c *Config) LoadCrowdsec() error {
c.Crowdsec.AcquisitionFiles[i] = f
}
c.Crowdsec.setMetricsInterval()
if err = c.LoadAPIClient(); err != nil {
return fmt.Errorf("loading api client: %w", err)
}
@ -139,6 +148,21 @@ func (c *Config) LoadCrowdsec() error {
return nil
}
func (c *CrowdsecServiceCfg) setMetricsInterval() {
switch {
case c.MetricsInterval == nil:
log.Tracef("metrics_interval is not set, default to %s", defaultMetricsInterval)
c.MetricsInterval = ptr.Of(defaultMetricsInterval)
case *c.MetricsInterval == time.Duration(0):
log.Info("metrics_interval is set to 0, disabling metrics")
case *c.MetricsInterval < minimumMetricsInterval:
log.Warnf("metrics_interval is too low (%s), setting it to %s", *c.MetricsInterval, minimumMetricsInterval)
c.MetricsInterval = ptr.Of(minimumMetricsInterval)
default:
log.Tracef("metrics_interval set to %s", c.MetricsInterval)
}
}
func (c *CrowdsecServiceCfg) DumpContextConfigFile() error {
// XXX: MakeDirs
out, err := yaml.Marshal(c.ContextToSend)

View file

@ -58,6 +58,7 @@ func TestLoadCrowdsec(t *testing.T) {
ParserRoutinesCount: 1,
OutputRoutinesCount: 1,
ConsoleContextValueLength: 2500,
MetricsInterval: ptr.Of(defaultMetricsInterval),
AcquisitionFiles: []string{acquisFullPath},
SimulationFilePath: "./testdata/simulation.yaml",
// context is loaded in pkg/alertcontext
@ -98,6 +99,7 @@ func TestLoadCrowdsec(t *testing.T) {
ParserRoutinesCount: 1,
OutputRoutinesCount: 1,
ConsoleContextValueLength: 0,
MetricsInterval: ptr.Of(defaultMetricsInterval),
AcquisitionFiles: []string{acquisFullPath, acquisInDirFullPath},
// context is loaded in pkg/alertcontext
// ContextToSend: map[string][]string{
@ -136,6 +138,7 @@ func TestLoadCrowdsec(t *testing.T) {
ParserRoutinesCount: 1,
OutputRoutinesCount: 1,
ConsoleContextValueLength: 10,
MetricsInterval: ptr.Of(defaultMetricsInterval),
AcquisitionFiles: []string{},
SimulationFilePath: "",
// context is loaded in pkg/alertcontext

View file

@ -39,6 +39,7 @@ type DatabaseCfg struct {
}
type AuthGCCfg struct {
// XXX: define these as custom type (with days etc.) ?
Cert *string `yaml:"cert,omitempty"`
CertDuration *time.Duration
Api *string `yaml:"api_key,omitempty"`
@ -48,11 +49,12 @@ type AuthGCCfg struct {
}
type FlushDBCfg struct {
MaxItems *int `yaml:"max_items,omitempty"`
MaxItems *int `yaml:"max_items,omitempty"`
// We could unmarshal as time.Duration, but alert filters right now are a map of strings
MaxAge *string `yaml:"max_age,omitempty"`
BouncersGC *AuthGCCfg `yaml:"bouncers_autodelete,omitempty"`
AgentsGC *AuthGCCfg `yaml:"agents_autodelete,omitempty"`
MaxAge *string `yaml:"max_age,omitempty"`
BouncersGC *AuthGCCfg `yaml:"bouncers_autodelete,omitempty"`
AgentsGC *AuthGCCfg `yaml:"agents_autodelete,omitempty"`
MetricsMaxAge *time.Duration `yaml:"metrics_max_age,omitempty"`
}
func (c *Config) LoadDBConfig(inCli bool) error {

View file

@ -2,14 +2,37 @@ package database
import (
"fmt"
"strings"
"time"
"github.com/pkg/errors"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/bouncer"
)
func (c *Client) BouncerUpdateBaseMetrics(bouncerName string, bouncerType string, baseMetrics *models.BaseMetrics) error {
os := baseMetrics.Os
features := strings.Join(baseMetrics.FeatureFlags, ",")
// XXX: bouncers have no heartbeat, they have "last pull", are we updating it?
_, err := c.Ent.Bouncer.
Update().
Where(bouncer.NameEQ(bouncerName)).
SetNillableVersion(baseMetrics.Version).
SetOsname(os.Name).
SetOsversion(os.Version).
SetFeatureflags(features).
SetType(bouncerType).
Save(c.CTX)
if err != nil {
return fmt.Errorf("unable to update base bouncer metrics in database: %s", err)
}
return nil
}
func (c *Client) SelectBouncer(apiKeyHash string) (*ent.Bouncer, error) {
result, err := c.Ent.Bouncer.Query().Where(bouncer.APIKeyEQ(apiKeyHash)).First(c.CTX)
if err != nil {

View file

@ -19,9 +19,9 @@ type Alert struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Scenario holds the value of the "scenario" field.
Scenario string `json:"scenario,omitempty"`
// BucketId holds the value of the "bucketId" field.
@ -168,15 +168,13 @@ func (a *Alert) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
a.CreatedAt = new(time.Time)
*a.CreatedAt = value.Time
a.CreatedAt = value.Time
}
case alert.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
a.UpdatedAt = new(time.Time)
*a.UpdatedAt = value.Time
a.UpdatedAt = value.Time
}
case alert.FieldScenario:
if value, ok := values[i].(*sql.NullString); !ok {
@ -367,15 +365,11 @@ func (a *Alert) String() string {
var builder strings.Builder
builder.WriteString("Alert(")
builder.WriteString(fmt.Sprintf("id=%v, ", a.ID))
if v := a.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(a.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := a.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(a.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("scenario=")
builder.WriteString(a.Scenario)

View file

@ -152,8 +152,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.

View file

@ -210,16 +210,6 @@ func CreatedAtLTE(v time.Time) predicate.Alert {
return predicate.Alert(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Alert {
return predicate.Alert(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Alert {
return predicate.Alert(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Alert {
return predicate.Alert(sql.FieldEQ(FieldUpdatedAt, v))
@ -260,16 +250,6 @@ func UpdatedAtLTE(v time.Time) predicate.Alert {
return predicate.Alert(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.Alert {
return predicate.Alert(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.Alert {
return predicate.Alert(sql.FieldNotNull(FieldUpdatedAt))
}
// ScenarioEQ applies the EQ predicate on the "scenario" field.
func ScenarioEQ(v string) predicate.Alert {
return predicate.Alert(sql.FieldEQ(FieldScenario, v))

View file

@ -473,6 +473,12 @@ func (ac *AlertCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (ac *AlertCreate) check() error {
if _, ok := ac.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Alert.created_at"`)}
}
if _, ok := ac.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Alert.updated_at"`)}
}
if _, ok := ac.mutation.Scenario(); !ok {
return &ValidationError{Name: "scenario", err: errors.New(`ent: missing required field "Alert.scenario"`)}
}
@ -507,11 +513,11 @@ func (ac *AlertCreate) createSpec() (*Alert, *sqlgraph.CreateSpec) {
)
if value, ok := ac.mutation.CreatedAt(); ok {
_spec.SetField(alert.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := ac.mutation.UpdatedAt(); ok {
_spec.SetField(alert.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := ac.mutation.Scenario(); ok {
_spec.SetField(alert.FieldScenario, field.TypeString, value)

View file

@ -32,30 +32,12 @@ func (au *AlertUpdate) Where(ps ...predicate.Alert) *AlertUpdate {
return au
}
// SetCreatedAt sets the "created_at" field.
func (au *AlertUpdate) SetCreatedAt(t time.Time) *AlertUpdate {
au.mutation.SetCreatedAt(t)
return au
}
// ClearCreatedAt clears the value of the "created_at" field.
func (au *AlertUpdate) ClearCreatedAt() *AlertUpdate {
au.mutation.ClearCreatedAt()
return au
}
// SetUpdatedAt sets the "updated_at" field.
func (au *AlertUpdate) SetUpdatedAt(t time.Time) *AlertUpdate {
au.mutation.SetUpdatedAt(t)
return au
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (au *AlertUpdate) ClearUpdatedAt() *AlertUpdate {
au.mutation.ClearUpdatedAt()
return au
}
// SetScenario sets the "scenario" field.
func (au *AlertUpdate) SetScenario(s string) *AlertUpdate {
au.mutation.SetScenario(s)
@ -660,11 +642,7 @@ func (au *AlertUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (au *AlertUpdate) defaults() {
if _, ok := au.mutation.CreatedAt(); !ok && !au.mutation.CreatedAtCleared() {
v := alert.UpdateDefaultCreatedAt()
au.mutation.SetCreatedAt(v)
}
if _, ok := au.mutation.UpdatedAt(); !ok && !au.mutation.UpdatedAtCleared() {
if _, ok := au.mutation.UpdatedAt(); !ok {
v := alert.UpdateDefaultUpdatedAt()
au.mutation.SetUpdatedAt(v)
}
@ -679,18 +657,9 @@ func (au *AlertUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := au.mutation.CreatedAt(); ok {
_spec.SetField(alert.FieldCreatedAt, field.TypeTime, value)
}
if au.mutation.CreatedAtCleared() {
_spec.ClearField(alert.FieldCreatedAt, field.TypeTime)
}
if value, ok := au.mutation.UpdatedAt(); ok {
_spec.SetField(alert.FieldUpdatedAt, field.TypeTime, value)
}
if au.mutation.UpdatedAtCleared() {
_spec.ClearField(alert.FieldUpdatedAt, field.TypeTime)
}
if value, ok := au.mutation.Scenario(); ok {
_spec.SetField(alert.FieldScenario, field.TypeString, value)
}
@ -1007,30 +976,12 @@ type AlertUpdateOne struct {
mutation *AlertMutation
}
// SetCreatedAt sets the "created_at" field.
func (auo *AlertUpdateOne) SetCreatedAt(t time.Time) *AlertUpdateOne {
auo.mutation.SetCreatedAt(t)
return auo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (auo *AlertUpdateOne) ClearCreatedAt() *AlertUpdateOne {
auo.mutation.ClearCreatedAt()
return auo
}
// SetUpdatedAt sets the "updated_at" field.
func (auo *AlertUpdateOne) SetUpdatedAt(t time.Time) *AlertUpdateOne {
auo.mutation.SetUpdatedAt(t)
return auo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (auo *AlertUpdateOne) ClearUpdatedAt() *AlertUpdateOne {
auo.mutation.ClearUpdatedAt()
return auo
}
// SetScenario sets the "scenario" field.
func (auo *AlertUpdateOne) SetScenario(s string) *AlertUpdateOne {
auo.mutation.SetScenario(s)
@ -1648,11 +1599,7 @@ func (auo *AlertUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (auo *AlertUpdateOne) defaults() {
if _, ok := auo.mutation.CreatedAt(); !ok && !auo.mutation.CreatedAtCleared() {
v := alert.UpdateDefaultCreatedAt()
auo.mutation.SetCreatedAt(v)
}
if _, ok := auo.mutation.UpdatedAt(); !ok && !auo.mutation.UpdatedAtCleared() {
if _, ok := auo.mutation.UpdatedAt(); !ok {
v := alert.UpdateDefaultUpdatedAt()
auo.mutation.SetUpdatedAt(v)
}
@ -1684,18 +1631,9 @@ func (auo *AlertUpdateOne) sqlSave(ctx context.Context) (_node *Alert, err error
}
}
}
if value, ok := auo.mutation.CreatedAt(); ok {
_spec.SetField(alert.FieldCreatedAt, field.TypeTime, value)
}
if auo.mutation.CreatedAtCleared() {
_spec.ClearField(alert.FieldCreatedAt, field.TypeTime)
}
if value, ok := auo.mutation.UpdatedAt(); ok {
_spec.SetField(alert.FieldUpdatedAt, field.TypeTime, value)
}
if auo.mutation.UpdatedAtCleared() {
_spec.ClearField(alert.FieldUpdatedAt, field.TypeTime)
}
if value, ok := auo.mutation.Scenario(); ok {
_spec.SetField(alert.FieldScenario, field.TypeString, value)
}

View file

@ -18,9 +18,9 @@ type Bouncer struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at"`
CreatedAt time.Time `json:"created_at"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at"`
UpdatedAt time.Time `json:"updated_at"`
// Name holds the value of the "name" field.
Name string `json:"name"`
// APIKey holds the value of the "api_key" field.
@ -38,7 +38,13 @@ type Bouncer struct {
// LastPull holds the value of the "last_pull" field.
LastPull time.Time `json:"last_pull"`
// AuthType holds the value of the "auth_type" field.
AuthType string `json:"auth_type"`
AuthType string `json:"auth_type"`
// Osname holds the value of the "osname" field.
Osname string `json:"osname,omitempty"`
// Osversion holds the value of the "osversion" field.
Osversion string `json:"osversion,omitempty"`
// Featureflags holds the value of the "featureflags" field.
Featureflags string `json:"featureflags,omitempty"`
selectValues sql.SelectValues
}
@ -51,7 +57,7 @@ func (*Bouncer) scanValues(columns []string) ([]any, error) {
values[i] = new(sql.NullBool)
case bouncer.FieldID:
values[i] = new(sql.NullInt64)
case bouncer.FieldName, bouncer.FieldAPIKey, bouncer.FieldIPAddress, bouncer.FieldType, bouncer.FieldVersion, bouncer.FieldAuthType:
case bouncer.FieldName, bouncer.FieldAPIKey, bouncer.FieldIPAddress, bouncer.FieldType, bouncer.FieldVersion, bouncer.FieldAuthType, bouncer.FieldOsname, bouncer.FieldOsversion, bouncer.FieldFeatureflags:
values[i] = new(sql.NullString)
case bouncer.FieldCreatedAt, bouncer.FieldUpdatedAt, bouncer.FieldUntil, bouncer.FieldLastPull:
values[i] = new(sql.NullTime)
@ -80,15 +86,13 @@ func (b *Bouncer) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
b.CreatedAt = new(time.Time)
*b.CreatedAt = value.Time
b.CreatedAt = value.Time
}
case bouncer.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
b.UpdatedAt = new(time.Time)
*b.UpdatedAt = value.Time
b.UpdatedAt = value.Time
}
case bouncer.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
@ -144,6 +148,24 @@ func (b *Bouncer) assignValues(columns []string, values []any) error {
} else if value.Valid {
b.AuthType = value.String
}
case bouncer.FieldOsname:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field osname", values[i])
} else if value.Valid {
b.Osname = value.String
}
case bouncer.FieldOsversion:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field osversion", values[i])
} else if value.Valid {
b.Osversion = value.String
}
case bouncer.FieldFeatureflags:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field featureflags", values[i])
} else if value.Valid {
b.Featureflags = value.String
}
default:
b.selectValues.Set(columns[i], values[i])
}
@ -180,15 +202,11 @@ func (b *Bouncer) String() string {
var builder strings.Builder
builder.WriteString("Bouncer(")
builder.WriteString(fmt.Sprintf("id=%v, ", b.ID))
if v := b.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(b.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := b.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(b.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(b.Name)
@ -215,6 +233,15 @@ func (b *Bouncer) String() string {
builder.WriteString(", ")
builder.WriteString("auth_type=")
builder.WriteString(b.AuthType)
builder.WriteString(", ")
builder.WriteString("osname=")
builder.WriteString(b.Osname)
builder.WriteString(", ")
builder.WriteString("osversion=")
builder.WriteString(b.Osversion)
builder.WriteString(", ")
builder.WriteString("featureflags=")
builder.WriteString(b.Featureflags)
builder.WriteByte(')')
return builder.String()
}

View file

@ -35,6 +35,12 @@ const (
FieldLastPull = "last_pull"
// FieldAuthType holds the string denoting the auth_type field in the database.
FieldAuthType = "auth_type"
// FieldOsname holds the string denoting the osname field in the database.
FieldOsname = "osname"
// FieldOsversion holds the string denoting the osversion field in the database.
FieldOsversion = "osversion"
// FieldFeatureflags holds the string denoting the featureflags field in the database.
FieldFeatureflags = "featureflags"
// Table holds the table name of the bouncer in the database.
Table = "bouncers"
)
@ -53,6 +59,9 @@ var Columns = []string{
FieldUntil,
FieldLastPull,
FieldAuthType,
FieldOsname,
FieldOsversion,
FieldFeatureflags,
}
// ValidColumn reports if the column name is valid (part of the table columns).
@ -68,8 +77,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
@ -146,3 +153,18 @@ func ByLastPull(opts ...sql.OrderTermOption) OrderOption {
func ByAuthType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAuthType, opts...).ToFunc()
}
// ByOsname orders the results by the osname field.
func ByOsname(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOsname, opts...).ToFunc()
}
// ByOsversion orders the results by the osversion field.
func ByOsversion(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOsversion, opts...).ToFunc()
}
// ByFeatureflags orders the results by the featureflags field.
func ByFeatureflags(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFeatureflags, opts...).ToFunc()
}

View file

@ -109,6 +109,21 @@ func AuthType(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldAuthType, v))
}
// Osname applies equality check predicate on the "osname" field. It's identical to OsnameEQ.
func Osname(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldOsname, v))
}
// Osversion applies equality check predicate on the "osversion" field. It's identical to OsversionEQ.
func Osversion(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldOsversion, v))
}
// Featureflags applies equality check predicate on the "featureflags" field. It's identical to FeatureflagsEQ.
func Featureflags(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldFeatureflags, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldCreatedAt, v))
@ -149,16 +164,6 @@ func CreatedAtLTE(v time.Time) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldUpdatedAt, v))
@ -199,16 +204,6 @@ func UpdatedAtLTE(v time.Time) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotNull(FieldUpdatedAt))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldName, v))
@ -729,6 +724,231 @@ func AuthTypeContainsFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContainsFold(FieldAuthType, v))
}
// OsnameEQ applies the EQ predicate on the "osname" field.
func OsnameEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldOsname, v))
}
// OsnameNEQ applies the NEQ predicate on the "osname" field.
func OsnameNEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldNEQ(FieldOsname, v))
}
// OsnameIn applies the In predicate on the "osname" field.
func OsnameIn(vs ...string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldIn(FieldOsname, vs...))
}
// OsnameNotIn applies the NotIn predicate on the "osname" field.
func OsnameNotIn(vs ...string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotIn(FieldOsname, vs...))
}
// OsnameGT applies the GT predicate on the "osname" field.
func OsnameGT(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldGT(FieldOsname, v))
}
// OsnameGTE applies the GTE predicate on the "osname" field.
func OsnameGTE(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldGTE(FieldOsname, v))
}
// OsnameLT applies the LT predicate on the "osname" field.
func OsnameLT(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLT(FieldOsname, v))
}
// OsnameLTE applies the LTE predicate on the "osname" field.
func OsnameLTE(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLTE(FieldOsname, v))
}
// OsnameContains applies the Contains predicate on the "osname" field.
func OsnameContains(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContains(FieldOsname, v))
}
// OsnameHasPrefix applies the HasPrefix predicate on the "osname" field.
func OsnameHasPrefix(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldHasPrefix(FieldOsname, v))
}
// OsnameHasSuffix applies the HasSuffix predicate on the "osname" field.
func OsnameHasSuffix(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldHasSuffix(FieldOsname, v))
}
// OsnameIsNil applies the IsNil predicate on the "osname" field.
func OsnameIsNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldIsNull(FieldOsname))
}
// OsnameNotNil applies the NotNil predicate on the "osname" field.
func OsnameNotNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotNull(FieldOsname))
}
// OsnameEqualFold applies the EqualFold predicate on the "osname" field.
func OsnameEqualFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEqualFold(FieldOsname, v))
}
// OsnameContainsFold applies the ContainsFold predicate on the "osname" field.
func OsnameContainsFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContainsFold(FieldOsname, v))
}
// OsversionEQ applies the EQ predicate on the "osversion" field.
func OsversionEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldOsversion, v))
}
// OsversionNEQ applies the NEQ predicate on the "osversion" field.
func OsversionNEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldNEQ(FieldOsversion, v))
}
// OsversionIn applies the In predicate on the "osversion" field.
func OsversionIn(vs ...string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldIn(FieldOsversion, vs...))
}
// OsversionNotIn applies the NotIn predicate on the "osversion" field.
func OsversionNotIn(vs ...string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotIn(FieldOsversion, vs...))
}
// OsversionGT applies the GT predicate on the "osversion" field.
func OsversionGT(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldGT(FieldOsversion, v))
}
// OsversionGTE applies the GTE predicate on the "osversion" field.
func OsversionGTE(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldGTE(FieldOsversion, v))
}
// OsversionLT applies the LT predicate on the "osversion" field.
func OsversionLT(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLT(FieldOsversion, v))
}
// OsversionLTE applies the LTE predicate on the "osversion" field.
func OsversionLTE(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLTE(FieldOsversion, v))
}
// OsversionContains applies the Contains predicate on the "osversion" field.
func OsversionContains(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContains(FieldOsversion, v))
}
// OsversionHasPrefix applies the HasPrefix predicate on the "osversion" field.
func OsversionHasPrefix(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldHasPrefix(FieldOsversion, v))
}
// OsversionHasSuffix applies the HasSuffix predicate on the "osversion" field.
func OsversionHasSuffix(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldHasSuffix(FieldOsversion, v))
}
// OsversionIsNil applies the IsNil predicate on the "osversion" field.
func OsversionIsNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldIsNull(FieldOsversion))
}
// OsversionNotNil applies the NotNil predicate on the "osversion" field.
func OsversionNotNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotNull(FieldOsversion))
}
// OsversionEqualFold applies the EqualFold predicate on the "osversion" field.
func OsversionEqualFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEqualFold(FieldOsversion, v))
}
// OsversionContainsFold applies the ContainsFold predicate on the "osversion" field.
func OsversionContainsFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContainsFold(FieldOsversion, v))
}
// FeatureflagsEQ applies the EQ predicate on the "featureflags" field.
func FeatureflagsEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEQ(FieldFeatureflags, v))
}
// FeatureflagsNEQ applies the NEQ predicate on the "featureflags" field.
func FeatureflagsNEQ(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldNEQ(FieldFeatureflags, v))
}
// FeatureflagsIn applies the In predicate on the "featureflags" field.
func FeatureflagsIn(vs ...string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldIn(FieldFeatureflags, vs...))
}
// FeatureflagsNotIn applies the NotIn predicate on the "featureflags" field.
func FeatureflagsNotIn(vs ...string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotIn(FieldFeatureflags, vs...))
}
// FeatureflagsGT applies the GT predicate on the "featureflags" field.
func FeatureflagsGT(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldGT(FieldFeatureflags, v))
}
// FeatureflagsGTE applies the GTE predicate on the "featureflags" field.
func FeatureflagsGTE(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldGTE(FieldFeatureflags, v))
}
// FeatureflagsLT applies the LT predicate on the "featureflags" field.
func FeatureflagsLT(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLT(FieldFeatureflags, v))
}
// FeatureflagsLTE applies the LTE predicate on the "featureflags" field.
func FeatureflagsLTE(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldLTE(FieldFeatureflags, v))
}
// FeatureflagsContains applies the Contains predicate on the "featureflags" field.
func FeatureflagsContains(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContains(FieldFeatureflags, v))
}
// FeatureflagsHasPrefix applies the HasPrefix predicate on the "featureflags" field.
func FeatureflagsHasPrefix(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldHasPrefix(FieldFeatureflags, v))
}
// FeatureflagsHasSuffix applies the HasSuffix predicate on the "featureflags" field.
func FeatureflagsHasSuffix(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldHasSuffix(FieldFeatureflags, v))
}
// FeatureflagsIsNil applies the IsNil predicate on the "featureflags" field.
func FeatureflagsIsNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldIsNull(FieldFeatureflags))
}
// FeatureflagsNotNil applies the NotNil predicate on the "featureflags" field.
func FeatureflagsNotNil() predicate.Bouncer {
return predicate.Bouncer(sql.FieldNotNull(FieldFeatureflags))
}
// FeatureflagsEqualFold applies the EqualFold predicate on the "featureflags" field.
func FeatureflagsEqualFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldEqualFold(FieldFeatureflags, v))
}
// FeatureflagsContainsFold applies the ContainsFold predicate on the "featureflags" field.
func FeatureflagsContainsFold(v string) predicate.Bouncer {
return predicate.Bouncer(sql.FieldContainsFold(FieldFeatureflags, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Bouncer) predicate.Bouncer {
return predicate.Bouncer(sql.AndPredicates(predicates...))

View file

@ -150,6 +150,48 @@ func (bc *BouncerCreate) SetNillableAuthType(s *string) *BouncerCreate {
return bc
}
// SetOsname sets the "osname" field.
func (bc *BouncerCreate) SetOsname(s string) *BouncerCreate {
bc.mutation.SetOsname(s)
return bc
}
// SetNillableOsname sets the "osname" field if the given value is not nil.
func (bc *BouncerCreate) SetNillableOsname(s *string) *BouncerCreate {
if s != nil {
bc.SetOsname(*s)
}
return bc
}
// SetOsversion sets the "osversion" field.
func (bc *BouncerCreate) SetOsversion(s string) *BouncerCreate {
bc.mutation.SetOsversion(s)
return bc
}
// SetNillableOsversion sets the "osversion" field if the given value is not nil.
func (bc *BouncerCreate) SetNillableOsversion(s *string) *BouncerCreate {
if s != nil {
bc.SetOsversion(*s)
}
return bc
}
// SetFeatureflags sets the "featureflags" field.
func (bc *BouncerCreate) SetFeatureflags(s string) *BouncerCreate {
bc.mutation.SetFeatureflags(s)
return bc
}
// SetNillableFeatureflags sets the "featureflags" field if the given value is not nil.
func (bc *BouncerCreate) SetNillableFeatureflags(s *string) *BouncerCreate {
if s != nil {
bc.SetFeatureflags(*s)
}
return bc
}
// Mutation returns the BouncerMutation object of the builder.
func (bc *BouncerCreate) Mutation() *BouncerMutation {
return bc.mutation
@ -213,6 +255,12 @@ func (bc *BouncerCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (bc *BouncerCreate) check() error {
if _, ok := bc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Bouncer.created_at"`)}
}
if _, ok := bc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Bouncer.updated_at"`)}
}
if _, ok := bc.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "Bouncer.name"`)}
}
@ -256,11 +304,11 @@ func (bc *BouncerCreate) createSpec() (*Bouncer, *sqlgraph.CreateSpec) {
)
if value, ok := bc.mutation.CreatedAt(); ok {
_spec.SetField(bouncer.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := bc.mutation.UpdatedAt(); ok {
_spec.SetField(bouncer.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := bc.mutation.Name(); ok {
_spec.SetField(bouncer.FieldName, field.TypeString, value)
@ -298,6 +346,18 @@ func (bc *BouncerCreate) createSpec() (*Bouncer, *sqlgraph.CreateSpec) {
_spec.SetField(bouncer.FieldAuthType, field.TypeString, value)
_node.AuthType = value
}
if value, ok := bc.mutation.Osname(); ok {
_spec.SetField(bouncer.FieldOsname, field.TypeString, value)
_node.Osname = value
}
if value, ok := bc.mutation.Osversion(); ok {
_spec.SetField(bouncer.FieldOsversion, field.TypeString, value)
_node.Osversion = value
}
if value, ok := bc.mutation.Featureflags(); ok {
_spec.SetField(bouncer.FieldFeatureflags, field.TypeString, value)
_node.Featureflags = value
}
return _node, _spec
}

View file

@ -34,9 +34,11 @@ func (bu *BouncerUpdate) SetCreatedAt(t time.Time) *BouncerUpdate {
return bu
}
// ClearCreatedAt clears the value of the "created_at" field.
func (bu *BouncerUpdate) ClearCreatedAt() *BouncerUpdate {
bu.mutation.ClearCreatedAt()
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (bu *BouncerUpdate) SetNillableCreatedAt(t *time.Time) *BouncerUpdate {
if t != nil {
bu.SetCreatedAt(*t)
}
return bu
}
@ -46,12 +48,6 @@ func (bu *BouncerUpdate) SetUpdatedAt(t time.Time) *BouncerUpdate {
return bu
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (bu *BouncerUpdate) ClearUpdatedAt() *BouncerUpdate {
bu.mutation.ClearUpdatedAt()
return bu
}
// SetName sets the "name" field.
func (bu *BouncerUpdate) SetName(s string) *BouncerUpdate {
bu.mutation.SetName(s)
@ -202,6 +198,66 @@ func (bu *BouncerUpdate) SetNillableAuthType(s *string) *BouncerUpdate {
return bu
}
// SetOsname sets the "osname" field.
func (bu *BouncerUpdate) SetOsname(s string) *BouncerUpdate {
bu.mutation.SetOsname(s)
return bu
}
// SetNillableOsname sets the "osname" field if the given value is not nil.
func (bu *BouncerUpdate) SetNillableOsname(s *string) *BouncerUpdate {
if s != nil {
bu.SetOsname(*s)
}
return bu
}
// ClearOsname clears the value of the "osname" field.
func (bu *BouncerUpdate) ClearOsname() *BouncerUpdate {
bu.mutation.ClearOsname()
return bu
}
// SetOsversion sets the "osversion" field.
func (bu *BouncerUpdate) SetOsversion(s string) *BouncerUpdate {
bu.mutation.SetOsversion(s)
return bu
}
// SetNillableOsversion sets the "osversion" field if the given value is not nil.
func (bu *BouncerUpdate) SetNillableOsversion(s *string) *BouncerUpdate {
if s != nil {
bu.SetOsversion(*s)
}
return bu
}
// ClearOsversion clears the value of the "osversion" field.
func (bu *BouncerUpdate) ClearOsversion() *BouncerUpdate {
bu.mutation.ClearOsversion()
return bu
}
// SetFeatureflags sets the "featureflags" field.
func (bu *BouncerUpdate) SetFeatureflags(s string) *BouncerUpdate {
bu.mutation.SetFeatureflags(s)
return bu
}
// SetNillableFeatureflags sets the "featureflags" field if the given value is not nil.
func (bu *BouncerUpdate) SetNillableFeatureflags(s *string) *BouncerUpdate {
if s != nil {
bu.SetFeatureflags(*s)
}
return bu
}
// ClearFeatureflags clears the value of the "featureflags" field.
func (bu *BouncerUpdate) ClearFeatureflags() *BouncerUpdate {
bu.mutation.ClearFeatureflags()
return bu
}
// Mutation returns the BouncerMutation object of the builder.
func (bu *BouncerUpdate) Mutation() *BouncerMutation {
return bu.mutation
@ -237,11 +293,7 @@ func (bu *BouncerUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (bu *BouncerUpdate) defaults() {
if _, ok := bu.mutation.CreatedAt(); !ok && !bu.mutation.CreatedAtCleared() {
v := bouncer.UpdateDefaultCreatedAt()
bu.mutation.SetCreatedAt(v)
}
if _, ok := bu.mutation.UpdatedAt(); !ok && !bu.mutation.UpdatedAtCleared() {
if _, ok := bu.mutation.UpdatedAt(); !ok {
v := bouncer.UpdateDefaultUpdatedAt()
bu.mutation.SetUpdatedAt(v)
}
@ -259,15 +311,9 @@ func (bu *BouncerUpdate) sqlSave(ctx context.Context) (n int, err error) {
if value, ok := bu.mutation.CreatedAt(); ok {
_spec.SetField(bouncer.FieldCreatedAt, field.TypeTime, value)
}
if bu.mutation.CreatedAtCleared() {
_spec.ClearField(bouncer.FieldCreatedAt, field.TypeTime)
}
if value, ok := bu.mutation.UpdatedAt(); ok {
_spec.SetField(bouncer.FieldUpdatedAt, field.TypeTime, value)
}
if bu.mutation.UpdatedAtCleared() {
_spec.ClearField(bouncer.FieldUpdatedAt, field.TypeTime)
}
if value, ok := bu.mutation.Name(); ok {
_spec.SetField(bouncer.FieldName, field.TypeString, value)
}
@ -307,6 +353,24 @@ func (bu *BouncerUpdate) sqlSave(ctx context.Context) (n int, err error) {
if value, ok := bu.mutation.AuthType(); ok {
_spec.SetField(bouncer.FieldAuthType, field.TypeString, value)
}
if value, ok := bu.mutation.Osname(); ok {
_spec.SetField(bouncer.FieldOsname, field.TypeString, value)
}
if bu.mutation.OsnameCleared() {
_spec.ClearField(bouncer.FieldOsname, field.TypeString)
}
if value, ok := bu.mutation.Osversion(); ok {
_spec.SetField(bouncer.FieldOsversion, field.TypeString, value)
}
if bu.mutation.OsversionCleared() {
_spec.ClearField(bouncer.FieldOsversion, field.TypeString)
}
if value, ok := bu.mutation.Featureflags(); ok {
_spec.SetField(bouncer.FieldFeatureflags, field.TypeString, value)
}
if bu.mutation.FeatureflagsCleared() {
_spec.ClearField(bouncer.FieldFeatureflags, field.TypeString)
}
if n, err = sqlgraph.UpdateNodes(ctx, bu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{bouncer.Label}
@ -333,9 +397,11 @@ func (buo *BouncerUpdateOne) SetCreatedAt(t time.Time) *BouncerUpdateOne {
return buo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (buo *BouncerUpdateOne) ClearCreatedAt() *BouncerUpdateOne {
buo.mutation.ClearCreatedAt()
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (buo *BouncerUpdateOne) SetNillableCreatedAt(t *time.Time) *BouncerUpdateOne {
if t != nil {
buo.SetCreatedAt(*t)
}
return buo
}
@ -345,12 +411,6 @@ func (buo *BouncerUpdateOne) SetUpdatedAt(t time.Time) *BouncerUpdateOne {
return buo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (buo *BouncerUpdateOne) ClearUpdatedAt() *BouncerUpdateOne {
buo.mutation.ClearUpdatedAt()
return buo
}
// SetName sets the "name" field.
func (buo *BouncerUpdateOne) SetName(s string) *BouncerUpdateOne {
buo.mutation.SetName(s)
@ -501,6 +561,66 @@ func (buo *BouncerUpdateOne) SetNillableAuthType(s *string) *BouncerUpdateOne {
return buo
}
// SetOsname sets the "osname" field.
func (buo *BouncerUpdateOne) SetOsname(s string) *BouncerUpdateOne {
buo.mutation.SetOsname(s)
return buo
}
// SetNillableOsname sets the "osname" field if the given value is not nil.
func (buo *BouncerUpdateOne) SetNillableOsname(s *string) *BouncerUpdateOne {
if s != nil {
buo.SetOsname(*s)
}
return buo
}
// ClearOsname clears the value of the "osname" field.
func (buo *BouncerUpdateOne) ClearOsname() *BouncerUpdateOne {
buo.mutation.ClearOsname()
return buo
}
// SetOsversion sets the "osversion" field.
func (buo *BouncerUpdateOne) SetOsversion(s string) *BouncerUpdateOne {
buo.mutation.SetOsversion(s)
return buo
}
// SetNillableOsversion sets the "osversion" field if the given value is not nil.
func (buo *BouncerUpdateOne) SetNillableOsversion(s *string) *BouncerUpdateOne {
if s != nil {
buo.SetOsversion(*s)
}
return buo
}
// ClearOsversion clears the value of the "osversion" field.
func (buo *BouncerUpdateOne) ClearOsversion() *BouncerUpdateOne {
buo.mutation.ClearOsversion()
return buo
}
// SetFeatureflags sets the "featureflags" field.
func (buo *BouncerUpdateOne) SetFeatureflags(s string) *BouncerUpdateOne {
buo.mutation.SetFeatureflags(s)
return buo
}
// SetNillableFeatureflags sets the "featureflags" field if the given value is not nil.
func (buo *BouncerUpdateOne) SetNillableFeatureflags(s *string) *BouncerUpdateOne {
if s != nil {
buo.SetFeatureflags(*s)
}
return buo
}
// ClearFeatureflags clears the value of the "featureflags" field.
func (buo *BouncerUpdateOne) ClearFeatureflags() *BouncerUpdateOne {
buo.mutation.ClearFeatureflags()
return buo
}
// Mutation returns the BouncerMutation object of the builder.
func (buo *BouncerUpdateOne) Mutation() *BouncerMutation {
return buo.mutation
@ -549,11 +669,7 @@ func (buo *BouncerUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (buo *BouncerUpdateOne) defaults() {
if _, ok := buo.mutation.CreatedAt(); !ok && !buo.mutation.CreatedAtCleared() {
v := bouncer.UpdateDefaultCreatedAt()
buo.mutation.SetCreatedAt(v)
}
if _, ok := buo.mutation.UpdatedAt(); !ok && !buo.mutation.UpdatedAtCleared() {
if _, ok := buo.mutation.UpdatedAt(); !ok {
v := bouncer.UpdateDefaultUpdatedAt()
buo.mutation.SetUpdatedAt(v)
}
@ -588,15 +704,9 @@ func (buo *BouncerUpdateOne) sqlSave(ctx context.Context) (_node *Bouncer, err e
if value, ok := buo.mutation.CreatedAt(); ok {
_spec.SetField(bouncer.FieldCreatedAt, field.TypeTime, value)
}
if buo.mutation.CreatedAtCleared() {
_spec.ClearField(bouncer.FieldCreatedAt, field.TypeTime)
}
if value, ok := buo.mutation.UpdatedAt(); ok {
_spec.SetField(bouncer.FieldUpdatedAt, field.TypeTime, value)
}
if buo.mutation.UpdatedAtCleared() {
_spec.ClearField(bouncer.FieldUpdatedAt, field.TypeTime)
}
if value, ok := buo.mutation.Name(); ok {
_spec.SetField(bouncer.FieldName, field.TypeString, value)
}
@ -636,6 +746,24 @@ func (buo *BouncerUpdateOne) sqlSave(ctx context.Context) (_node *Bouncer, err e
if value, ok := buo.mutation.AuthType(); ok {
_spec.SetField(bouncer.FieldAuthType, field.TypeString, value)
}
if value, ok := buo.mutation.Osname(); ok {
_spec.SetField(bouncer.FieldOsname, field.TypeString, value)
}
if buo.mutation.OsnameCleared() {
_spec.ClearField(bouncer.FieldOsname, field.TypeString)
}
if value, ok := buo.mutation.Osversion(); ok {
_spec.SetField(bouncer.FieldOsversion, field.TypeString, value)
}
if buo.mutation.OsversionCleared() {
_spec.ClearField(bouncer.FieldOsversion, field.TypeString)
}
if value, ok := buo.mutation.Featureflags(); ok {
_spec.SetField(bouncer.FieldFeatureflags, field.TypeString, value)
}
if buo.mutation.FeatureflagsCleared() {
_spec.ClearField(bouncer.FieldFeatureflags, field.TypeString)
}
_node = &Bouncer{config: buo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues

View file

@ -23,6 +23,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
)
// Client is the client that holds all ent builders.
@ -46,6 +47,8 @@ type Client struct {
Machine *MachineClient
// Meta is the client for interacting with the Meta builders.
Meta *MetaClient
// Metric is the client for interacting with the Metric builders.
Metric *MetricClient
}
// NewClient creates a new client configured with the given options.
@ -65,6 +68,7 @@ func (c *Client) init() {
c.Lock = NewLockClient(c.config)
c.Machine = NewMachineClient(c.config)
c.Meta = NewMetaClient(c.config)
c.Metric = NewMetricClient(c.config)
}
type (
@ -165,6 +169,7 @@ func (c *Client) Tx(ctx context.Context) (*Tx, error) {
Lock: NewLockClient(cfg),
Machine: NewMachineClient(cfg),
Meta: NewMetaClient(cfg),
Metric: NewMetricClient(cfg),
}, nil
}
@ -192,6 +197,7 @@ func (c *Client) BeginTx(ctx context.Context, opts *sql.TxOptions) (*Tx, error)
Lock: NewLockClient(cfg),
Machine: NewMachineClient(cfg),
Meta: NewMetaClient(cfg),
Metric: NewMetricClient(cfg),
}, nil
}
@ -222,7 +228,7 @@ func (c *Client) Close() error {
func (c *Client) Use(hooks ...Hook) {
for _, n := range []interface{ Use(...Hook) }{
c.Alert, c.Bouncer, c.ConfigItem, c.Decision, c.Event, c.Lock, c.Machine,
c.Meta,
c.Meta, c.Metric,
} {
n.Use(hooks...)
}
@ -233,7 +239,7 @@ func (c *Client) Use(hooks ...Hook) {
func (c *Client) Intercept(interceptors ...Interceptor) {
for _, n := range []interface{ Intercept(...Interceptor) }{
c.Alert, c.Bouncer, c.ConfigItem, c.Decision, c.Event, c.Lock, c.Machine,
c.Meta,
c.Meta, c.Metric,
} {
n.Intercept(interceptors...)
}
@ -258,6 +264,8 @@ func (c *Client) Mutate(ctx context.Context, m Mutation) (Value, error) {
return c.Machine.mutate(ctx, m)
case *MetaMutation:
return c.Meta.mutate(ctx, m)
case *MetricMutation:
return c.Metric.mutate(ctx, m)
default:
return nil, fmt.Errorf("ent: unknown mutation type %T", m)
}
@ -1455,13 +1463,147 @@ func (c *MetaClient) mutate(ctx context.Context, m *MetaMutation) (Value, error)
}
}
// MetricClient is a client for the Metric schema.
type MetricClient struct {
config
}
// NewMetricClient returns a client for the Metric from the given config.
func NewMetricClient(c config) *MetricClient {
return &MetricClient{config: c}
}
// Use adds a list of mutation hooks to the hooks stack.
// A call to `Use(f, g, h)` equals to `metric.Hooks(f(g(h())))`.
func (c *MetricClient) Use(hooks ...Hook) {
c.hooks.Metric = append(c.hooks.Metric, hooks...)
}
// Intercept adds a list of query interceptors to the interceptors stack.
// A call to `Intercept(f, g, h)` equals to `metric.Intercept(f(g(h())))`.
func (c *MetricClient) Intercept(interceptors ...Interceptor) {
c.inters.Metric = append(c.inters.Metric, interceptors...)
}
// Create returns a builder for creating a Metric entity.
func (c *MetricClient) Create() *MetricCreate {
mutation := newMetricMutation(c.config, OpCreate)
return &MetricCreate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// CreateBulk returns a builder for creating a bulk of Metric entities.
func (c *MetricClient) CreateBulk(builders ...*MetricCreate) *MetricCreateBulk {
return &MetricCreateBulk{config: c.config, builders: builders}
}
// MapCreateBulk creates a bulk creation builder from the given slice. For each item in the slice, the function creates
// a builder and applies setFunc on it.
func (c *MetricClient) MapCreateBulk(slice any, setFunc func(*MetricCreate, int)) *MetricCreateBulk {
rv := reflect.ValueOf(slice)
if rv.Kind() != reflect.Slice {
return &MetricCreateBulk{err: fmt.Errorf("calling to MetricClient.MapCreateBulk with wrong type %T, need slice", slice)}
}
builders := make([]*MetricCreate, rv.Len())
for i := 0; i < rv.Len(); i++ {
builders[i] = c.Create()
setFunc(builders[i], i)
}
return &MetricCreateBulk{config: c.config, builders: builders}
}
// Update returns an update builder for Metric.
func (c *MetricClient) Update() *MetricUpdate {
mutation := newMetricMutation(c.config, OpUpdate)
return &MetricUpdate{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOne returns an update builder for the given entity.
func (c *MetricClient) UpdateOne(m *Metric) *MetricUpdateOne {
mutation := newMetricMutation(c.config, OpUpdateOne, withMetric(m))
return &MetricUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// UpdateOneID returns an update builder for the given id.
func (c *MetricClient) UpdateOneID(id int) *MetricUpdateOne {
mutation := newMetricMutation(c.config, OpUpdateOne, withMetricID(id))
return &MetricUpdateOne{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// Delete returns a delete builder for Metric.
func (c *MetricClient) Delete() *MetricDelete {
mutation := newMetricMutation(c.config, OpDelete)
return &MetricDelete{config: c.config, hooks: c.Hooks(), mutation: mutation}
}
// DeleteOne returns a builder for deleting the given entity.
func (c *MetricClient) DeleteOne(m *Metric) *MetricDeleteOne {
return c.DeleteOneID(m.ID)
}
// DeleteOneID returns a builder for deleting the given entity by its id.
func (c *MetricClient) DeleteOneID(id int) *MetricDeleteOne {
builder := c.Delete().Where(metric.ID(id))
builder.mutation.id = &id
builder.mutation.op = OpDeleteOne
return &MetricDeleteOne{builder}
}
// Query returns a query builder for Metric.
func (c *MetricClient) Query() *MetricQuery {
return &MetricQuery{
config: c.config,
ctx: &QueryContext{Type: TypeMetric},
inters: c.Interceptors(),
}
}
// Get returns a Metric entity by its id.
func (c *MetricClient) Get(ctx context.Context, id int) (*Metric, error) {
return c.Query().Where(metric.ID(id)).Only(ctx)
}
// GetX is like Get, but panics if an error occurs.
func (c *MetricClient) GetX(ctx context.Context, id int) *Metric {
obj, err := c.Get(ctx, id)
if err != nil {
panic(err)
}
return obj
}
// Hooks returns the client hooks.
func (c *MetricClient) Hooks() []Hook {
return c.hooks.Metric
}
// Interceptors returns the client interceptors.
func (c *MetricClient) Interceptors() []Interceptor {
return c.inters.Metric
}
func (c *MetricClient) mutate(ctx context.Context, m *MetricMutation) (Value, error) {
switch m.Op() {
case OpCreate:
return (&MetricCreate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdate:
return (&MetricUpdate{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpUpdateOne:
return (&MetricUpdateOne{config: c.config, hooks: c.Hooks(), mutation: m}).Save(ctx)
case OpDelete, OpDeleteOne:
return (&MetricDelete{config: c.config, hooks: c.Hooks(), mutation: m}).Exec(ctx)
default:
return nil, fmt.Errorf("ent: unknown Metric mutation op: %q", m.Op())
}
}
// hooks and interceptors per client, for fast access.
type (
hooks struct {
Alert, Bouncer, ConfigItem, Decision, Event, Lock, Machine, Meta []ent.Hook
Alert, Bouncer, ConfigItem, Decision, Event, Lock, Machine, Meta,
Metric []ent.Hook
}
inters struct {
Alert, Bouncer, ConfigItem, Decision, Event, Lock, Machine,
Meta []ent.Interceptor
Alert, Bouncer, ConfigItem, Decision, Event, Lock, Machine, Meta,
Metric []ent.Interceptor
}
)

View file

@ -18,9 +18,9 @@ type ConfigItem struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at"`
CreatedAt time.Time `json:"created_at"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at"`
UpdatedAt time.Time `json:"updated_at"`
// Name holds the value of the "name" field.
Name string `json:"name"`
// Value holds the value of the "value" field.
@ -64,15 +64,13 @@ func (ci *ConfigItem) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
ci.CreatedAt = new(time.Time)
*ci.CreatedAt = value.Time
ci.CreatedAt = value.Time
}
case configitem.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
ci.UpdatedAt = new(time.Time)
*ci.UpdatedAt = value.Time
ci.UpdatedAt = value.Time
}
case configitem.FieldName:
if value, ok := values[i].(*sql.NullString); !ok {
@ -122,15 +120,11 @@ func (ci *ConfigItem) String() string {
var builder strings.Builder
builder.WriteString("ConfigItem(")
builder.WriteString(fmt.Sprintf("id=%v, ", ci.ID))
if v := ci.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(ci.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := ci.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(ci.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("name=")
builder.WriteString(ci.Name)

View file

@ -47,8 +47,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.

View file

@ -114,16 +114,6 @@ func CreatedAtLTE(v time.Time) predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldEQ(FieldUpdatedAt, v))
@ -164,16 +154,6 @@ func UpdatedAtLTE(v time.Time) predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldNotNull(FieldUpdatedAt))
}
// NameEQ applies the EQ predicate on the "name" field.
func NameEQ(v string) predicate.ConfigItem {
return predicate.ConfigItem(sql.FieldEQ(FieldName, v))

View file

@ -107,6 +107,12 @@ func (cic *ConfigItemCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (cic *ConfigItemCreate) check() error {
if _, ok := cic.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "ConfigItem.created_at"`)}
}
if _, ok := cic.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "ConfigItem.updated_at"`)}
}
if _, ok := cic.mutation.Name(); !ok {
return &ValidationError{Name: "name", err: errors.New(`ent: missing required field "ConfigItem.name"`)}
}
@ -141,11 +147,11 @@ func (cic *ConfigItemCreate) createSpec() (*ConfigItem, *sqlgraph.CreateSpec) {
)
if value, ok := cic.mutation.CreatedAt(); ok {
_spec.SetField(configitem.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := cic.mutation.UpdatedAt(); ok {
_spec.SetField(configitem.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := cic.mutation.Name(); ok {
_spec.SetField(configitem.FieldName, field.TypeString, value)

View file

@ -28,30 +28,12 @@ func (ciu *ConfigItemUpdate) Where(ps ...predicate.ConfigItem) *ConfigItemUpdate
return ciu
}
// SetCreatedAt sets the "created_at" field.
func (ciu *ConfigItemUpdate) SetCreatedAt(t time.Time) *ConfigItemUpdate {
ciu.mutation.SetCreatedAt(t)
return ciu
}
// ClearCreatedAt clears the value of the "created_at" field.
func (ciu *ConfigItemUpdate) ClearCreatedAt() *ConfigItemUpdate {
ciu.mutation.ClearCreatedAt()
return ciu
}
// SetUpdatedAt sets the "updated_at" field.
func (ciu *ConfigItemUpdate) SetUpdatedAt(t time.Time) *ConfigItemUpdate {
ciu.mutation.SetUpdatedAt(t)
return ciu
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (ciu *ConfigItemUpdate) ClearUpdatedAt() *ConfigItemUpdate {
ciu.mutation.ClearUpdatedAt()
return ciu
}
// SetName sets the "name" field.
func (ciu *ConfigItemUpdate) SetName(s string) *ConfigItemUpdate {
ciu.mutation.SetName(s)
@ -115,11 +97,7 @@ func (ciu *ConfigItemUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (ciu *ConfigItemUpdate) defaults() {
if _, ok := ciu.mutation.CreatedAt(); !ok && !ciu.mutation.CreatedAtCleared() {
v := configitem.UpdateDefaultCreatedAt()
ciu.mutation.SetCreatedAt(v)
}
if _, ok := ciu.mutation.UpdatedAt(); !ok && !ciu.mutation.UpdatedAtCleared() {
if _, ok := ciu.mutation.UpdatedAt(); !ok {
v := configitem.UpdateDefaultUpdatedAt()
ciu.mutation.SetUpdatedAt(v)
}
@ -134,18 +112,9 @@ func (ciu *ConfigItemUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := ciu.mutation.CreatedAt(); ok {
_spec.SetField(configitem.FieldCreatedAt, field.TypeTime, value)
}
if ciu.mutation.CreatedAtCleared() {
_spec.ClearField(configitem.FieldCreatedAt, field.TypeTime)
}
if value, ok := ciu.mutation.UpdatedAt(); ok {
_spec.SetField(configitem.FieldUpdatedAt, field.TypeTime, value)
}
if ciu.mutation.UpdatedAtCleared() {
_spec.ClearField(configitem.FieldUpdatedAt, field.TypeTime)
}
if value, ok := ciu.mutation.Name(); ok {
_spec.SetField(configitem.FieldName, field.TypeString, value)
}
@ -172,30 +141,12 @@ type ConfigItemUpdateOne struct {
mutation *ConfigItemMutation
}
// SetCreatedAt sets the "created_at" field.
func (ciuo *ConfigItemUpdateOne) SetCreatedAt(t time.Time) *ConfigItemUpdateOne {
ciuo.mutation.SetCreatedAt(t)
return ciuo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (ciuo *ConfigItemUpdateOne) ClearCreatedAt() *ConfigItemUpdateOne {
ciuo.mutation.ClearCreatedAt()
return ciuo
}
// SetUpdatedAt sets the "updated_at" field.
func (ciuo *ConfigItemUpdateOne) SetUpdatedAt(t time.Time) *ConfigItemUpdateOne {
ciuo.mutation.SetUpdatedAt(t)
return ciuo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (ciuo *ConfigItemUpdateOne) ClearUpdatedAt() *ConfigItemUpdateOne {
ciuo.mutation.ClearUpdatedAt()
return ciuo
}
// SetName sets the "name" field.
func (ciuo *ConfigItemUpdateOne) SetName(s string) *ConfigItemUpdateOne {
ciuo.mutation.SetName(s)
@ -272,11 +223,7 @@ func (ciuo *ConfigItemUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (ciuo *ConfigItemUpdateOne) defaults() {
if _, ok := ciuo.mutation.CreatedAt(); !ok && !ciuo.mutation.CreatedAtCleared() {
v := configitem.UpdateDefaultCreatedAt()
ciuo.mutation.SetCreatedAt(v)
}
if _, ok := ciuo.mutation.UpdatedAt(); !ok && !ciuo.mutation.UpdatedAtCleared() {
if _, ok := ciuo.mutation.UpdatedAt(); !ok {
v := configitem.UpdateDefaultUpdatedAt()
ciuo.mutation.SetUpdatedAt(v)
}
@ -308,18 +255,9 @@ func (ciuo *ConfigItemUpdateOne) sqlSave(ctx context.Context) (_node *ConfigItem
}
}
}
if value, ok := ciuo.mutation.CreatedAt(); ok {
_spec.SetField(configitem.FieldCreatedAt, field.TypeTime, value)
}
if ciuo.mutation.CreatedAtCleared() {
_spec.ClearField(configitem.FieldCreatedAt, field.TypeTime)
}
if value, ok := ciuo.mutation.UpdatedAt(); ok {
_spec.SetField(configitem.FieldUpdatedAt, field.TypeTime, value)
}
if ciuo.mutation.UpdatedAtCleared() {
_spec.ClearField(configitem.FieldUpdatedAt, field.TypeTime)
}
if value, ok := ciuo.mutation.Name(); ok {
_spec.SetField(configitem.FieldName, field.TypeString, value)
}

View file

@ -19,9 +19,9 @@ type Decision struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Until holds the value of the "until" field.
Until *time.Time `json:"until,omitempty"`
// Scenario holds the value of the "scenario" field.
@ -116,15 +116,13 @@ func (d *Decision) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
d.CreatedAt = new(time.Time)
*d.CreatedAt = value.Time
d.CreatedAt = value.Time
}
case decision.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
d.UpdatedAt = new(time.Time)
*d.UpdatedAt = value.Time
d.UpdatedAt = value.Time
}
case decision.FieldUntil:
if value, ok := values[i].(*sql.NullTime); !ok {
@ -252,15 +250,11 @@ func (d *Decision) String() string {
var builder strings.Builder
builder.WriteString("Decision(")
builder.WriteString(fmt.Sprintf("id=%v, ", d.ID))
if v := d.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(d.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := d.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(d.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := d.Until; v != nil {
builder.WriteString("until=")

View file

@ -93,8 +93,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.

View file

@ -175,16 +175,6 @@ func CreatedAtLTE(v time.Time) predicate.Decision {
return predicate.Decision(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Decision {
return predicate.Decision(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Decision {
return predicate.Decision(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Decision {
return predicate.Decision(sql.FieldEQ(FieldUpdatedAt, v))
@ -225,16 +215,6 @@ func UpdatedAtLTE(v time.Time) predicate.Decision {
return predicate.Decision(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.Decision {
return predicate.Decision(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.Decision {
return predicate.Decision(sql.FieldNotNull(FieldUpdatedAt))
}
// UntilEQ applies the EQ predicate on the "until" field.
func UntilEQ(v time.Time) predicate.Decision {
return predicate.Decision(sql.FieldEQ(FieldUntil, v))

View file

@ -275,6 +275,12 @@ func (dc *DecisionCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (dc *DecisionCreate) check() error {
if _, ok := dc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Decision.created_at"`)}
}
if _, ok := dc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Decision.updated_at"`)}
}
if _, ok := dc.mutation.Scenario(); !ok {
return &ValidationError{Name: "scenario", err: errors.New(`ent: missing required field "Decision.scenario"`)}
}
@ -321,11 +327,11 @@ func (dc *DecisionCreate) createSpec() (*Decision, *sqlgraph.CreateSpec) {
)
if value, ok := dc.mutation.CreatedAt(); ok {
_spec.SetField(decision.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := dc.mutation.UpdatedAt(); ok {
_spec.SetField(decision.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := dc.mutation.Until(); ok {
_spec.SetField(decision.FieldUntil, field.TypeTime, value)

View file

@ -29,30 +29,12 @@ func (du *DecisionUpdate) Where(ps ...predicate.Decision) *DecisionUpdate {
return du
}
// SetCreatedAt sets the "created_at" field.
func (du *DecisionUpdate) SetCreatedAt(t time.Time) *DecisionUpdate {
du.mutation.SetCreatedAt(t)
return du
}
// ClearCreatedAt clears the value of the "created_at" field.
func (du *DecisionUpdate) ClearCreatedAt() *DecisionUpdate {
du.mutation.ClearCreatedAt()
return du
}
// SetUpdatedAt sets the "updated_at" field.
func (du *DecisionUpdate) SetUpdatedAt(t time.Time) *DecisionUpdate {
du.mutation.SetUpdatedAt(t)
return du
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (du *DecisionUpdate) ClearUpdatedAt() *DecisionUpdate {
du.mutation.ClearUpdatedAt()
return du
}
// SetUntil sets the "until" field.
func (du *DecisionUpdate) SetUntil(t time.Time) *DecisionUpdate {
du.mutation.SetUntil(t)
@ -392,11 +374,7 @@ func (du *DecisionUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (du *DecisionUpdate) defaults() {
if _, ok := du.mutation.CreatedAt(); !ok && !du.mutation.CreatedAtCleared() {
v := decision.UpdateDefaultCreatedAt()
du.mutation.SetCreatedAt(v)
}
if _, ok := du.mutation.UpdatedAt(); !ok && !du.mutation.UpdatedAtCleared() {
if _, ok := du.mutation.UpdatedAt(); !ok {
v := decision.UpdateDefaultUpdatedAt()
du.mutation.SetUpdatedAt(v)
}
@ -411,18 +389,9 @@ func (du *DecisionUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := du.mutation.CreatedAt(); ok {
_spec.SetField(decision.FieldCreatedAt, field.TypeTime, value)
}
if du.mutation.CreatedAtCleared() {
_spec.ClearField(decision.FieldCreatedAt, field.TypeTime)
}
if value, ok := du.mutation.UpdatedAt(); ok {
_spec.SetField(decision.FieldUpdatedAt, field.TypeTime, value)
}
if du.mutation.UpdatedAtCleared() {
_spec.ClearField(decision.FieldUpdatedAt, field.TypeTime)
}
if value, ok := du.mutation.Until(); ok {
_spec.SetField(decision.FieldUntil, field.TypeTime, value)
}
@ -547,30 +516,12 @@ type DecisionUpdateOne struct {
mutation *DecisionMutation
}
// SetCreatedAt sets the "created_at" field.
func (duo *DecisionUpdateOne) SetCreatedAt(t time.Time) *DecisionUpdateOne {
duo.mutation.SetCreatedAt(t)
return duo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (duo *DecisionUpdateOne) ClearCreatedAt() *DecisionUpdateOne {
duo.mutation.ClearCreatedAt()
return duo
}
// SetUpdatedAt sets the "updated_at" field.
func (duo *DecisionUpdateOne) SetUpdatedAt(t time.Time) *DecisionUpdateOne {
duo.mutation.SetUpdatedAt(t)
return duo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (duo *DecisionUpdateOne) ClearUpdatedAt() *DecisionUpdateOne {
duo.mutation.ClearUpdatedAt()
return duo
}
// SetUntil sets the "until" field.
func (duo *DecisionUpdateOne) SetUntil(t time.Time) *DecisionUpdateOne {
duo.mutation.SetUntil(t)
@ -923,11 +874,7 @@ func (duo *DecisionUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (duo *DecisionUpdateOne) defaults() {
if _, ok := duo.mutation.CreatedAt(); !ok && !duo.mutation.CreatedAtCleared() {
v := decision.UpdateDefaultCreatedAt()
duo.mutation.SetCreatedAt(v)
}
if _, ok := duo.mutation.UpdatedAt(); !ok && !duo.mutation.UpdatedAtCleared() {
if _, ok := duo.mutation.UpdatedAt(); !ok {
v := decision.UpdateDefaultUpdatedAt()
duo.mutation.SetUpdatedAt(v)
}
@ -959,18 +906,9 @@ func (duo *DecisionUpdateOne) sqlSave(ctx context.Context) (_node *Decision, err
}
}
}
if value, ok := duo.mutation.CreatedAt(); ok {
_spec.SetField(decision.FieldCreatedAt, field.TypeTime, value)
}
if duo.mutation.CreatedAtCleared() {
_spec.ClearField(decision.FieldCreatedAt, field.TypeTime)
}
if value, ok := duo.mutation.UpdatedAt(); ok {
_spec.SetField(decision.FieldUpdatedAt, field.TypeTime, value)
}
if duo.mutation.UpdatedAtCleared() {
_spec.ClearField(decision.FieldUpdatedAt, field.TypeTime)
}
if value, ok := duo.mutation.Until(); ok {
_spec.SetField(decision.FieldUntil, field.TypeTime, value)
}

View file

@ -20,6 +20,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/database/ent/lock"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/meta"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
)
// ent aliases to avoid import conflicts in user's code.
@ -88,6 +89,7 @@ func checkColumn(table, column string) error {
lock.Table: lock.ValidColumn,
machine.Table: machine.ValidColumn,
meta.Table: meta.ValidColumn,
metric.Table: metric.ValidColumn,
})
})
return columnCheck(table, column)

View file

@ -19,9 +19,9 @@ type Event struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Time holds the value of the "time" field.
Time time.Time `json:"time,omitempty"`
// Serialized holds the value of the "serialized" field.
@ -92,15 +92,13 @@ func (e *Event) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
e.CreatedAt = new(time.Time)
*e.CreatedAt = value.Time
e.CreatedAt = value.Time
}
case event.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
e.UpdatedAt = new(time.Time)
*e.UpdatedAt = value.Time
e.UpdatedAt = value.Time
}
case event.FieldTime:
if value, ok := values[i].(*sql.NullTime); !ok {
@ -161,15 +159,11 @@ func (e *Event) String() string {
var builder strings.Builder
builder.WriteString("Event(")
builder.WriteString(fmt.Sprintf("id=%v, ", e.ID))
if v := e.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(e.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := e.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(e.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("time=")
builder.WriteString(e.Time.Format(time.ANSIC))

View file

@ -60,8 +60,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.

View file

@ -120,16 +120,6 @@ func CreatedAtLTE(v time.Time) predicate.Event {
return predicate.Event(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Event {
return predicate.Event(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Event {
return predicate.Event(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Event {
return predicate.Event(sql.FieldEQ(FieldUpdatedAt, v))
@ -170,16 +160,6 @@ func UpdatedAtLTE(v time.Time) predicate.Event {
return predicate.Event(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.Event {
return predicate.Event(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.Event {
return predicate.Event(sql.FieldNotNull(FieldUpdatedAt))
}
// TimeEQ applies the EQ predicate on the "time" field.
func TimeEQ(v time.Time) predicate.Event {
return predicate.Event(sql.FieldEQ(FieldTime, v))

View file

@ -141,6 +141,12 @@ func (ec *EventCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (ec *EventCreate) check() error {
if _, ok := ec.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Event.created_at"`)}
}
if _, ok := ec.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Event.updated_at"`)}
}
if _, ok := ec.mutation.Time(); !ok {
return &ValidationError{Name: "time", err: errors.New(`ent: missing required field "Event.time"`)}
}
@ -180,11 +186,11 @@ func (ec *EventCreate) createSpec() (*Event, *sqlgraph.CreateSpec) {
)
if value, ok := ec.mutation.CreatedAt(); ok {
_spec.SetField(event.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := ec.mutation.UpdatedAt(); ok {
_spec.SetField(event.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := ec.mutation.Time(); ok {
_spec.SetField(event.FieldTime, field.TypeTime, value)

View file

@ -29,30 +29,12 @@ func (eu *EventUpdate) Where(ps ...predicate.Event) *EventUpdate {
return eu
}
// SetCreatedAt sets the "created_at" field.
func (eu *EventUpdate) SetCreatedAt(t time.Time) *EventUpdate {
eu.mutation.SetCreatedAt(t)
return eu
}
// ClearCreatedAt clears the value of the "created_at" field.
func (eu *EventUpdate) ClearCreatedAt() *EventUpdate {
eu.mutation.ClearCreatedAt()
return eu
}
// SetUpdatedAt sets the "updated_at" field.
func (eu *EventUpdate) SetUpdatedAt(t time.Time) *EventUpdate {
eu.mutation.SetUpdatedAt(t)
return eu
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (eu *EventUpdate) ClearUpdatedAt() *EventUpdate {
eu.mutation.ClearUpdatedAt()
return eu
}
// SetTime sets the "time" field.
func (eu *EventUpdate) SetTime(t time.Time) *EventUpdate {
eu.mutation.SetTime(t)
@ -161,11 +143,7 @@ func (eu *EventUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (eu *EventUpdate) defaults() {
if _, ok := eu.mutation.CreatedAt(); !ok && !eu.mutation.CreatedAtCleared() {
v := event.UpdateDefaultCreatedAt()
eu.mutation.SetCreatedAt(v)
}
if _, ok := eu.mutation.UpdatedAt(); !ok && !eu.mutation.UpdatedAtCleared() {
if _, ok := eu.mutation.UpdatedAt(); !ok {
v := event.UpdateDefaultUpdatedAt()
eu.mutation.SetUpdatedAt(v)
}
@ -193,18 +171,9 @@ func (eu *EventUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := eu.mutation.CreatedAt(); ok {
_spec.SetField(event.FieldCreatedAt, field.TypeTime, value)
}
if eu.mutation.CreatedAtCleared() {
_spec.ClearField(event.FieldCreatedAt, field.TypeTime)
}
if value, ok := eu.mutation.UpdatedAt(); ok {
_spec.SetField(event.FieldUpdatedAt, field.TypeTime, value)
}
if eu.mutation.UpdatedAtCleared() {
_spec.ClearField(event.FieldUpdatedAt, field.TypeTime)
}
if value, ok := eu.mutation.Time(); ok {
_spec.SetField(event.FieldTime, field.TypeTime, value)
}
@ -260,30 +229,12 @@ type EventUpdateOne struct {
mutation *EventMutation
}
// SetCreatedAt sets the "created_at" field.
func (euo *EventUpdateOne) SetCreatedAt(t time.Time) *EventUpdateOne {
euo.mutation.SetCreatedAt(t)
return euo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (euo *EventUpdateOne) ClearCreatedAt() *EventUpdateOne {
euo.mutation.ClearCreatedAt()
return euo
}
// SetUpdatedAt sets the "updated_at" field.
func (euo *EventUpdateOne) SetUpdatedAt(t time.Time) *EventUpdateOne {
euo.mutation.SetUpdatedAt(t)
return euo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (euo *EventUpdateOne) ClearUpdatedAt() *EventUpdateOne {
euo.mutation.ClearUpdatedAt()
return euo
}
// SetTime sets the "time" field.
func (euo *EventUpdateOne) SetTime(t time.Time) *EventUpdateOne {
euo.mutation.SetTime(t)
@ -405,11 +356,7 @@ func (euo *EventUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (euo *EventUpdateOne) defaults() {
if _, ok := euo.mutation.CreatedAt(); !ok && !euo.mutation.CreatedAtCleared() {
v := event.UpdateDefaultCreatedAt()
euo.mutation.SetCreatedAt(v)
}
if _, ok := euo.mutation.UpdatedAt(); !ok && !euo.mutation.UpdatedAtCleared() {
if _, ok := euo.mutation.UpdatedAt(); !ok {
v := event.UpdateDefaultUpdatedAt()
euo.mutation.SetUpdatedAt(v)
}
@ -454,18 +401,9 @@ func (euo *EventUpdateOne) sqlSave(ctx context.Context) (_node *Event, err error
}
}
}
if value, ok := euo.mutation.CreatedAt(); ok {
_spec.SetField(event.FieldCreatedAt, field.TypeTime, value)
}
if euo.mutation.CreatedAtCleared() {
_spec.ClearField(event.FieldCreatedAt, field.TypeTime)
}
if value, ok := euo.mutation.UpdatedAt(); ok {
_spec.SetField(event.FieldUpdatedAt, field.TypeTime, value)
}
if euo.mutation.UpdatedAtCleared() {
_spec.ClearField(event.FieldUpdatedAt, field.TypeTime)
}
if value, ok := euo.mutation.Time(); ok {
_spec.SetField(event.FieldTime, field.TypeTime, value)
}

View file

@ -105,6 +105,18 @@ func (f MetaFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error)
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MetaMutation", m)
}
// The MetricFunc type is an adapter to allow the use of ordinary
// function as Metric mutator.
type MetricFunc func(context.Context, *ent.MetricMutation) (ent.Value, error)
// Mutate calls f(ctx, m).
func (f MetricFunc) Mutate(ctx context.Context, m ent.Mutation) (ent.Value, error) {
if mv, ok := m.(*ent.MetricMutation); ok {
return f(ctx, mv)
}
return nil, fmt.Errorf("unexpected mutation type %T. expect *ent.MetricMutation", m)
}
// Condition is a hook condition function.
type Condition func(context.Context, ent.Mutation) bool

View file

@ -28,20 +28,6 @@ func (lu *LockUpdate) Where(ps ...predicate.Lock) *LockUpdate {
return lu
}
// SetName sets the "name" field.
func (lu *LockUpdate) SetName(s string) *LockUpdate {
lu.mutation.SetName(s)
return lu
}
// SetNillableName sets the "name" field if the given value is not nil.
func (lu *LockUpdate) SetNillableName(s *string) *LockUpdate {
if s != nil {
lu.SetName(*s)
}
return lu
}
// SetCreatedAt sets the "created_at" field.
func (lu *LockUpdate) SetCreatedAt(t time.Time) *LockUpdate {
lu.mutation.SetCreatedAt(t)
@ -97,9 +83,6 @@ func (lu *LockUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := lu.mutation.Name(); ok {
_spec.SetField(lock.FieldName, field.TypeString, value)
}
if value, ok := lu.mutation.CreatedAt(); ok {
_spec.SetField(lock.FieldCreatedAt, field.TypeTime, value)
}
@ -123,20 +106,6 @@ type LockUpdateOne struct {
mutation *LockMutation
}
// SetName sets the "name" field.
func (luo *LockUpdateOne) SetName(s string) *LockUpdateOne {
luo.mutation.SetName(s)
return luo
}
// SetNillableName sets the "name" field if the given value is not nil.
func (luo *LockUpdateOne) SetNillableName(s *string) *LockUpdateOne {
if s != nil {
luo.SetName(*s)
}
return luo
}
// SetCreatedAt sets the "created_at" field.
func (luo *LockUpdateOne) SetCreatedAt(t time.Time) *LockUpdateOne {
luo.mutation.SetCreatedAt(t)
@ -222,9 +191,6 @@ func (luo *LockUpdateOne) sqlSave(ctx context.Context) (_node *Lock, err error)
}
}
}
if value, ok := luo.mutation.Name(); ok {
_spec.SetField(lock.FieldName, field.TypeString, value)
}
if value, ok := luo.mutation.CreatedAt(); ok {
_spec.SetField(lock.FieldCreatedAt, field.TypeTime, value)
}

View file

@ -3,6 +3,7 @@
package ent
import (
"encoding/json"
"fmt"
"strings"
"time"
@ -10,6 +11,7 @@ import (
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// Machine is the model entity for the Machine schema.
@ -18,9 +20,9 @@ type Machine struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
// LastPush holds the value of the "last_push" field.
LastPush *time.Time `json:"last_push,omitempty"`
// LastHeartbeat holds the value of the "last_heartbeat" field.
@ -41,6 +43,14 @@ type Machine struct {
Status string `json:"status,omitempty"`
// AuthType holds the value of the "auth_type" field.
AuthType string `json:"auth_type"`
// Osname holds the value of the "osname" field.
Osname string `json:"osname,omitempty"`
// Osversion holds the value of the "osversion" field.
Osversion string `json:"osversion,omitempty"`
// Featureflags holds the value of the "featureflags" field.
Featureflags string `json:"featureflags,omitempty"`
// Hubstate holds the value of the "hubstate" field.
Hubstate *models.HubItems `json:"hubstate,omitempty"`
// Edges holds the relations/edges for other nodes in the graph.
// The values are being populated by the MachineQuery when eager-loading is set.
Edges MachineEdges `json:"edges"`
@ -70,11 +80,13 @@ func (*Machine) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case machine.FieldHubstate:
values[i] = new([]byte)
case machine.FieldIsValidated:
values[i] = new(sql.NullBool)
case machine.FieldID:
values[i] = new(sql.NullInt64)
case machine.FieldMachineId, machine.FieldPassword, machine.FieldIpAddress, machine.FieldScenarios, machine.FieldVersion, machine.FieldStatus, machine.FieldAuthType:
case machine.FieldMachineId, machine.FieldPassword, machine.FieldIpAddress, machine.FieldScenarios, machine.FieldVersion, machine.FieldStatus, machine.FieldAuthType, machine.FieldOsname, machine.FieldOsversion, machine.FieldFeatureflags:
values[i] = new(sql.NullString)
case machine.FieldCreatedAt, machine.FieldUpdatedAt, machine.FieldLastPush, machine.FieldLastHeartbeat:
values[i] = new(sql.NullTime)
@ -103,15 +115,13 @@ func (m *Machine) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
m.CreatedAt = new(time.Time)
*m.CreatedAt = value.Time
m.CreatedAt = value.Time
}
case machine.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
m.UpdatedAt = new(time.Time)
*m.UpdatedAt = value.Time
m.UpdatedAt = value.Time
}
case machine.FieldLastPush:
if value, ok := values[i].(*sql.NullTime); !ok {
@ -175,6 +185,32 @@ func (m *Machine) assignValues(columns []string, values []any) error {
} else if value.Valid {
m.AuthType = value.String
}
case machine.FieldOsname:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field osname", values[i])
} else if value.Valid {
m.Osname = value.String
}
case machine.FieldOsversion:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field osversion", values[i])
} else if value.Valid {
m.Osversion = value.String
}
case machine.FieldFeatureflags:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field featureflags", values[i])
} else if value.Valid {
m.Featureflags = value.String
}
case machine.FieldHubstate:
if value, ok := values[i].(*[]byte); !ok {
return fmt.Errorf("unexpected type %T for field hubstate", values[i])
} else if value != nil && len(*value) > 0 {
if err := json.Unmarshal(*value, &m.Hubstate); err != nil {
return fmt.Errorf("unmarshal field hubstate: %w", err)
}
}
default:
m.selectValues.Set(columns[i], values[i])
}
@ -216,15 +252,11 @@ func (m *Machine) String() string {
var builder strings.Builder
builder.WriteString("Machine(")
builder.WriteString(fmt.Sprintf("id=%v, ", m.ID))
if v := m.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := m.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(m.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := m.LastPush; v != nil {
builder.WriteString("last_push=")
@ -258,6 +290,18 @@ func (m *Machine) String() string {
builder.WriteString(", ")
builder.WriteString("auth_type=")
builder.WriteString(m.AuthType)
builder.WriteString(", ")
builder.WriteString("osname=")
builder.WriteString(m.Osname)
builder.WriteString(", ")
builder.WriteString("osversion=")
builder.WriteString(m.Osversion)
builder.WriteString(", ")
builder.WriteString("featureflags=")
builder.WriteString(m.Featureflags)
builder.WriteString(", ")
builder.WriteString("hubstate=")
builder.WriteString(fmt.Sprintf("%v", m.Hubstate))
builder.WriteByte(')')
return builder.String()
}

View file

@ -38,6 +38,14 @@ const (
FieldStatus = "status"
// FieldAuthType holds the string denoting the auth_type field in the database.
FieldAuthType = "auth_type"
// FieldOsname holds the string denoting the osname field in the database.
FieldOsname = "osname"
// FieldOsversion holds the string denoting the osversion field in the database.
FieldOsversion = "osversion"
// FieldFeatureflags holds the string denoting the featureflags field in the database.
FieldFeatureflags = "featureflags"
// FieldHubstate holds the string denoting the hubstate field in the database.
FieldHubstate = "hubstate"
// EdgeAlerts holds the string denoting the alerts edge name in mutations.
EdgeAlerts = "alerts"
// Table holds the table name of the machine in the database.
@ -66,6 +74,10 @@ var Columns = []string{
FieldIsValidated,
FieldStatus,
FieldAuthType,
FieldOsname,
FieldOsversion,
FieldFeatureflags,
FieldHubstate,
}
// ValidColumn reports if the column name is valid (part of the table columns).
@ -81,8 +93,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.
@ -171,6 +181,21 @@ func ByAuthType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldAuthType, opts...).ToFunc()
}
// ByOsname orders the results by the osname field.
func ByOsname(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOsname, opts...).ToFunc()
}
// ByOsversion orders the results by the osversion field.
func ByOsversion(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldOsversion, opts...).ToFunc()
}
// ByFeatureflags orders the results by the featureflags field.
func ByFeatureflags(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldFeatureflags, opts...).ToFunc()
}
// ByAlertsCount orders the results by alerts count.
func ByAlertsCount(opts ...sql.OrderTermOption) OrderOption {
return func(s *sql.Selector) {

View file

@ -115,6 +115,21 @@ func AuthType(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldAuthType, v))
}
// Osname applies equality check predicate on the "osname" field. It's identical to OsnameEQ.
func Osname(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldOsname, v))
}
// Osversion applies equality check predicate on the "osversion" field. It's identical to OsversionEQ.
func Osversion(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldOsversion, v))
}
// Featureflags applies equality check predicate on the "featureflags" field. It's identical to FeatureflagsEQ.
func Featureflags(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldFeatureflags, v))
}
// CreatedAtEQ applies the EQ predicate on the "created_at" field.
func CreatedAtEQ(v time.Time) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldCreatedAt, v))
@ -155,16 +170,6 @@ func CreatedAtLTE(v time.Time) predicate.Machine {
return predicate.Machine(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Machine {
return predicate.Machine(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Machine {
return predicate.Machine(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldUpdatedAt, v))
@ -205,16 +210,6 @@ func UpdatedAtLTE(v time.Time) predicate.Machine {
return predicate.Machine(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.Machine {
return predicate.Machine(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.Machine {
return predicate.Machine(sql.FieldNotNull(FieldUpdatedAt))
}
// LastPushEQ applies the EQ predicate on the "last_push" field.
func LastPushEQ(v time.Time) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldLastPush, v))
@ -810,6 +805,241 @@ func AuthTypeContainsFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldContainsFold(FieldAuthType, v))
}
// OsnameEQ applies the EQ predicate on the "osname" field.
func OsnameEQ(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldOsname, v))
}
// OsnameNEQ applies the NEQ predicate on the "osname" field.
func OsnameNEQ(v string) predicate.Machine {
return predicate.Machine(sql.FieldNEQ(FieldOsname, v))
}
// OsnameIn applies the In predicate on the "osname" field.
func OsnameIn(vs ...string) predicate.Machine {
return predicate.Machine(sql.FieldIn(FieldOsname, vs...))
}
// OsnameNotIn applies the NotIn predicate on the "osname" field.
func OsnameNotIn(vs ...string) predicate.Machine {
return predicate.Machine(sql.FieldNotIn(FieldOsname, vs...))
}
// OsnameGT applies the GT predicate on the "osname" field.
func OsnameGT(v string) predicate.Machine {
return predicate.Machine(sql.FieldGT(FieldOsname, v))
}
// OsnameGTE applies the GTE predicate on the "osname" field.
func OsnameGTE(v string) predicate.Machine {
return predicate.Machine(sql.FieldGTE(FieldOsname, v))
}
// OsnameLT applies the LT predicate on the "osname" field.
func OsnameLT(v string) predicate.Machine {
return predicate.Machine(sql.FieldLT(FieldOsname, v))
}
// OsnameLTE applies the LTE predicate on the "osname" field.
func OsnameLTE(v string) predicate.Machine {
return predicate.Machine(sql.FieldLTE(FieldOsname, v))
}
// OsnameContains applies the Contains predicate on the "osname" field.
func OsnameContains(v string) predicate.Machine {
return predicate.Machine(sql.FieldContains(FieldOsname, v))
}
// OsnameHasPrefix applies the HasPrefix predicate on the "osname" field.
func OsnameHasPrefix(v string) predicate.Machine {
return predicate.Machine(sql.FieldHasPrefix(FieldOsname, v))
}
// OsnameHasSuffix applies the HasSuffix predicate on the "osname" field.
func OsnameHasSuffix(v string) predicate.Machine {
return predicate.Machine(sql.FieldHasSuffix(FieldOsname, v))
}
// OsnameIsNil applies the IsNil predicate on the "osname" field.
func OsnameIsNil() predicate.Machine {
return predicate.Machine(sql.FieldIsNull(FieldOsname))
}
// OsnameNotNil applies the NotNil predicate on the "osname" field.
func OsnameNotNil() predicate.Machine {
return predicate.Machine(sql.FieldNotNull(FieldOsname))
}
// OsnameEqualFold applies the EqualFold predicate on the "osname" field.
func OsnameEqualFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldEqualFold(FieldOsname, v))
}
// OsnameContainsFold applies the ContainsFold predicate on the "osname" field.
func OsnameContainsFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldContainsFold(FieldOsname, v))
}
// OsversionEQ applies the EQ predicate on the "osversion" field.
func OsversionEQ(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldOsversion, v))
}
// OsversionNEQ applies the NEQ predicate on the "osversion" field.
func OsversionNEQ(v string) predicate.Machine {
return predicate.Machine(sql.FieldNEQ(FieldOsversion, v))
}
// OsversionIn applies the In predicate on the "osversion" field.
func OsversionIn(vs ...string) predicate.Machine {
return predicate.Machine(sql.FieldIn(FieldOsversion, vs...))
}
// OsversionNotIn applies the NotIn predicate on the "osversion" field.
func OsversionNotIn(vs ...string) predicate.Machine {
return predicate.Machine(sql.FieldNotIn(FieldOsversion, vs...))
}
// OsversionGT applies the GT predicate on the "osversion" field.
func OsversionGT(v string) predicate.Machine {
return predicate.Machine(sql.FieldGT(FieldOsversion, v))
}
// OsversionGTE applies the GTE predicate on the "osversion" field.
func OsversionGTE(v string) predicate.Machine {
return predicate.Machine(sql.FieldGTE(FieldOsversion, v))
}
// OsversionLT applies the LT predicate on the "osversion" field.
func OsversionLT(v string) predicate.Machine {
return predicate.Machine(sql.FieldLT(FieldOsversion, v))
}
// OsversionLTE applies the LTE predicate on the "osversion" field.
func OsversionLTE(v string) predicate.Machine {
return predicate.Machine(sql.FieldLTE(FieldOsversion, v))
}
// OsversionContains applies the Contains predicate on the "osversion" field.
func OsversionContains(v string) predicate.Machine {
return predicate.Machine(sql.FieldContains(FieldOsversion, v))
}
// OsversionHasPrefix applies the HasPrefix predicate on the "osversion" field.
func OsversionHasPrefix(v string) predicate.Machine {
return predicate.Machine(sql.FieldHasPrefix(FieldOsversion, v))
}
// OsversionHasSuffix applies the HasSuffix predicate on the "osversion" field.
func OsversionHasSuffix(v string) predicate.Machine {
return predicate.Machine(sql.FieldHasSuffix(FieldOsversion, v))
}
// OsversionIsNil applies the IsNil predicate on the "osversion" field.
func OsversionIsNil() predicate.Machine {
return predicate.Machine(sql.FieldIsNull(FieldOsversion))
}
// OsversionNotNil applies the NotNil predicate on the "osversion" field.
func OsversionNotNil() predicate.Machine {
return predicate.Machine(sql.FieldNotNull(FieldOsversion))
}
// OsversionEqualFold applies the EqualFold predicate on the "osversion" field.
func OsversionEqualFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldEqualFold(FieldOsversion, v))
}
// OsversionContainsFold applies the ContainsFold predicate on the "osversion" field.
func OsversionContainsFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldContainsFold(FieldOsversion, v))
}
// FeatureflagsEQ applies the EQ predicate on the "featureflags" field.
func FeatureflagsEQ(v string) predicate.Machine {
return predicate.Machine(sql.FieldEQ(FieldFeatureflags, v))
}
// FeatureflagsNEQ applies the NEQ predicate on the "featureflags" field.
func FeatureflagsNEQ(v string) predicate.Machine {
return predicate.Machine(sql.FieldNEQ(FieldFeatureflags, v))
}
// FeatureflagsIn applies the In predicate on the "featureflags" field.
func FeatureflagsIn(vs ...string) predicate.Machine {
return predicate.Machine(sql.FieldIn(FieldFeatureflags, vs...))
}
// FeatureflagsNotIn applies the NotIn predicate on the "featureflags" field.
func FeatureflagsNotIn(vs ...string) predicate.Machine {
return predicate.Machine(sql.FieldNotIn(FieldFeatureflags, vs...))
}
// FeatureflagsGT applies the GT predicate on the "featureflags" field.
func FeatureflagsGT(v string) predicate.Machine {
return predicate.Machine(sql.FieldGT(FieldFeatureflags, v))
}
// FeatureflagsGTE applies the GTE predicate on the "featureflags" field.
func FeatureflagsGTE(v string) predicate.Machine {
return predicate.Machine(sql.FieldGTE(FieldFeatureflags, v))
}
// FeatureflagsLT applies the LT predicate on the "featureflags" field.
func FeatureflagsLT(v string) predicate.Machine {
return predicate.Machine(sql.FieldLT(FieldFeatureflags, v))
}
// FeatureflagsLTE applies the LTE predicate on the "featureflags" field.
func FeatureflagsLTE(v string) predicate.Machine {
return predicate.Machine(sql.FieldLTE(FieldFeatureflags, v))
}
// FeatureflagsContains applies the Contains predicate on the "featureflags" field.
func FeatureflagsContains(v string) predicate.Machine {
return predicate.Machine(sql.FieldContains(FieldFeatureflags, v))
}
// FeatureflagsHasPrefix applies the HasPrefix predicate on the "featureflags" field.
func FeatureflagsHasPrefix(v string) predicate.Machine {
return predicate.Machine(sql.FieldHasPrefix(FieldFeatureflags, v))
}
// FeatureflagsHasSuffix applies the HasSuffix predicate on the "featureflags" field.
func FeatureflagsHasSuffix(v string) predicate.Machine {
return predicate.Machine(sql.FieldHasSuffix(FieldFeatureflags, v))
}
// FeatureflagsIsNil applies the IsNil predicate on the "featureflags" field.
func FeatureflagsIsNil() predicate.Machine {
return predicate.Machine(sql.FieldIsNull(FieldFeatureflags))
}
// FeatureflagsNotNil applies the NotNil predicate on the "featureflags" field.
func FeatureflagsNotNil() predicate.Machine {
return predicate.Machine(sql.FieldNotNull(FieldFeatureflags))
}
// FeatureflagsEqualFold applies the EqualFold predicate on the "featureflags" field.
func FeatureflagsEqualFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldEqualFold(FieldFeatureflags, v))
}
// FeatureflagsContainsFold applies the ContainsFold predicate on the "featureflags" field.
func FeatureflagsContainsFold(v string) predicate.Machine {
return predicate.Machine(sql.FieldContainsFold(FieldFeatureflags, v))
}
// HubstateIsNil applies the IsNil predicate on the "hubstate" field.
func HubstateIsNil() predicate.Machine {
return predicate.Machine(sql.FieldIsNull(FieldHubstate))
}
// HubstateNotNil applies the NotNil predicate on the "hubstate" field.
func HubstateNotNil() predicate.Machine {
return predicate.Machine(sql.FieldNotNull(FieldHubstate))
}
// HasAlerts applies the HasEdge predicate on the "alerts" edge.
func HasAlerts() predicate.Machine {
return predicate.Machine(func(s *sql.Selector) {

View file

@ -12,6 +12,7 @@ import (
"entgo.io/ent/schema/field"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/alert"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// MachineCreate is the builder for creating a Machine entity.
@ -165,6 +166,54 @@ func (mc *MachineCreate) SetNillableAuthType(s *string) *MachineCreate {
return mc
}
// SetOsname sets the "osname" field.
func (mc *MachineCreate) SetOsname(s string) *MachineCreate {
mc.mutation.SetOsname(s)
return mc
}
// SetNillableOsname sets the "osname" field if the given value is not nil.
func (mc *MachineCreate) SetNillableOsname(s *string) *MachineCreate {
if s != nil {
mc.SetOsname(*s)
}
return mc
}
// SetOsversion sets the "osversion" field.
func (mc *MachineCreate) SetOsversion(s string) *MachineCreate {
mc.mutation.SetOsversion(s)
return mc
}
// SetNillableOsversion sets the "osversion" field if the given value is not nil.
func (mc *MachineCreate) SetNillableOsversion(s *string) *MachineCreate {
if s != nil {
mc.SetOsversion(*s)
}
return mc
}
// SetFeatureflags sets the "featureflags" field.
func (mc *MachineCreate) SetFeatureflags(s string) *MachineCreate {
mc.mutation.SetFeatureflags(s)
return mc
}
// SetNillableFeatureflags sets the "featureflags" field if the given value is not nil.
func (mc *MachineCreate) SetNillableFeatureflags(s *string) *MachineCreate {
if s != nil {
mc.SetFeatureflags(*s)
}
return mc
}
// SetHubstate sets the "hubstate" field.
func (mc *MachineCreate) SetHubstate(mi *models.HubItems) *MachineCreate {
mc.mutation.SetHubstate(mi)
return mc
}
// AddAlertIDs adds the "alerts" edge to the Alert entity by IDs.
func (mc *MachineCreate) AddAlertIDs(ids ...int) *MachineCreate {
mc.mutation.AddAlertIDs(ids...)
@ -243,6 +292,12 @@ func (mc *MachineCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (mc *MachineCreate) check() error {
if _, ok := mc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Machine.created_at"`)}
}
if _, ok := mc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Machine.updated_at"`)}
}
if _, ok := mc.mutation.MachineId(); !ok {
return &ValidationError{Name: "machineId", err: errors.New(`ent: missing required field "Machine.machineId"`)}
}
@ -291,11 +346,11 @@ func (mc *MachineCreate) createSpec() (*Machine, *sqlgraph.CreateSpec) {
)
if value, ok := mc.mutation.CreatedAt(); ok {
_spec.SetField(machine.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := mc.mutation.UpdatedAt(); ok {
_spec.SetField(machine.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := mc.mutation.LastPush(); ok {
_spec.SetField(machine.FieldLastPush, field.TypeTime, value)
@ -337,6 +392,22 @@ func (mc *MachineCreate) createSpec() (*Machine, *sqlgraph.CreateSpec) {
_spec.SetField(machine.FieldAuthType, field.TypeString, value)
_node.AuthType = value
}
if value, ok := mc.mutation.Osname(); ok {
_spec.SetField(machine.FieldOsname, field.TypeString, value)
_node.Osname = value
}
if value, ok := mc.mutation.Osversion(); ok {
_spec.SetField(machine.FieldOsversion, field.TypeString, value)
_node.Osversion = value
}
if value, ok := mc.mutation.Featureflags(); ok {
_spec.SetField(machine.FieldFeatureflags, field.TypeString, value)
_node.Featureflags = value
}
if value, ok := mc.mutation.Hubstate(); ok {
_spec.SetField(machine.FieldHubstate, field.TypeJSON, value)
_node.Hubstate = value
}
if nodes := mc.mutation.AlertsIDs(); len(nodes) > 0 {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,

View file

@ -14,6 +14,7 @@ import (
"github.com/crowdsecurity/crowdsec/pkg/database/ent/alert"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// MachineUpdate is the builder for updating Machine entities.
@ -29,30 +30,12 @@ func (mu *MachineUpdate) Where(ps ...predicate.Machine) *MachineUpdate {
return mu
}
// SetCreatedAt sets the "created_at" field.
func (mu *MachineUpdate) SetCreatedAt(t time.Time) *MachineUpdate {
mu.mutation.SetCreatedAt(t)
return mu
}
// ClearCreatedAt clears the value of the "created_at" field.
func (mu *MachineUpdate) ClearCreatedAt() *MachineUpdate {
mu.mutation.ClearCreatedAt()
return mu
}
// SetUpdatedAt sets the "updated_at" field.
func (mu *MachineUpdate) SetUpdatedAt(t time.Time) *MachineUpdate {
mu.mutation.SetUpdatedAt(t)
return mu
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (mu *MachineUpdate) ClearUpdatedAt() *MachineUpdate {
mu.mutation.ClearUpdatedAt()
return mu
}
// SetLastPush sets the "last_push" field.
func (mu *MachineUpdate) SetLastPush(t time.Time) *MachineUpdate {
mu.mutation.SetLastPush(t)
@ -77,20 +60,6 @@ func (mu *MachineUpdate) ClearLastHeartbeat() *MachineUpdate {
return mu
}
// SetMachineId sets the "machineId" field.
func (mu *MachineUpdate) SetMachineId(s string) *MachineUpdate {
mu.mutation.SetMachineId(s)
return mu
}
// SetNillableMachineId sets the "machineId" field if the given value is not nil.
func (mu *MachineUpdate) SetNillableMachineId(s *string) *MachineUpdate {
if s != nil {
mu.SetMachineId(*s)
}
return mu
}
// SetPassword sets the "password" field.
func (mu *MachineUpdate) SetPassword(s string) *MachineUpdate {
mu.mutation.SetPassword(s)
@ -207,6 +176,78 @@ func (mu *MachineUpdate) SetNillableAuthType(s *string) *MachineUpdate {
return mu
}
// SetOsname sets the "osname" field.
func (mu *MachineUpdate) SetOsname(s string) *MachineUpdate {
mu.mutation.SetOsname(s)
return mu
}
// SetNillableOsname sets the "osname" field if the given value is not nil.
func (mu *MachineUpdate) SetNillableOsname(s *string) *MachineUpdate {
if s != nil {
mu.SetOsname(*s)
}
return mu
}
// ClearOsname clears the value of the "osname" field.
func (mu *MachineUpdate) ClearOsname() *MachineUpdate {
mu.mutation.ClearOsname()
return mu
}
// SetOsversion sets the "osversion" field.
func (mu *MachineUpdate) SetOsversion(s string) *MachineUpdate {
mu.mutation.SetOsversion(s)
return mu
}
// SetNillableOsversion sets the "osversion" field if the given value is not nil.
func (mu *MachineUpdate) SetNillableOsversion(s *string) *MachineUpdate {
if s != nil {
mu.SetOsversion(*s)
}
return mu
}
// ClearOsversion clears the value of the "osversion" field.
func (mu *MachineUpdate) ClearOsversion() *MachineUpdate {
mu.mutation.ClearOsversion()
return mu
}
// SetFeatureflags sets the "featureflags" field.
func (mu *MachineUpdate) SetFeatureflags(s string) *MachineUpdate {
mu.mutation.SetFeatureflags(s)
return mu
}
// SetNillableFeatureflags sets the "featureflags" field if the given value is not nil.
func (mu *MachineUpdate) SetNillableFeatureflags(s *string) *MachineUpdate {
if s != nil {
mu.SetFeatureflags(*s)
}
return mu
}
// ClearFeatureflags clears the value of the "featureflags" field.
func (mu *MachineUpdate) ClearFeatureflags() *MachineUpdate {
mu.mutation.ClearFeatureflags()
return mu
}
// SetHubstate sets the "hubstate" field.
func (mu *MachineUpdate) SetHubstate(mi *models.HubItems) *MachineUpdate {
mu.mutation.SetHubstate(mi)
return mu
}
// ClearHubstate clears the value of the "hubstate" field.
func (mu *MachineUpdate) ClearHubstate() *MachineUpdate {
mu.mutation.ClearHubstate()
return mu
}
// AddAlertIDs adds the "alerts" edge to the Alert entity by IDs.
func (mu *MachineUpdate) AddAlertIDs(ids ...int) *MachineUpdate {
mu.mutation.AddAlertIDs(ids...)
@ -278,11 +319,7 @@ func (mu *MachineUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (mu *MachineUpdate) defaults() {
if _, ok := mu.mutation.CreatedAt(); !ok && !mu.mutation.CreatedAtCleared() {
v := machine.UpdateDefaultCreatedAt()
mu.mutation.SetCreatedAt(v)
}
if _, ok := mu.mutation.UpdatedAt(); !ok && !mu.mutation.UpdatedAtCleared() {
if _, ok := mu.mutation.UpdatedAt(); !ok {
v := machine.UpdateDefaultUpdatedAt()
mu.mutation.SetUpdatedAt(v)
}
@ -318,18 +355,9 @@ func (mu *MachineUpdate) sqlSave(ctx context.Context) (n int, err error) {
}
}
}
if value, ok := mu.mutation.CreatedAt(); ok {
_spec.SetField(machine.FieldCreatedAt, field.TypeTime, value)
}
if mu.mutation.CreatedAtCleared() {
_spec.ClearField(machine.FieldCreatedAt, field.TypeTime)
}
if value, ok := mu.mutation.UpdatedAt(); ok {
_spec.SetField(machine.FieldUpdatedAt, field.TypeTime, value)
}
if mu.mutation.UpdatedAtCleared() {
_spec.ClearField(machine.FieldUpdatedAt, field.TypeTime)
}
if value, ok := mu.mutation.LastPush(); ok {
_spec.SetField(machine.FieldLastPush, field.TypeTime, value)
}
@ -342,9 +370,6 @@ func (mu *MachineUpdate) sqlSave(ctx context.Context) (n int, err error) {
if mu.mutation.LastHeartbeatCleared() {
_spec.ClearField(machine.FieldLastHeartbeat, field.TypeTime)
}
if value, ok := mu.mutation.MachineId(); ok {
_spec.SetField(machine.FieldMachineId, field.TypeString, value)
}
if value, ok := mu.mutation.Password(); ok {
_spec.SetField(machine.FieldPassword, field.TypeString, value)
}
@ -375,6 +400,30 @@ func (mu *MachineUpdate) sqlSave(ctx context.Context) (n int, err error) {
if value, ok := mu.mutation.AuthType(); ok {
_spec.SetField(machine.FieldAuthType, field.TypeString, value)
}
if value, ok := mu.mutation.Osname(); ok {
_spec.SetField(machine.FieldOsname, field.TypeString, value)
}
if mu.mutation.OsnameCleared() {
_spec.ClearField(machine.FieldOsname, field.TypeString)
}
if value, ok := mu.mutation.Osversion(); ok {
_spec.SetField(machine.FieldOsversion, field.TypeString, value)
}
if mu.mutation.OsversionCleared() {
_spec.ClearField(machine.FieldOsversion, field.TypeString)
}
if value, ok := mu.mutation.Featureflags(); ok {
_spec.SetField(machine.FieldFeatureflags, field.TypeString, value)
}
if mu.mutation.FeatureflagsCleared() {
_spec.ClearField(machine.FieldFeatureflags, field.TypeString)
}
if value, ok := mu.mutation.Hubstate(); ok {
_spec.SetField(machine.FieldHubstate, field.TypeJSON, value)
}
if mu.mutation.HubstateCleared() {
_spec.ClearField(machine.FieldHubstate, field.TypeJSON)
}
if mu.mutation.AlertsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,
@ -440,30 +489,12 @@ type MachineUpdateOne struct {
mutation *MachineMutation
}
// SetCreatedAt sets the "created_at" field.
func (muo *MachineUpdateOne) SetCreatedAt(t time.Time) *MachineUpdateOne {
muo.mutation.SetCreatedAt(t)
return muo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (muo *MachineUpdateOne) ClearCreatedAt() *MachineUpdateOne {
muo.mutation.ClearCreatedAt()
return muo
}
// SetUpdatedAt sets the "updated_at" field.
func (muo *MachineUpdateOne) SetUpdatedAt(t time.Time) *MachineUpdateOne {
muo.mutation.SetUpdatedAt(t)
return muo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (muo *MachineUpdateOne) ClearUpdatedAt() *MachineUpdateOne {
muo.mutation.ClearUpdatedAt()
return muo
}
// SetLastPush sets the "last_push" field.
func (muo *MachineUpdateOne) SetLastPush(t time.Time) *MachineUpdateOne {
muo.mutation.SetLastPush(t)
@ -488,20 +519,6 @@ func (muo *MachineUpdateOne) ClearLastHeartbeat() *MachineUpdateOne {
return muo
}
// SetMachineId sets the "machineId" field.
func (muo *MachineUpdateOne) SetMachineId(s string) *MachineUpdateOne {
muo.mutation.SetMachineId(s)
return muo
}
// SetNillableMachineId sets the "machineId" field if the given value is not nil.
func (muo *MachineUpdateOne) SetNillableMachineId(s *string) *MachineUpdateOne {
if s != nil {
muo.SetMachineId(*s)
}
return muo
}
// SetPassword sets the "password" field.
func (muo *MachineUpdateOne) SetPassword(s string) *MachineUpdateOne {
muo.mutation.SetPassword(s)
@ -618,6 +635,78 @@ func (muo *MachineUpdateOne) SetNillableAuthType(s *string) *MachineUpdateOne {
return muo
}
// SetOsname sets the "osname" field.
func (muo *MachineUpdateOne) SetOsname(s string) *MachineUpdateOne {
muo.mutation.SetOsname(s)
return muo
}
// SetNillableOsname sets the "osname" field if the given value is not nil.
func (muo *MachineUpdateOne) SetNillableOsname(s *string) *MachineUpdateOne {
if s != nil {
muo.SetOsname(*s)
}
return muo
}
// ClearOsname clears the value of the "osname" field.
func (muo *MachineUpdateOne) ClearOsname() *MachineUpdateOne {
muo.mutation.ClearOsname()
return muo
}
// SetOsversion sets the "osversion" field.
func (muo *MachineUpdateOne) SetOsversion(s string) *MachineUpdateOne {
muo.mutation.SetOsversion(s)
return muo
}
// SetNillableOsversion sets the "osversion" field if the given value is not nil.
func (muo *MachineUpdateOne) SetNillableOsversion(s *string) *MachineUpdateOne {
if s != nil {
muo.SetOsversion(*s)
}
return muo
}
// ClearOsversion clears the value of the "osversion" field.
func (muo *MachineUpdateOne) ClearOsversion() *MachineUpdateOne {
muo.mutation.ClearOsversion()
return muo
}
// SetFeatureflags sets the "featureflags" field.
func (muo *MachineUpdateOne) SetFeatureflags(s string) *MachineUpdateOne {
muo.mutation.SetFeatureflags(s)
return muo
}
// SetNillableFeatureflags sets the "featureflags" field if the given value is not nil.
func (muo *MachineUpdateOne) SetNillableFeatureflags(s *string) *MachineUpdateOne {
if s != nil {
muo.SetFeatureflags(*s)
}
return muo
}
// ClearFeatureflags clears the value of the "featureflags" field.
func (muo *MachineUpdateOne) ClearFeatureflags() *MachineUpdateOne {
muo.mutation.ClearFeatureflags()
return muo
}
// SetHubstate sets the "hubstate" field.
func (muo *MachineUpdateOne) SetHubstate(mi *models.HubItems) *MachineUpdateOne {
muo.mutation.SetHubstate(mi)
return muo
}
// ClearHubstate clears the value of the "hubstate" field.
func (muo *MachineUpdateOne) ClearHubstate() *MachineUpdateOne {
muo.mutation.ClearHubstate()
return muo
}
// AddAlertIDs adds the "alerts" edge to the Alert entity by IDs.
func (muo *MachineUpdateOne) AddAlertIDs(ids ...int) *MachineUpdateOne {
muo.mutation.AddAlertIDs(ids...)
@ -702,11 +791,7 @@ func (muo *MachineUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (muo *MachineUpdateOne) defaults() {
if _, ok := muo.mutation.CreatedAt(); !ok && !muo.mutation.CreatedAtCleared() {
v := machine.UpdateDefaultCreatedAt()
muo.mutation.SetCreatedAt(v)
}
if _, ok := muo.mutation.UpdatedAt(); !ok && !muo.mutation.UpdatedAtCleared() {
if _, ok := muo.mutation.UpdatedAt(); !ok {
v := machine.UpdateDefaultUpdatedAt()
muo.mutation.SetUpdatedAt(v)
}
@ -759,18 +844,9 @@ func (muo *MachineUpdateOne) sqlSave(ctx context.Context) (_node *Machine, err e
}
}
}
if value, ok := muo.mutation.CreatedAt(); ok {
_spec.SetField(machine.FieldCreatedAt, field.TypeTime, value)
}
if muo.mutation.CreatedAtCleared() {
_spec.ClearField(machine.FieldCreatedAt, field.TypeTime)
}
if value, ok := muo.mutation.UpdatedAt(); ok {
_spec.SetField(machine.FieldUpdatedAt, field.TypeTime, value)
}
if muo.mutation.UpdatedAtCleared() {
_spec.ClearField(machine.FieldUpdatedAt, field.TypeTime)
}
if value, ok := muo.mutation.LastPush(); ok {
_spec.SetField(machine.FieldLastPush, field.TypeTime, value)
}
@ -783,9 +859,6 @@ func (muo *MachineUpdateOne) sqlSave(ctx context.Context) (_node *Machine, err e
if muo.mutation.LastHeartbeatCleared() {
_spec.ClearField(machine.FieldLastHeartbeat, field.TypeTime)
}
if value, ok := muo.mutation.MachineId(); ok {
_spec.SetField(machine.FieldMachineId, field.TypeString, value)
}
if value, ok := muo.mutation.Password(); ok {
_spec.SetField(machine.FieldPassword, field.TypeString, value)
}
@ -816,6 +889,30 @@ func (muo *MachineUpdateOne) sqlSave(ctx context.Context) (_node *Machine, err e
if value, ok := muo.mutation.AuthType(); ok {
_spec.SetField(machine.FieldAuthType, field.TypeString, value)
}
if value, ok := muo.mutation.Osname(); ok {
_spec.SetField(machine.FieldOsname, field.TypeString, value)
}
if muo.mutation.OsnameCleared() {
_spec.ClearField(machine.FieldOsname, field.TypeString)
}
if value, ok := muo.mutation.Osversion(); ok {
_spec.SetField(machine.FieldOsversion, field.TypeString, value)
}
if muo.mutation.OsversionCleared() {
_spec.ClearField(machine.FieldOsversion, field.TypeString)
}
if value, ok := muo.mutation.Featureflags(); ok {
_spec.SetField(machine.FieldFeatureflags, field.TypeString, value)
}
if muo.mutation.FeatureflagsCleared() {
_spec.ClearField(machine.FieldFeatureflags, field.TypeString)
}
if value, ok := muo.mutation.Hubstate(); ok {
_spec.SetField(machine.FieldHubstate, field.TypeJSON, value)
}
if muo.mutation.HubstateCleared() {
_spec.ClearField(machine.FieldHubstate, field.TypeJSON)
}
if muo.mutation.AlertsCleared() {
edge := &sqlgraph.EdgeSpec{
Rel: sqlgraph.O2M,

View file

@ -19,9 +19,9 @@ type Meta struct {
// ID of the ent.
ID int `json:"id,omitempty"`
// CreatedAt holds the value of the "created_at" field.
CreatedAt *time.Time `json:"created_at,omitempty"`
CreatedAt time.Time `json:"created_at,omitempty"`
// UpdatedAt holds the value of the "updated_at" field.
UpdatedAt *time.Time `json:"updated_at,omitempty"`
UpdatedAt time.Time `json:"updated_at,omitempty"`
// Key holds the value of the "key" field.
Key string `json:"key,omitempty"`
// Value holds the value of the "value" field.
@ -92,15 +92,13 @@ func (m *Meta) assignValues(columns []string, values []any) error {
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field created_at", values[i])
} else if value.Valid {
m.CreatedAt = new(time.Time)
*m.CreatedAt = value.Time
m.CreatedAt = value.Time
}
case meta.FieldUpdatedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field updated_at", values[i])
} else if value.Valid {
m.UpdatedAt = new(time.Time)
*m.UpdatedAt = value.Time
m.UpdatedAt = value.Time
}
case meta.FieldKey:
if value, ok := values[i].(*sql.NullString); !ok {
@ -161,15 +159,11 @@ func (m *Meta) String() string {
var builder strings.Builder
builder.WriteString("Meta(")
builder.WriteString(fmt.Sprintf("id=%v, ", m.ID))
if v := m.CreatedAt; v != nil {
builder.WriteString("created_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("created_at=")
builder.WriteString(m.CreatedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := m.UpdatedAt; v != nil {
builder.WriteString("updated_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString("updated_at=")
builder.WriteString(m.UpdatedAt.Format(time.ANSIC))
builder.WriteString(", ")
builder.WriteString("key=")
builder.WriteString(m.Key)

View file

@ -60,8 +60,6 @@ func ValidColumn(column string) bool {
var (
// DefaultCreatedAt holds the default value on creation for the "created_at" field.
DefaultCreatedAt func() time.Time
// UpdateDefaultCreatedAt holds the default value on update for the "created_at" field.
UpdateDefaultCreatedAt func() time.Time
// DefaultUpdatedAt holds the default value on creation for the "updated_at" field.
DefaultUpdatedAt func() time.Time
// UpdateDefaultUpdatedAt holds the default value on update for the "updated_at" field.

View file

@ -120,16 +120,6 @@ func CreatedAtLTE(v time.Time) predicate.Meta {
return predicate.Meta(sql.FieldLTE(FieldCreatedAt, v))
}
// CreatedAtIsNil applies the IsNil predicate on the "created_at" field.
func CreatedAtIsNil() predicate.Meta {
return predicate.Meta(sql.FieldIsNull(FieldCreatedAt))
}
// CreatedAtNotNil applies the NotNil predicate on the "created_at" field.
func CreatedAtNotNil() predicate.Meta {
return predicate.Meta(sql.FieldNotNull(FieldCreatedAt))
}
// UpdatedAtEQ applies the EQ predicate on the "updated_at" field.
func UpdatedAtEQ(v time.Time) predicate.Meta {
return predicate.Meta(sql.FieldEQ(FieldUpdatedAt, v))
@ -170,16 +160,6 @@ func UpdatedAtLTE(v time.Time) predicate.Meta {
return predicate.Meta(sql.FieldLTE(FieldUpdatedAt, v))
}
// UpdatedAtIsNil applies the IsNil predicate on the "updated_at" field.
func UpdatedAtIsNil() predicate.Meta {
return predicate.Meta(sql.FieldIsNull(FieldUpdatedAt))
}
// UpdatedAtNotNil applies the NotNil predicate on the "updated_at" field.
func UpdatedAtNotNil() predicate.Meta {
return predicate.Meta(sql.FieldNotNull(FieldUpdatedAt))
}
// KeyEQ applies the EQ predicate on the "key" field.
func KeyEQ(v string) predicate.Meta {
return predicate.Meta(sql.FieldEQ(FieldKey, v))

View file

@ -141,6 +141,12 @@ func (mc *MetaCreate) defaults() {
// check runs all checks and user-defined validators on the builder.
func (mc *MetaCreate) check() error {
if _, ok := mc.mutation.CreatedAt(); !ok {
return &ValidationError{Name: "created_at", err: errors.New(`ent: missing required field "Meta.created_at"`)}
}
if _, ok := mc.mutation.UpdatedAt(); !ok {
return &ValidationError{Name: "updated_at", err: errors.New(`ent: missing required field "Meta.updated_at"`)}
}
if _, ok := mc.mutation.Key(); !ok {
return &ValidationError{Name: "key", err: errors.New(`ent: missing required field "Meta.key"`)}
}
@ -180,11 +186,11 @@ func (mc *MetaCreate) createSpec() (*Meta, *sqlgraph.CreateSpec) {
)
if value, ok := mc.mutation.CreatedAt(); ok {
_spec.SetField(meta.FieldCreatedAt, field.TypeTime, value)
_node.CreatedAt = &value
_node.CreatedAt = value
}
if value, ok := mc.mutation.UpdatedAt(); ok {
_spec.SetField(meta.FieldUpdatedAt, field.TypeTime, value)
_node.UpdatedAt = &value
_node.UpdatedAt = value
}
if value, ok := mc.mutation.Key(); ok {
_spec.SetField(meta.FieldKey, field.TypeString, value)

View file

@ -35,9 +35,11 @@ func (mu *MetaUpdate) SetCreatedAt(t time.Time) *MetaUpdate {
return mu
}
// ClearCreatedAt clears the value of the "created_at" field.
func (mu *MetaUpdate) ClearCreatedAt() *MetaUpdate {
mu.mutation.ClearCreatedAt()
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (mu *MetaUpdate) SetNillableCreatedAt(t *time.Time) *MetaUpdate {
if t != nil {
mu.SetCreatedAt(*t)
}
return mu
}
@ -47,12 +49,6 @@ func (mu *MetaUpdate) SetUpdatedAt(t time.Time) *MetaUpdate {
return mu
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (mu *MetaUpdate) ClearUpdatedAt() *MetaUpdate {
mu.mutation.ClearUpdatedAt()
return mu
}
// SetKey sets the "key" field.
func (mu *MetaUpdate) SetKey(s string) *MetaUpdate {
mu.mutation.SetKey(s)
@ -161,11 +157,7 @@ func (mu *MetaUpdate) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (mu *MetaUpdate) defaults() {
if _, ok := mu.mutation.CreatedAt(); !ok && !mu.mutation.CreatedAtCleared() {
v := meta.UpdateDefaultCreatedAt()
mu.mutation.SetCreatedAt(v)
}
if _, ok := mu.mutation.UpdatedAt(); !ok && !mu.mutation.UpdatedAtCleared() {
if _, ok := mu.mutation.UpdatedAt(); !ok {
v := meta.UpdateDefaultUpdatedAt()
mu.mutation.SetUpdatedAt(v)
}
@ -196,15 +188,9 @@ func (mu *MetaUpdate) sqlSave(ctx context.Context) (n int, err error) {
if value, ok := mu.mutation.CreatedAt(); ok {
_spec.SetField(meta.FieldCreatedAt, field.TypeTime, value)
}
if mu.mutation.CreatedAtCleared() {
_spec.ClearField(meta.FieldCreatedAt, field.TypeTime)
}
if value, ok := mu.mutation.UpdatedAt(); ok {
_spec.SetField(meta.FieldUpdatedAt, field.TypeTime, value)
}
if mu.mutation.UpdatedAtCleared() {
_spec.ClearField(meta.FieldUpdatedAt, field.TypeTime)
}
if value, ok := mu.mutation.Key(); ok {
_spec.SetField(meta.FieldKey, field.TypeString, value)
}
@ -266,9 +252,11 @@ func (muo *MetaUpdateOne) SetCreatedAt(t time.Time) *MetaUpdateOne {
return muo
}
// ClearCreatedAt clears the value of the "created_at" field.
func (muo *MetaUpdateOne) ClearCreatedAt() *MetaUpdateOne {
muo.mutation.ClearCreatedAt()
// SetNillableCreatedAt sets the "created_at" field if the given value is not nil.
func (muo *MetaUpdateOne) SetNillableCreatedAt(t *time.Time) *MetaUpdateOne {
if t != nil {
muo.SetCreatedAt(*t)
}
return muo
}
@ -278,12 +266,6 @@ func (muo *MetaUpdateOne) SetUpdatedAt(t time.Time) *MetaUpdateOne {
return muo
}
// ClearUpdatedAt clears the value of the "updated_at" field.
func (muo *MetaUpdateOne) ClearUpdatedAt() *MetaUpdateOne {
muo.mutation.ClearUpdatedAt()
return muo
}
// SetKey sets the "key" field.
func (muo *MetaUpdateOne) SetKey(s string) *MetaUpdateOne {
muo.mutation.SetKey(s)
@ -405,11 +387,7 @@ func (muo *MetaUpdateOne) ExecX(ctx context.Context) {
// defaults sets the default values of the builder before save.
func (muo *MetaUpdateOne) defaults() {
if _, ok := muo.mutation.CreatedAt(); !ok && !muo.mutation.CreatedAtCleared() {
v := meta.UpdateDefaultCreatedAt()
muo.mutation.SetCreatedAt(v)
}
if _, ok := muo.mutation.UpdatedAt(); !ok && !muo.mutation.UpdatedAtCleared() {
if _, ok := muo.mutation.UpdatedAt(); !ok {
v := meta.UpdateDefaultUpdatedAt()
muo.mutation.SetUpdatedAt(v)
}
@ -457,15 +435,9 @@ func (muo *MetaUpdateOne) sqlSave(ctx context.Context) (_node *Meta, err error)
if value, ok := muo.mutation.CreatedAt(); ok {
_spec.SetField(meta.FieldCreatedAt, field.TypeTime, value)
}
if muo.mutation.CreatedAtCleared() {
_spec.ClearField(meta.FieldCreatedAt, field.TypeTime)
}
if value, ok := muo.mutation.UpdatedAt(); ok {
_spec.SetField(meta.FieldUpdatedAt, field.TypeTime, value)
}
if muo.mutation.UpdatedAtCleared() {
_spec.ClearField(meta.FieldUpdatedAt, field.TypeTime)
}
if value, ok := muo.mutation.Key(); ok {
_spec.SetField(meta.FieldKey, field.TypeString, value)
}

154
pkg/database/ent/metric.go Normal file
View file

@ -0,0 +1,154 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"fmt"
"strings"
"time"
"entgo.io/ent"
"entgo.io/ent/dialect/sql"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
)
// Metric is the model entity for the Metric schema.
type Metric struct {
config `json:"-"`
// ID of the ent.
ID int `json:"id,omitempty"`
// Type of the metrics source: LP=logprocessor, RC=remediation
GeneratedType metric.GeneratedType `json:"generated_type,omitempty"`
// Source of the metrics: machine id, bouncer name...
// It must come from the auth middleware.
GeneratedBy string `json:"generated_by,omitempty"`
// When the metrics are collected/calculated at the source
CollectedAt time.Time `json:"collected_at,omitempty"`
// When the metrics are sent to the console
PushedAt *time.Time `json:"pushed_at,omitempty"`
// The actual metrics (item0)
Payload string `json:"payload,omitempty"`
selectValues sql.SelectValues
}
// scanValues returns the types for scanning values from sql.Rows.
func (*Metric) scanValues(columns []string) ([]any, error) {
values := make([]any, len(columns))
for i := range columns {
switch columns[i] {
case metric.FieldID:
values[i] = new(sql.NullInt64)
case metric.FieldGeneratedType, metric.FieldGeneratedBy, metric.FieldPayload:
values[i] = new(sql.NullString)
case metric.FieldCollectedAt, metric.FieldPushedAt:
values[i] = new(sql.NullTime)
default:
values[i] = new(sql.UnknownType)
}
}
return values, nil
}
// assignValues assigns the values that were returned from sql.Rows (after scanning)
// to the Metric fields.
func (m *Metric) assignValues(columns []string, values []any) error {
if m, n := len(values), len(columns); m < n {
return fmt.Errorf("mismatch number of scan values: %d != %d", m, n)
}
for i := range columns {
switch columns[i] {
case metric.FieldID:
value, ok := values[i].(*sql.NullInt64)
if !ok {
return fmt.Errorf("unexpected type %T for field id", value)
}
m.ID = int(value.Int64)
case metric.FieldGeneratedType:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field generated_type", values[i])
} else if value.Valid {
m.GeneratedType = metric.GeneratedType(value.String)
}
case metric.FieldGeneratedBy:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field generated_by", values[i])
} else if value.Valid {
m.GeneratedBy = value.String
}
case metric.FieldCollectedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field collected_at", values[i])
} else if value.Valid {
m.CollectedAt = value.Time
}
case metric.FieldPushedAt:
if value, ok := values[i].(*sql.NullTime); !ok {
return fmt.Errorf("unexpected type %T for field pushed_at", values[i])
} else if value.Valid {
m.PushedAt = new(time.Time)
*m.PushedAt = value.Time
}
case metric.FieldPayload:
if value, ok := values[i].(*sql.NullString); !ok {
return fmt.Errorf("unexpected type %T for field payload", values[i])
} else if value.Valid {
m.Payload = value.String
}
default:
m.selectValues.Set(columns[i], values[i])
}
}
return nil
}
// Value returns the ent.Value that was dynamically selected and assigned to the Metric.
// This includes values selected through modifiers, order, etc.
func (m *Metric) Value(name string) (ent.Value, error) {
return m.selectValues.Get(name)
}
// Update returns a builder for updating this Metric.
// Note that you need to call Metric.Unwrap() before calling this method if this Metric
// was returned from a transaction, and the transaction was committed or rolled back.
func (m *Metric) Update() *MetricUpdateOne {
return NewMetricClient(m.config).UpdateOne(m)
}
// Unwrap unwraps the Metric entity that was returned from a transaction after it was closed,
// so that all future queries will be executed through the driver which created the transaction.
func (m *Metric) Unwrap() *Metric {
_tx, ok := m.config.driver.(*txDriver)
if !ok {
panic("ent: Metric is not a transactional entity")
}
m.config.driver = _tx.drv
return m
}
// String implements the fmt.Stringer.
func (m *Metric) String() string {
var builder strings.Builder
builder.WriteString("Metric(")
builder.WriteString(fmt.Sprintf("id=%v, ", m.ID))
builder.WriteString("generated_type=")
builder.WriteString(fmt.Sprintf("%v", m.GeneratedType))
builder.WriteString(", ")
builder.WriteString("generated_by=")
builder.WriteString(m.GeneratedBy)
builder.WriteString(", ")
builder.WriteString("collected_at=")
builder.WriteString(m.CollectedAt.Format(time.ANSIC))
builder.WriteString(", ")
if v := m.PushedAt; v != nil {
builder.WriteString("pushed_at=")
builder.WriteString(v.Format(time.ANSIC))
}
builder.WriteString(", ")
builder.WriteString("payload=")
builder.WriteString(m.Payload)
builder.WriteByte(')')
return builder.String()
}
// Metrics is a parsable slice of Metric.
type Metrics []*Metric

View file

@ -0,0 +1,104 @@
// Code generated by ent, DO NOT EDIT.
package metric
import (
"fmt"
"entgo.io/ent/dialect/sql"
)
const (
// Label holds the string label denoting the metric type in the database.
Label = "metric"
// FieldID holds the string denoting the id field in the database.
FieldID = "id"
// FieldGeneratedType holds the string denoting the generated_type field in the database.
FieldGeneratedType = "generated_type"
// FieldGeneratedBy holds the string denoting the generated_by field in the database.
FieldGeneratedBy = "generated_by"
// FieldCollectedAt holds the string denoting the collected_at field in the database.
FieldCollectedAt = "collected_at"
// FieldPushedAt holds the string denoting the pushed_at field in the database.
FieldPushedAt = "pushed_at"
// FieldPayload holds the string denoting the payload field in the database.
FieldPayload = "payload"
// Table holds the table name of the metric in the database.
Table = "metrics"
)
// Columns holds all SQL columns for metric fields.
var Columns = []string{
FieldID,
FieldGeneratedType,
FieldGeneratedBy,
FieldCollectedAt,
FieldPushedAt,
FieldPayload,
}
// ValidColumn reports if the column name is valid (part of the table columns).
func ValidColumn(column string) bool {
for i := range Columns {
if column == Columns[i] {
return true
}
}
return false
}
// GeneratedType defines the type for the "generated_type" enum field.
type GeneratedType string
// GeneratedType values.
const (
GeneratedTypeLP GeneratedType = "LP"
GeneratedTypeRC GeneratedType = "RC"
)
func (gt GeneratedType) String() string {
return string(gt)
}
// GeneratedTypeValidator is a validator for the "generated_type" field enum values. It is called by the builders before save.
func GeneratedTypeValidator(gt GeneratedType) error {
switch gt {
case GeneratedTypeLP, GeneratedTypeRC:
return nil
default:
return fmt.Errorf("metric: invalid enum value for generated_type field: %q", gt)
}
}
// OrderOption defines the ordering options for the Metric queries.
type OrderOption func(*sql.Selector)
// ByID orders the results by the id field.
func ByID(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldID, opts...).ToFunc()
}
// ByGeneratedType orders the results by the generated_type field.
func ByGeneratedType(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGeneratedType, opts...).ToFunc()
}
// ByGeneratedBy orders the results by the generated_by field.
func ByGeneratedBy(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldGeneratedBy, opts...).ToFunc()
}
// ByCollectedAt orders the results by the collected_at field.
func ByCollectedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldCollectedAt, opts...).ToFunc()
}
// ByPushedAt orders the results by the pushed_at field.
func ByPushedAt(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPushedAt, opts...).ToFunc()
}
// ByPayload orders the results by the payload field.
func ByPayload(opts ...sql.OrderTermOption) OrderOption {
return sql.OrderByField(FieldPayload, opts...).ToFunc()
}

View file

@ -0,0 +1,330 @@
// Code generated by ent, DO NOT EDIT.
package metric
import (
"time"
"entgo.io/ent/dialect/sql"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
)
// ID filters vertices based on their ID field.
func ID(id int) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldID, id))
}
// IDEQ applies the EQ predicate on the ID field.
func IDEQ(id int) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldID, id))
}
// IDNEQ applies the NEQ predicate on the ID field.
func IDNEQ(id int) predicate.Metric {
return predicate.Metric(sql.FieldNEQ(FieldID, id))
}
// IDIn applies the In predicate on the ID field.
func IDIn(ids ...int) predicate.Metric {
return predicate.Metric(sql.FieldIn(FieldID, ids...))
}
// IDNotIn applies the NotIn predicate on the ID field.
func IDNotIn(ids ...int) predicate.Metric {
return predicate.Metric(sql.FieldNotIn(FieldID, ids...))
}
// IDGT applies the GT predicate on the ID field.
func IDGT(id int) predicate.Metric {
return predicate.Metric(sql.FieldGT(FieldID, id))
}
// IDGTE applies the GTE predicate on the ID field.
func IDGTE(id int) predicate.Metric {
return predicate.Metric(sql.FieldGTE(FieldID, id))
}
// IDLT applies the LT predicate on the ID field.
func IDLT(id int) predicate.Metric {
return predicate.Metric(sql.FieldLT(FieldID, id))
}
// IDLTE applies the LTE predicate on the ID field.
func IDLTE(id int) predicate.Metric {
return predicate.Metric(sql.FieldLTE(FieldID, id))
}
// GeneratedBy applies equality check predicate on the "generated_by" field. It's identical to GeneratedByEQ.
func GeneratedBy(v string) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldGeneratedBy, v))
}
// CollectedAt applies equality check predicate on the "collected_at" field. It's identical to CollectedAtEQ.
func CollectedAt(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldCollectedAt, v))
}
// PushedAt applies equality check predicate on the "pushed_at" field. It's identical to PushedAtEQ.
func PushedAt(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldPushedAt, v))
}
// Payload applies equality check predicate on the "payload" field. It's identical to PayloadEQ.
func Payload(v string) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldPayload, v))
}
// GeneratedTypeEQ applies the EQ predicate on the "generated_type" field.
func GeneratedTypeEQ(v GeneratedType) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldGeneratedType, v))
}
// GeneratedTypeNEQ applies the NEQ predicate on the "generated_type" field.
func GeneratedTypeNEQ(v GeneratedType) predicate.Metric {
return predicate.Metric(sql.FieldNEQ(FieldGeneratedType, v))
}
// GeneratedTypeIn applies the In predicate on the "generated_type" field.
func GeneratedTypeIn(vs ...GeneratedType) predicate.Metric {
return predicate.Metric(sql.FieldIn(FieldGeneratedType, vs...))
}
// GeneratedTypeNotIn applies the NotIn predicate on the "generated_type" field.
func GeneratedTypeNotIn(vs ...GeneratedType) predicate.Metric {
return predicate.Metric(sql.FieldNotIn(FieldGeneratedType, vs...))
}
// GeneratedByEQ applies the EQ predicate on the "generated_by" field.
func GeneratedByEQ(v string) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldGeneratedBy, v))
}
// GeneratedByNEQ applies the NEQ predicate on the "generated_by" field.
func GeneratedByNEQ(v string) predicate.Metric {
return predicate.Metric(sql.FieldNEQ(FieldGeneratedBy, v))
}
// GeneratedByIn applies the In predicate on the "generated_by" field.
func GeneratedByIn(vs ...string) predicate.Metric {
return predicate.Metric(sql.FieldIn(FieldGeneratedBy, vs...))
}
// GeneratedByNotIn applies the NotIn predicate on the "generated_by" field.
func GeneratedByNotIn(vs ...string) predicate.Metric {
return predicate.Metric(sql.FieldNotIn(FieldGeneratedBy, vs...))
}
// GeneratedByGT applies the GT predicate on the "generated_by" field.
func GeneratedByGT(v string) predicate.Metric {
return predicate.Metric(sql.FieldGT(FieldGeneratedBy, v))
}
// GeneratedByGTE applies the GTE predicate on the "generated_by" field.
func GeneratedByGTE(v string) predicate.Metric {
return predicate.Metric(sql.FieldGTE(FieldGeneratedBy, v))
}
// GeneratedByLT applies the LT predicate on the "generated_by" field.
func GeneratedByLT(v string) predicate.Metric {
return predicate.Metric(sql.FieldLT(FieldGeneratedBy, v))
}
// GeneratedByLTE applies the LTE predicate on the "generated_by" field.
func GeneratedByLTE(v string) predicate.Metric {
return predicate.Metric(sql.FieldLTE(FieldGeneratedBy, v))
}
// GeneratedByContains applies the Contains predicate on the "generated_by" field.
func GeneratedByContains(v string) predicate.Metric {
return predicate.Metric(sql.FieldContains(FieldGeneratedBy, v))
}
// GeneratedByHasPrefix applies the HasPrefix predicate on the "generated_by" field.
func GeneratedByHasPrefix(v string) predicate.Metric {
return predicate.Metric(sql.FieldHasPrefix(FieldGeneratedBy, v))
}
// GeneratedByHasSuffix applies the HasSuffix predicate on the "generated_by" field.
func GeneratedByHasSuffix(v string) predicate.Metric {
return predicate.Metric(sql.FieldHasSuffix(FieldGeneratedBy, v))
}
// GeneratedByEqualFold applies the EqualFold predicate on the "generated_by" field.
func GeneratedByEqualFold(v string) predicate.Metric {
return predicate.Metric(sql.FieldEqualFold(FieldGeneratedBy, v))
}
// GeneratedByContainsFold applies the ContainsFold predicate on the "generated_by" field.
func GeneratedByContainsFold(v string) predicate.Metric {
return predicate.Metric(sql.FieldContainsFold(FieldGeneratedBy, v))
}
// CollectedAtEQ applies the EQ predicate on the "collected_at" field.
func CollectedAtEQ(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldCollectedAt, v))
}
// CollectedAtNEQ applies the NEQ predicate on the "collected_at" field.
func CollectedAtNEQ(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldNEQ(FieldCollectedAt, v))
}
// CollectedAtIn applies the In predicate on the "collected_at" field.
func CollectedAtIn(vs ...time.Time) predicate.Metric {
return predicate.Metric(sql.FieldIn(FieldCollectedAt, vs...))
}
// CollectedAtNotIn applies the NotIn predicate on the "collected_at" field.
func CollectedAtNotIn(vs ...time.Time) predicate.Metric {
return predicate.Metric(sql.FieldNotIn(FieldCollectedAt, vs...))
}
// CollectedAtGT applies the GT predicate on the "collected_at" field.
func CollectedAtGT(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldGT(FieldCollectedAt, v))
}
// CollectedAtGTE applies the GTE predicate on the "collected_at" field.
func CollectedAtGTE(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldGTE(FieldCollectedAt, v))
}
// CollectedAtLT applies the LT predicate on the "collected_at" field.
func CollectedAtLT(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldLT(FieldCollectedAt, v))
}
// CollectedAtLTE applies the LTE predicate on the "collected_at" field.
func CollectedAtLTE(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldLTE(FieldCollectedAt, v))
}
// PushedAtEQ applies the EQ predicate on the "pushed_at" field.
func PushedAtEQ(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldPushedAt, v))
}
// PushedAtNEQ applies the NEQ predicate on the "pushed_at" field.
func PushedAtNEQ(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldNEQ(FieldPushedAt, v))
}
// PushedAtIn applies the In predicate on the "pushed_at" field.
func PushedAtIn(vs ...time.Time) predicate.Metric {
return predicate.Metric(sql.FieldIn(FieldPushedAt, vs...))
}
// PushedAtNotIn applies the NotIn predicate on the "pushed_at" field.
func PushedAtNotIn(vs ...time.Time) predicate.Metric {
return predicate.Metric(sql.FieldNotIn(FieldPushedAt, vs...))
}
// PushedAtGT applies the GT predicate on the "pushed_at" field.
func PushedAtGT(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldGT(FieldPushedAt, v))
}
// PushedAtGTE applies the GTE predicate on the "pushed_at" field.
func PushedAtGTE(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldGTE(FieldPushedAt, v))
}
// PushedAtLT applies the LT predicate on the "pushed_at" field.
func PushedAtLT(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldLT(FieldPushedAt, v))
}
// PushedAtLTE applies the LTE predicate on the "pushed_at" field.
func PushedAtLTE(v time.Time) predicate.Metric {
return predicate.Metric(sql.FieldLTE(FieldPushedAt, v))
}
// PushedAtIsNil applies the IsNil predicate on the "pushed_at" field.
func PushedAtIsNil() predicate.Metric {
return predicate.Metric(sql.FieldIsNull(FieldPushedAt))
}
// PushedAtNotNil applies the NotNil predicate on the "pushed_at" field.
func PushedAtNotNil() predicate.Metric {
return predicate.Metric(sql.FieldNotNull(FieldPushedAt))
}
// PayloadEQ applies the EQ predicate on the "payload" field.
func PayloadEQ(v string) predicate.Metric {
return predicate.Metric(sql.FieldEQ(FieldPayload, v))
}
// PayloadNEQ applies the NEQ predicate on the "payload" field.
func PayloadNEQ(v string) predicate.Metric {
return predicate.Metric(sql.FieldNEQ(FieldPayload, v))
}
// PayloadIn applies the In predicate on the "payload" field.
func PayloadIn(vs ...string) predicate.Metric {
return predicate.Metric(sql.FieldIn(FieldPayload, vs...))
}
// PayloadNotIn applies the NotIn predicate on the "payload" field.
func PayloadNotIn(vs ...string) predicate.Metric {
return predicate.Metric(sql.FieldNotIn(FieldPayload, vs...))
}
// PayloadGT applies the GT predicate on the "payload" field.
func PayloadGT(v string) predicate.Metric {
return predicate.Metric(sql.FieldGT(FieldPayload, v))
}
// PayloadGTE applies the GTE predicate on the "payload" field.
func PayloadGTE(v string) predicate.Metric {
return predicate.Metric(sql.FieldGTE(FieldPayload, v))
}
// PayloadLT applies the LT predicate on the "payload" field.
func PayloadLT(v string) predicate.Metric {
return predicate.Metric(sql.FieldLT(FieldPayload, v))
}
// PayloadLTE applies the LTE predicate on the "payload" field.
func PayloadLTE(v string) predicate.Metric {
return predicate.Metric(sql.FieldLTE(FieldPayload, v))
}
// PayloadContains applies the Contains predicate on the "payload" field.
func PayloadContains(v string) predicate.Metric {
return predicate.Metric(sql.FieldContains(FieldPayload, v))
}
// PayloadHasPrefix applies the HasPrefix predicate on the "payload" field.
func PayloadHasPrefix(v string) predicate.Metric {
return predicate.Metric(sql.FieldHasPrefix(FieldPayload, v))
}
// PayloadHasSuffix applies the HasSuffix predicate on the "payload" field.
func PayloadHasSuffix(v string) predicate.Metric {
return predicate.Metric(sql.FieldHasSuffix(FieldPayload, v))
}
// PayloadEqualFold applies the EqualFold predicate on the "payload" field.
func PayloadEqualFold(v string) predicate.Metric {
return predicate.Metric(sql.FieldEqualFold(FieldPayload, v))
}
// PayloadContainsFold applies the ContainsFold predicate on the "payload" field.
func PayloadContainsFold(v string) predicate.Metric {
return predicate.Metric(sql.FieldContainsFold(FieldPayload, v))
}
// And groups predicates with the AND operator between them.
func And(predicates ...predicate.Metric) predicate.Metric {
return predicate.Metric(sql.AndPredicates(predicates...))
}
// Or groups predicates with the OR operator between them.
func Or(predicates ...predicate.Metric) predicate.Metric {
return predicate.Metric(sql.OrPredicates(predicates...))
}
// Not applies the not operator on the given predicate.
func Not(p predicate.Metric) predicate.Metric {
return predicate.Metric(sql.NotPredicates(p))
}

View file

@ -0,0 +1,246 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
)
// MetricCreate is the builder for creating a Metric entity.
type MetricCreate struct {
config
mutation *MetricMutation
hooks []Hook
}
// SetGeneratedType sets the "generated_type" field.
func (mc *MetricCreate) SetGeneratedType(mt metric.GeneratedType) *MetricCreate {
mc.mutation.SetGeneratedType(mt)
return mc
}
// SetGeneratedBy sets the "generated_by" field.
func (mc *MetricCreate) SetGeneratedBy(s string) *MetricCreate {
mc.mutation.SetGeneratedBy(s)
return mc
}
// SetCollectedAt sets the "collected_at" field.
func (mc *MetricCreate) SetCollectedAt(t time.Time) *MetricCreate {
mc.mutation.SetCollectedAt(t)
return mc
}
// SetPushedAt sets the "pushed_at" field.
func (mc *MetricCreate) SetPushedAt(t time.Time) *MetricCreate {
mc.mutation.SetPushedAt(t)
return mc
}
// SetNillablePushedAt sets the "pushed_at" field if the given value is not nil.
func (mc *MetricCreate) SetNillablePushedAt(t *time.Time) *MetricCreate {
if t != nil {
mc.SetPushedAt(*t)
}
return mc
}
// SetPayload sets the "payload" field.
func (mc *MetricCreate) SetPayload(s string) *MetricCreate {
mc.mutation.SetPayload(s)
return mc
}
// Mutation returns the MetricMutation object of the builder.
func (mc *MetricCreate) Mutation() *MetricMutation {
return mc.mutation
}
// Save creates the Metric in the database.
func (mc *MetricCreate) Save(ctx context.Context) (*Metric, error) {
return withHooks(ctx, mc.sqlSave, mc.mutation, mc.hooks)
}
// SaveX calls Save and panics if Save returns an error.
func (mc *MetricCreate) SaveX(ctx context.Context) *Metric {
v, err := mc.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (mc *MetricCreate) Exec(ctx context.Context) error {
_, err := mc.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (mc *MetricCreate) ExecX(ctx context.Context) {
if err := mc.Exec(ctx); err != nil {
panic(err)
}
}
// check runs all checks and user-defined validators on the builder.
func (mc *MetricCreate) check() error {
if _, ok := mc.mutation.GeneratedType(); !ok {
return &ValidationError{Name: "generated_type", err: errors.New(`ent: missing required field "Metric.generated_type"`)}
}
if v, ok := mc.mutation.GeneratedType(); ok {
if err := metric.GeneratedTypeValidator(v); err != nil {
return &ValidationError{Name: "generated_type", err: fmt.Errorf(`ent: validator failed for field "Metric.generated_type": %w`, err)}
}
}
if _, ok := mc.mutation.GeneratedBy(); !ok {
return &ValidationError{Name: "generated_by", err: errors.New(`ent: missing required field "Metric.generated_by"`)}
}
if _, ok := mc.mutation.CollectedAt(); !ok {
return &ValidationError{Name: "collected_at", err: errors.New(`ent: missing required field "Metric.collected_at"`)}
}
if _, ok := mc.mutation.Payload(); !ok {
return &ValidationError{Name: "payload", err: errors.New(`ent: missing required field "Metric.payload"`)}
}
return nil
}
func (mc *MetricCreate) sqlSave(ctx context.Context) (*Metric, error) {
if err := mc.check(); err != nil {
return nil, err
}
_node, _spec := mc.createSpec()
if err := sqlgraph.CreateNode(ctx, mc.driver, _spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
id := _spec.ID.Value.(int64)
_node.ID = int(id)
mc.mutation.id = &_node.ID
mc.mutation.done = true
return _node, nil
}
func (mc *MetricCreate) createSpec() (*Metric, *sqlgraph.CreateSpec) {
var (
_node = &Metric{config: mc.config}
_spec = sqlgraph.NewCreateSpec(metric.Table, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt))
)
if value, ok := mc.mutation.GeneratedType(); ok {
_spec.SetField(metric.FieldGeneratedType, field.TypeEnum, value)
_node.GeneratedType = value
}
if value, ok := mc.mutation.GeneratedBy(); ok {
_spec.SetField(metric.FieldGeneratedBy, field.TypeString, value)
_node.GeneratedBy = value
}
if value, ok := mc.mutation.CollectedAt(); ok {
_spec.SetField(metric.FieldCollectedAt, field.TypeTime, value)
_node.CollectedAt = value
}
if value, ok := mc.mutation.PushedAt(); ok {
_spec.SetField(metric.FieldPushedAt, field.TypeTime, value)
_node.PushedAt = &value
}
if value, ok := mc.mutation.Payload(); ok {
_spec.SetField(metric.FieldPayload, field.TypeString, value)
_node.Payload = value
}
return _node, _spec
}
// MetricCreateBulk is the builder for creating many Metric entities in bulk.
type MetricCreateBulk struct {
config
err error
builders []*MetricCreate
}
// Save creates the Metric entities in the database.
func (mcb *MetricCreateBulk) Save(ctx context.Context) ([]*Metric, error) {
if mcb.err != nil {
return nil, mcb.err
}
specs := make([]*sqlgraph.CreateSpec, len(mcb.builders))
nodes := make([]*Metric, len(mcb.builders))
mutators := make([]Mutator, len(mcb.builders))
for i := range mcb.builders {
func(i int, root context.Context) {
builder := mcb.builders[i]
var mut Mutator = MutateFunc(func(ctx context.Context, m Mutation) (Value, error) {
mutation, ok := m.(*MetricMutation)
if !ok {
return nil, fmt.Errorf("unexpected mutation type %T", m)
}
if err := builder.check(); err != nil {
return nil, err
}
builder.mutation = mutation
var err error
nodes[i], specs[i] = builder.createSpec()
if i < len(mutators)-1 {
_, err = mutators[i+1].Mutate(root, mcb.builders[i+1].mutation)
} else {
spec := &sqlgraph.BatchCreateSpec{Nodes: specs}
// Invoke the actual operation on the latest mutation in the chain.
if err = sqlgraph.BatchCreate(ctx, mcb.driver, spec); err != nil {
if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
}
}
if err != nil {
return nil, err
}
mutation.id = &nodes[i].ID
if specs[i].ID.Value != nil {
id := specs[i].ID.Value.(int64)
nodes[i].ID = int(id)
}
mutation.done = true
return nodes[i], nil
})
for i := len(builder.hooks) - 1; i >= 0; i-- {
mut = builder.hooks[i](mut)
}
mutators[i] = mut
}(i, ctx)
}
if len(mutators) > 0 {
if _, err := mutators[0].Mutate(ctx, mcb.builders[0].mutation); err != nil {
return nil, err
}
}
return nodes, nil
}
// SaveX is like Save, but panics if an error occurs.
func (mcb *MetricCreateBulk) SaveX(ctx context.Context) []*Metric {
v, err := mcb.Save(ctx)
if err != nil {
panic(err)
}
return v
}
// Exec executes the query.
func (mcb *MetricCreateBulk) Exec(ctx context.Context) error {
_, err := mcb.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (mcb *MetricCreateBulk) ExecX(ctx context.Context) {
if err := mcb.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -0,0 +1,88 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
)
// MetricDelete is the builder for deleting a Metric entity.
type MetricDelete struct {
config
hooks []Hook
mutation *MetricMutation
}
// Where appends a list predicates to the MetricDelete builder.
func (md *MetricDelete) Where(ps ...predicate.Metric) *MetricDelete {
md.mutation.Where(ps...)
return md
}
// Exec executes the deletion query and returns how many vertices were deleted.
func (md *MetricDelete) Exec(ctx context.Context) (int, error) {
return withHooks(ctx, md.sqlExec, md.mutation, md.hooks)
}
// ExecX is like Exec, but panics if an error occurs.
func (md *MetricDelete) ExecX(ctx context.Context) int {
n, err := md.Exec(ctx)
if err != nil {
panic(err)
}
return n
}
func (md *MetricDelete) sqlExec(ctx context.Context) (int, error) {
_spec := sqlgraph.NewDeleteSpec(metric.Table, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt))
if ps := md.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
affected, err := sqlgraph.DeleteNodes(ctx, md.driver, _spec)
if err != nil && sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
md.mutation.done = true
return affected, err
}
// MetricDeleteOne is the builder for deleting a single Metric entity.
type MetricDeleteOne struct {
md *MetricDelete
}
// Where appends a list predicates to the MetricDelete builder.
func (mdo *MetricDeleteOne) Where(ps ...predicate.Metric) *MetricDeleteOne {
mdo.md.mutation.Where(ps...)
return mdo
}
// Exec executes the deletion query.
func (mdo *MetricDeleteOne) Exec(ctx context.Context) error {
n, err := mdo.md.Exec(ctx)
switch {
case err != nil:
return err
case n == 0:
return &NotFoundError{metric.Label}
default:
return nil
}
}
// ExecX is like Exec, but panics if an error occurs.
func (mdo *MetricDeleteOne) ExecX(ctx context.Context) {
if err := mdo.Exec(ctx); err != nil {
panic(err)
}
}

View file

@ -0,0 +1,526 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"fmt"
"math"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
)
// MetricQuery is the builder for querying Metric entities.
type MetricQuery struct {
config
ctx *QueryContext
order []metric.OrderOption
inters []Interceptor
predicates []predicate.Metric
// intermediate query (i.e. traversal path).
sql *sql.Selector
path func(context.Context) (*sql.Selector, error)
}
// Where adds a new predicate for the MetricQuery builder.
func (mq *MetricQuery) Where(ps ...predicate.Metric) *MetricQuery {
mq.predicates = append(mq.predicates, ps...)
return mq
}
// Limit the number of records to be returned by this query.
func (mq *MetricQuery) Limit(limit int) *MetricQuery {
mq.ctx.Limit = &limit
return mq
}
// Offset to start from.
func (mq *MetricQuery) Offset(offset int) *MetricQuery {
mq.ctx.Offset = &offset
return mq
}
// Unique configures the query builder to filter duplicate records on query.
// By default, unique is set to true, and can be disabled using this method.
func (mq *MetricQuery) Unique(unique bool) *MetricQuery {
mq.ctx.Unique = &unique
return mq
}
// Order specifies how the records should be ordered.
func (mq *MetricQuery) Order(o ...metric.OrderOption) *MetricQuery {
mq.order = append(mq.order, o...)
return mq
}
// First returns the first Metric entity from the query.
// Returns a *NotFoundError when no Metric was found.
func (mq *MetricQuery) First(ctx context.Context) (*Metric, error) {
nodes, err := mq.Limit(1).All(setContextOp(ctx, mq.ctx, "First"))
if err != nil {
return nil, err
}
if len(nodes) == 0 {
return nil, &NotFoundError{metric.Label}
}
return nodes[0], nil
}
// FirstX is like First, but panics if an error occurs.
func (mq *MetricQuery) FirstX(ctx context.Context) *Metric {
node, err := mq.First(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return node
}
// FirstID returns the first Metric ID from the query.
// Returns a *NotFoundError when no Metric ID was found.
func (mq *MetricQuery) FirstID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = mq.Limit(1).IDs(setContextOp(ctx, mq.ctx, "FirstID")); err != nil {
return
}
if len(ids) == 0 {
err = &NotFoundError{metric.Label}
return
}
return ids[0], nil
}
// FirstIDX is like FirstID, but panics if an error occurs.
func (mq *MetricQuery) FirstIDX(ctx context.Context) int {
id, err := mq.FirstID(ctx)
if err != nil && !IsNotFound(err) {
panic(err)
}
return id
}
// Only returns a single Metric entity found by the query, ensuring it only returns one.
// Returns a *NotSingularError when more than one Metric entity is found.
// Returns a *NotFoundError when no Metric entities are found.
func (mq *MetricQuery) Only(ctx context.Context) (*Metric, error) {
nodes, err := mq.Limit(2).All(setContextOp(ctx, mq.ctx, "Only"))
if err != nil {
return nil, err
}
switch len(nodes) {
case 1:
return nodes[0], nil
case 0:
return nil, &NotFoundError{metric.Label}
default:
return nil, &NotSingularError{metric.Label}
}
}
// OnlyX is like Only, but panics if an error occurs.
func (mq *MetricQuery) OnlyX(ctx context.Context) *Metric {
node, err := mq.Only(ctx)
if err != nil {
panic(err)
}
return node
}
// OnlyID is like Only, but returns the only Metric ID in the query.
// Returns a *NotSingularError when more than one Metric ID is found.
// Returns a *NotFoundError when no entities are found.
func (mq *MetricQuery) OnlyID(ctx context.Context) (id int, err error) {
var ids []int
if ids, err = mq.Limit(2).IDs(setContextOp(ctx, mq.ctx, "OnlyID")); err != nil {
return
}
switch len(ids) {
case 1:
id = ids[0]
case 0:
err = &NotFoundError{metric.Label}
default:
err = &NotSingularError{metric.Label}
}
return
}
// OnlyIDX is like OnlyID, but panics if an error occurs.
func (mq *MetricQuery) OnlyIDX(ctx context.Context) int {
id, err := mq.OnlyID(ctx)
if err != nil {
panic(err)
}
return id
}
// All executes the query and returns a list of Metrics.
func (mq *MetricQuery) All(ctx context.Context) ([]*Metric, error) {
ctx = setContextOp(ctx, mq.ctx, "All")
if err := mq.prepareQuery(ctx); err != nil {
return nil, err
}
qr := querierAll[[]*Metric, *MetricQuery]()
return withInterceptors[[]*Metric](ctx, mq, qr, mq.inters)
}
// AllX is like All, but panics if an error occurs.
func (mq *MetricQuery) AllX(ctx context.Context) []*Metric {
nodes, err := mq.All(ctx)
if err != nil {
panic(err)
}
return nodes
}
// IDs executes the query and returns a list of Metric IDs.
func (mq *MetricQuery) IDs(ctx context.Context) (ids []int, err error) {
if mq.ctx.Unique == nil && mq.path != nil {
mq.Unique(true)
}
ctx = setContextOp(ctx, mq.ctx, "IDs")
if err = mq.Select(metric.FieldID).Scan(ctx, &ids); err != nil {
return nil, err
}
return ids, nil
}
// IDsX is like IDs, but panics if an error occurs.
func (mq *MetricQuery) IDsX(ctx context.Context) []int {
ids, err := mq.IDs(ctx)
if err != nil {
panic(err)
}
return ids
}
// Count returns the count of the given query.
func (mq *MetricQuery) Count(ctx context.Context) (int, error) {
ctx = setContextOp(ctx, mq.ctx, "Count")
if err := mq.prepareQuery(ctx); err != nil {
return 0, err
}
return withInterceptors[int](ctx, mq, querierCount[*MetricQuery](), mq.inters)
}
// CountX is like Count, but panics if an error occurs.
func (mq *MetricQuery) CountX(ctx context.Context) int {
count, err := mq.Count(ctx)
if err != nil {
panic(err)
}
return count
}
// Exist returns true if the query has elements in the graph.
func (mq *MetricQuery) Exist(ctx context.Context) (bool, error) {
ctx = setContextOp(ctx, mq.ctx, "Exist")
switch _, err := mq.FirstID(ctx); {
case IsNotFound(err):
return false, nil
case err != nil:
return false, fmt.Errorf("ent: check existence: %w", err)
default:
return true, nil
}
}
// ExistX is like Exist, but panics if an error occurs.
func (mq *MetricQuery) ExistX(ctx context.Context) bool {
exist, err := mq.Exist(ctx)
if err != nil {
panic(err)
}
return exist
}
// Clone returns a duplicate of the MetricQuery builder, including all associated steps. It can be
// used to prepare common query builders and use them differently after the clone is made.
func (mq *MetricQuery) Clone() *MetricQuery {
if mq == nil {
return nil
}
return &MetricQuery{
config: mq.config,
ctx: mq.ctx.Clone(),
order: append([]metric.OrderOption{}, mq.order...),
inters: append([]Interceptor{}, mq.inters...),
predicates: append([]predicate.Metric{}, mq.predicates...),
// clone intermediate query.
sql: mq.sql.Clone(),
path: mq.path,
}
}
// GroupBy is used to group vertices by one or more fields/columns.
// It is often used with aggregate functions, like: count, max, mean, min, sum.
//
// Example:
//
// var v []struct {
// GeneratedType metric.GeneratedType `json:"generated_type,omitempty"`
// Count int `json:"count,omitempty"`
// }
//
// client.Metric.Query().
// GroupBy(metric.FieldGeneratedType).
// Aggregate(ent.Count()).
// Scan(ctx, &v)
func (mq *MetricQuery) GroupBy(field string, fields ...string) *MetricGroupBy {
mq.ctx.Fields = append([]string{field}, fields...)
grbuild := &MetricGroupBy{build: mq}
grbuild.flds = &mq.ctx.Fields
grbuild.label = metric.Label
grbuild.scan = grbuild.Scan
return grbuild
}
// Select allows the selection one or more fields/columns for the given query,
// instead of selecting all fields in the entity.
//
// Example:
//
// var v []struct {
// GeneratedType metric.GeneratedType `json:"generated_type,omitempty"`
// }
//
// client.Metric.Query().
// Select(metric.FieldGeneratedType).
// Scan(ctx, &v)
func (mq *MetricQuery) Select(fields ...string) *MetricSelect {
mq.ctx.Fields = append(mq.ctx.Fields, fields...)
sbuild := &MetricSelect{MetricQuery: mq}
sbuild.label = metric.Label
sbuild.flds, sbuild.scan = &mq.ctx.Fields, sbuild.Scan
return sbuild
}
// Aggregate returns a MetricSelect configured with the given aggregations.
func (mq *MetricQuery) Aggregate(fns ...AggregateFunc) *MetricSelect {
return mq.Select().Aggregate(fns...)
}
func (mq *MetricQuery) prepareQuery(ctx context.Context) error {
for _, inter := range mq.inters {
if inter == nil {
return fmt.Errorf("ent: uninitialized interceptor (forgotten import ent/runtime?)")
}
if trv, ok := inter.(Traverser); ok {
if err := trv.Traverse(ctx, mq); err != nil {
return err
}
}
}
for _, f := range mq.ctx.Fields {
if !metric.ValidColumn(f) {
return &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
}
if mq.path != nil {
prev, err := mq.path(ctx)
if err != nil {
return err
}
mq.sql = prev
}
return nil
}
func (mq *MetricQuery) sqlAll(ctx context.Context, hooks ...queryHook) ([]*Metric, error) {
var (
nodes = []*Metric{}
_spec = mq.querySpec()
)
_spec.ScanValues = func(columns []string) ([]any, error) {
return (*Metric).scanValues(nil, columns)
}
_spec.Assign = func(columns []string, values []any) error {
node := &Metric{config: mq.config}
nodes = append(nodes, node)
return node.assignValues(columns, values)
}
for i := range hooks {
hooks[i](ctx, _spec)
}
if err := sqlgraph.QueryNodes(ctx, mq.driver, _spec); err != nil {
return nil, err
}
if len(nodes) == 0 {
return nodes, nil
}
return nodes, nil
}
func (mq *MetricQuery) sqlCount(ctx context.Context) (int, error) {
_spec := mq.querySpec()
_spec.Node.Columns = mq.ctx.Fields
if len(mq.ctx.Fields) > 0 {
_spec.Unique = mq.ctx.Unique != nil && *mq.ctx.Unique
}
return sqlgraph.CountNodes(ctx, mq.driver, _spec)
}
func (mq *MetricQuery) querySpec() *sqlgraph.QuerySpec {
_spec := sqlgraph.NewQuerySpec(metric.Table, metric.Columns, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt))
_spec.From = mq.sql
if unique := mq.ctx.Unique; unique != nil {
_spec.Unique = *unique
} else if mq.path != nil {
_spec.Unique = true
}
if fields := mq.ctx.Fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, metric.FieldID)
for i := range fields {
if fields[i] != metric.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, fields[i])
}
}
}
if ps := mq.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if limit := mq.ctx.Limit; limit != nil {
_spec.Limit = *limit
}
if offset := mq.ctx.Offset; offset != nil {
_spec.Offset = *offset
}
if ps := mq.order; len(ps) > 0 {
_spec.Order = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
return _spec
}
func (mq *MetricQuery) sqlQuery(ctx context.Context) *sql.Selector {
builder := sql.Dialect(mq.driver.Dialect())
t1 := builder.Table(metric.Table)
columns := mq.ctx.Fields
if len(columns) == 0 {
columns = metric.Columns
}
selector := builder.Select(t1.Columns(columns...)...).From(t1)
if mq.sql != nil {
selector = mq.sql
selector.Select(selector.Columns(columns...)...)
}
if mq.ctx.Unique != nil && *mq.ctx.Unique {
selector.Distinct()
}
for _, p := range mq.predicates {
p(selector)
}
for _, p := range mq.order {
p(selector)
}
if offset := mq.ctx.Offset; offset != nil {
// limit is mandatory for offset clause. We start
// with default value, and override it below if needed.
selector.Offset(*offset).Limit(math.MaxInt32)
}
if limit := mq.ctx.Limit; limit != nil {
selector.Limit(*limit)
}
return selector
}
// MetricGroupBy is the group-by builder for Metric entities.
type MetricGroupBy struct {
selector
build *MetricQuery
}
// Aggregate adds the given aggregation functions to the group-by query.
func (mgb *MetricGroupBy) Aggregate(fns ...AggregateFunc) *MetricGroupBy {
mgb.fns = append(mgb.fns, fns...)
return mgb
}
// Scan applies the selector query and scans the result into the given value.
func (mgb *MetricGroupBy) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, mgb.build.ctx, "GroupBy")
if err := mgb.build.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*MetricQuery, *MetricGroupBy](ctx, mgb.build, mgb, mgb.build.inters, v)
}
func (mgb *MetricGroupBy) sqlScan(ctx context.Context, root *MetricQuery, v any) error {
selector := root.sqlQuery(ctx).Select()
aggregation := make([]string, 0, len(mgb.fns))
for _, fn := range mgb.fns {
aggregation = append(aggregation, fn(selector))
}
if len(selector.SelectedColumns()) == 0 {
columns := make([]string, 0, len(*mgb.flds)+len(mgb.fns))
for _, f := range *mgb.flds {
columns = append(columns, selector.C(f))
}
columns = append(columns, aggregation...)
selector.Select(columns...)
}
selector.GroupBy(selector.Columns(*mgb.flds...)...)
if err := selector.Err(); err != nil {
return err
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := mgb.build.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}
// MetricSelect is the builder for selecting fields of Metric entities.
type MetricSelect struct {
*MetricQuery
selector
}
// Aggregate adds the given aggregation functions to the selector query.
func (ms *MetricSelect) Aggregate(fns ...AggregateFunc) *MetricSelect {
ms.fns = append(ms.fns, fns...)
return ms
}
// Scan applies the selector query and scans the result into the given value.
func (ms *MetricSelect) Scan(ctx context.Context, v any) error {
ctx = setContextOp(ctx, ms.ctx, "Select")
if err := ms.prepareQuery(ctx); err != nil {
return err
}
return scanWithInterceptors[*MetricQuery, *MetricSelect](ctx, ms.MetricQuery, ms, ms.inters, v)
}
func (ms *MetricSelect) sqlScan(ctx context.Context, root *MetricQuery, v any) error {
selector := root.sqlQuery(ctx)
aggregation := make([]string, 0, len(ms.fns))
for _, fn := range ms.fns {
aggregation = append(aggregation, fn(selector))
}
switch n := len(*ms.selector.flds); {
case n == 0 && len(aggregation) > 0:
selector.Select(aggregation...)
case n != 0 && len(aggregation) > 0:
selector.AppendSelect(aggregation...)
}
rows := &sql.Rows{}
query, args := selector.Query()
if err := ms.driver.Query(ctx, query, args, rows); err != nil {
return err
}
defer rows.Close()
return sql.ScanSlice(rows, v)
}

View file

@ -0,0 +1,228 @@
// Code generated by ent, DO NOT EDIT.
package ent
import (
"context"
"errors"
"fmt"
"time"
"entgo.io/ent/dialect/sql"
"entgo.io/ent/dialect/sql/sqlgraph"
"entgo.io/ent/schema/field"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/predicate"
)
// MetricUpdate is the builder for updating Metric entities.
type MetricUpdate struct {
config
hooks []Hook
mutation *MetricMutation
}
// Where appends a list predicates to the MetricUpdate builder.
func (mu *MetricUpdate) Where(ps ...predicate.Metric) *MetricUpdate {
mu.mutation.Where(ps...)
return mu
}
// SetPushedAt sets the "pushed_at" field.
func (mu *MetricUpdate) SetPushedAt(t time.Time) *MetricUpdate {
mu.mutation.SetPushedAt(t)
return mu
}
// SetNillablePushedAt sets the "pushed_at" field if the given value is not nil.
func (mu *MetricUpdate) SetNillablePushedAt(t *time.Time) *MetricUpdate {
if t != nil {
mu.SetPushedAt(*t)
}
return mu
}
// ClearPushedAt clears the value of the "pushed_at" field.
func (mu *MetricUpdate) ClearPushedAt() *MetricUpdate {
mu.mutation.ClearPushedAt()
return mu
}
// Mutation returns the MetricMutation object of the builder.
func (mu *MetricUpdate) Mutation() *MetricMutation {
return mu.mutation
}
// Save executes the query and returns the number of nodes affected by the update operation.
func (mu *MetricUpdate) Save(ctx context.Context) (int, error) {
return withHooks(ctx, mu.sqlSave, mu.mutation, mu.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (mu *MetricUpdate) SaveX(ctx context.Context) int {
affected, err := mu.Save(ctx)
if err != nil {
panic(err)
}
return affected
}
// Exec executes the query.
func (mu *MetricUpdate) Exec(ctx context.Context) error {
_, err := mu.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (mu *MetricUpdate) ExecX(ctx context.Context) {
if err := mu.Exec(ctx); err != nil {
panic(err)
}
}
func (mu *MetricUpdate) sqlSave(ctx context.Context) (n int, err error) {
_spec := sqlgraph.NewUpdateSpec(metric.Table, metric.Columns, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt))
if ps := mu.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := mu.mutation.PushedAt(); ok {
_spec.SetField(metric.FieldPushedAt, field.TypeTime, value)
}
if mu.mutation.PushedAtCleared() {
_spec.ClearField(metric.FieldPushedAt, field.TypeTime)
}
if n, err = sqlgraph.UpdateNodes(ctx, mu.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{metric.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return 0, err
}
mu.mutation.done = true
return n, nil
}
// MetricUpdateOne is the builder for updating a single Metric entity.
type MetricUpdateOne struct {
config
fields []string
hooks []Hook
mutation *MetricMutation
}
// SetPushedAt sets the "pushed_at" field.
func (muo *MetricUpdateOne) SetPushedAt(t time.Time) *MetricUpdateOne {
muo.mutation.SetPushedAt(t)
return muo
}
// SetNillablePushedAt sets the "pushed_at" field if the given value is not nil.
func (muo *MetricUpdateOne) SetNillablePushedAt(t *time.Time) *MetricUpdateOne {
if t != nil {
muo.SetPushedAt(*t)
}
return muo
}
// ClearPushedAt clears the value of the "pushed_at" field.
func (muo *MetricUpdateOne) ClearPushedAt() *MetricUpdateOne {
muo.mutation.ClearPushedAt()
return muo
}
// Mutation returns the MetricMutation object of the builder.
func (muo *MetricUpdateOne) Mutation() *MetricMutation {
return muo.mutation
}
// Where appends a list predicates to the MetricUpdate builder.
func (muo *MetricUpdateOne) Where(ps ...predicate.Metric) *MetricUpdateOne {
muo.mutation.Where(ps...)
return muo
}
// Select allows selecting one or more fields (columns) of the returned entity.
// The default is selecting all fields defined in the entity schema.
func (muo *MetricUpdateOne) Select(field string, fields ...string) *MetricUpdateOne {
muo.fields = append([]string{field}, fields...)
return muo
}
// Save executes the query and returns the updated Metric entity.
func (muo *MetricUpdateOne) Save(ctx context.Context) (*Metric, error) {
return withHooks(ctx, muo.sqlSave, muo.mutation, muo.hooks)
}
// SaveX is like Save, but panics if an error occurs.
func (muo *MetricUpdateOne) SaveX(ctx context.Context) *Metric {
node, err := muo.Save(ctx)
if err != nil {
panic(err)
}
return node
}
// Exec executes the query on the entity.
func (muo *MetricUpdateOne) Exec(ctx context.Context) error {
_, err := muo.Save(ctx)
return err
}
// ExecX is like Exec, but panics if an error occurs.
func (muo *MetricUpdateOne) ExecX(ctx context.Context) {
if err := muo.Exec(ctx); err != nil {
panic(err)
}
}
func (muo *MetricUpdateOne) sqlSave(ctx context.Context) (_node *Metric, err error) {
_spec := sqlgraph.NewUpdateSpec(metric.Table, metric.Columns, sqlgraph.NewFieldSpec(metric.FieldID, field.TypeInt))
id, ok := muo.mutation.ID()
if !ok {
return nil, &ValidationError{Name: "id", err: errors.New(`ent: missing "Metric.id" for update`)}
}
_spec.Node.ID.Value = id
if fields := muo.fields; len(fields) > 0 {
_spec.Node.Columns = make([]string, 0, len(fields))
_spec.Node.Columns = append(_spec.Node.Columns, metric.FieldID)
for _, f := range fields {
if !metric.ValidColumn(f) {
return nil, &ValidationError{Name: f, err: fmt.Errorf("ent: invalid field %q for query", f)}
}
if f != metric.FieldID {
_spec.Node.Columns = append(_spec.Node.Columns, f)
}
}
}
if ps := muo.mutation.predicates; len(ps) > 0 {
_spec.Predicate = func(selector *sql.Selector) {
for i := range ps {
ps[i](selector)
}
}
}
if value, ok := muo.mutation.PushedAt(); ok {
_spec.SetField(metric.FieldPushedAt, field.TypeTime, value)
}
if muo.mutation.PushedAtCleared() {
_spec.ClearField(metric.FieldPushedAt, field.TypeTime)
}
_node = &Metric{config: muo.config}
_spec.Assign = _node.assignValues
_spec.ScanValues = _node.scanValues
if err = sqlgraph.UpdateNode(ctx, muo.driver, _spec); err != nil {
if _, ok := err.(*sqlgraph.NotFoundError); ok {
err = &NotFoundError{metric.Label}
} else if sqlgraph.IsConstraintError(err) {
err = &ConstraintError{msg: err.Error(), wrap: err}
}
return nil, err
}
muo.mutation.done = true
return _node, nil
}

View file

@ -11,8 +11,8 @@ var (
// AlertsColumns holds the columns for the "alerts" table.
AlertsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "scenario", Type: field.TypeString},
{Name: "bucket_id", Type: field.TypeString, Nullable: true, Default: ""},
{Name: "message", Type: field.TypeString, Nullable: true, Default: ""},
@ -60,8 +60,8 @@ var (
// BouncersColumns holds the columns for the "bouncers" table.
BouncersColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Unique: true},
{Name: "api_key", Type: field.TypeString},
{Name: "revoked", Type: field.TypeBool},
@ -71,6 +71,9 @@ var (
{Name: "until", Type: field.TypeTime, Nullable: true},
{Name: "last_pull", Type: field.TypeTime},
{Name: "auth_type", Type: field.TypeString, Default: "api-key"},
{Name: "osname", Type: field.TypeString, Nullable: true},
{Name: "osversion", Type: field.TypeString, Nullable: true},
{Name: "featureflags", Type: field.TypeString, Nullable: true},
}
// BouncersTable holds the schema information for the "bouncers" table.
BouncersTable = &schema.Table{
@ -81,8 +84,8 @@ var (
// ConfigItemsColumns holds the columns for the "config_items" table.
ConfigItemsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "name", Type: field.TypeString, Unique: true},
{Name: "value", Type: field.TypeString},
}
@ -95,8 +98,8 @@ var (
// DecisionsColumns holds the columns for the "decisions" table.
DecisionsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "until", Type: field.TypeTime, Nullable: true, SchemaType: map[string]string{"mysql": "datetime"}},
{Name: "scenario", Type: field.TypeString},
{Name: "type", Type: field.TypeString},
@ -151,8 +154,8 @@ var (
// EventsColumns holds the columns for the "events" table.
EventsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "time", Type: field.TypeTime},
{Name: "serialized", Type: field.TypeString, Size: 8191},
{Name: "alert_events", Type: field.TypeInt, Nullable: true},
@ -193,8 +196,8 @@ var (
// MachinesColumns holds the columns for the "machines" table.
MachinesColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "last_push", Type: field.TypeTime, Nullable: true},
{Name: "last_heartbeat", Type: field.TypeTime, Nullable: true},
{Name: "machine_id", Type: field.TypeString, Unique: true},
@ -205,6 +208,10 @@ var (
{Name: "is_validated", Type: field.TypeBool, Default: false},
{Name: "status", Type: field.TypeString, Nullable: true},
{Name: "auth_type", Type: field.TypeString, Default: "password"},
{Name: "osname", Type: field.TypeString, Nullable: true},
{Name: "osversion", Type: field.TypeString, Nullable: true},
{Name: "featureflags", Type: field.TypeString, Nullable: true},
{Name: "hubstate", Type: field.TypeJSON, Nullable: true},
}
// MachinesTable holds the schema information for the "machines" table.
MachinesTable = &schema.Table{
@ -215,8 +222,8 @@ var (
// MetaColumns holds the columns for the "meta" table.
MetaColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "created_at", Type: field.TypeTime, Nullable: true},
{Name: "updated_at", Type: field.TypeTime, Nullable: true},
{Name: "created_at", Type: field.TypeTime},
{Name: "updated_at", Type: field.TypeTime},
{Name: "key", Type: field.TypeString},
{Name: "value", Type: field.TypeString, Size: 4095},
{Name: "alert_metas", Type: field.TypeInt, Nullable: true},
@ -242,6 +249,28 @@ var (
},
},
}
// MetricsColumns holds the columns for the "metrics" table.
MetricsColumns = []*schema.Column{
{Name: "id", Type: field.TypeInt, Increment: true},
{Name: "generated_type", Type: field.TypeEnum, Enums: []string{"LP", "RC"}},
{Name: "generated_by", Type: field.TypeString},
{Name: "collected_at", Type: field.TypeTime},
{Name: "pushed_at", Type: field.TypeTime, Nullable: true},
{Name: "payload", Type: field.TypeString},
}
// MetricsTable holds the schema information for the "metrics" table.
MetricsTable = &schema.Table{
Name: "metrics",
Columns: MetricsColumns,
PrimaryKey: []*schema.Column{MetricsColumns[0]},
Indexes: []*schema.Index{
{
Name: "metric_generated_type_generated_by_collected_at",
Unique: true,
Columns: []*schema.Column{MetricsColumns[1], MetricsColumns[2], MetricsColumns[3]},
},
},
}
// Tables holds all the tables in the schema.
Tables = []*schema.Table{
AlertsTable,
@ -252,6 +281,7 @@ var (
LocksTable,
MachinesTable,
MetaTable,
MetricsTable,
}
)

File diff suppressed because it is too large Load diff

View file

@ -29,3 +29,6 @@ type Machine func(*sql.Selector)
// Meta is the predicate function for meta builders.
type Meta func(*sql.Selector)
// Metric is the predicate function for metric builders.
type Metric func(*sql.Selector)

View file

@ -26,8 +26,6 @@ func init() {
alertDescCreatedAt := alertFields[0].Descriptor()
// alert.DefaultCreatedAt holds the default value on creation for the created_at field.
alert.DefaultCreatedAt = alertDescCreatedAt.Default.(func() time.Time)
// alert.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
alert.UpdateDefaultCreatedAt = alertDescCreatedAt.UpdateDefault.(func() time.Time)
// alertDescUpdatedAt is the schema descriptor for updated_at field.
alertDescUpdatedAt := alertFields[1].Descriptor()
// alert.DefaultUpdatedAt holds the default value on creation for the updated_at field.
@ -64,8 +62,6 @@ func init() {
bouncerDescCreatedAt := bouncerFields[0].Descriptor()
// bouncer.DefaultCreatedAt holds the default value on creation for the created_at field.
bouncer.DefaultCreatedAt = bouncerDescCreatedAt.Default.(func() time.Time)
// bouncer.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
bouncer.UpdateDefaultCreatedAt = bouncerDescCreatedAt.UpdateDefault.(func() time.Time)
// bouncerDescUpdatedAt is the schema descriptor for updated_at field.
bouncerDescUpdatedAt := bouncerFields[1].Descriptor()
// bouncer.DefaultUpdatedAt holds the default value on creation for the updated_at field.
@ -94,8 +90,6 @@ func init() {
configitemDescCreatedAt := configitemFields[0].Descriptor()
// configitem.DefaultCreatedAt holds the default value on creation for the created_at field.
configitem.DefaultCreatedAt = configitemDescCreatedAt.Default.(func() time.Time)
// configitem.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
configitem.UpdateDefaultCreatedAt = configitemDescCreatedAt.UpdateDefault.(func() time.Time)
// configitemDescUpdatedAt is the schema descriptor for updated_at field.
configitemDescUpdatedAt := configitemFields[1].Descriptor()
// configitem.DefaultUpdatedAt holds the default value on creation for the updated_at field.
@ -108,8 +102,6 @@ func init() {
decisionDescCreatedAt := decisionFields[0].Descriptor()
// decision.DefaultCreatedAt holds the default value on creation for the created_at field.
decision.DefaultCreatedAt = decisionDescCreatedAt.Default.(func() time.Time)
// decision.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
decision.UpdateDefaultCreatedAt = decisionDescCreatedAt.UpdateDefault.(func() time.Time)
// decisionDescUpdatedAt is the schema descriptor for updated_at field.
decisionDescUpdatedAt := decisionFields[1].Descriptor()
// decision.DefaultUpdatedAt holds the default value on creation for the updated_at field.
@ -126,8 +118,6 @@ func init() {
eventDescCreatedAt := eventFields[0].Descriptor()
// event.DefaultCreatedAt holds the default value on creation for the created_at field.
event.DefaultCreatedAt = eventDescCreatedAt.Default.(func() time.Time)
// event.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
event.UpdateDefaultCreatedAt = eventDescCreatedAt.UpdateDefault.(func() time.Time)
// eventDescUpdatedAt is the schema descriptor for updated_at field.
eventDescUpdatedAt := eventFields[1].Descriptor()
// event.DefaultUpdatedAt holds the default value on creation for the updated_at field.
@ -150,8 +140,6 @@ func init() {
machineDescCreatedAt := machineFields[0].Descriptor()
// machine.DefaultCreatedAt holds the default value on creation for the created_at field.
machine.DefaultCreatedAt = machineDescCreatedAt.Default.(func() time.Time)
// machine.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
machine.UpdateDefaultCreatedAt = machineDescCreatedAt.UpdateDefault.(func() time.Time)
// machineDescUpdatedAt is the schema descriptor for updated_at field.
machineDescUpdatedAt := machineFields[1].Descriptor()
// machine.DefaultUpdatedAt holds the default value on creation for the updated_at field.
@ -188,8 +176,6 @@ func init() {
metaDescCreatedAt := metaFields[0].Descriptor()
// meta.DefaultCreatedAt holds the default value on creation for the created_at field.
meta.DefaultCreatedAt = metaDescCreatedAt.Default.(func() time.Time)
// meta.UpdateDefaultCreatedAt holds the default value on update for the created_at field.
meta.UpdateDefaultCreatedAt = metaDescCreatedAt.UpdateDefault.(func() time.Time)
// metaDescUpdatedAt is the schema descriptor for updated_at field.
metaDescUpdatedAt := metaFields[1].Descriptor()
// meta.DefaultUpdatedAt holds the default value on creation for the updated_at field.

View file

@ -19,10 +19,10 @@ func (Alert) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
Immutable(),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
UpdateDefault(types.UtcNow),
field.String("scenario"),
field.String("bucketId").Default("").Optional(),
field.String("message").Default("").Optional(),

View file

@ -16,10 +16,10 @@ func (Bouncer) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional().StructTag(`json:"created_at"`),
StructTag(`json:"created_at"`),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional().StructTag(`json:"updated_at"`),
UpdateDefault(types.UtcNow).StructTag(`json:"updated_at"`),
field.String("name").Unique().StructTag(`json:"name"`),
field.String("api_key").Sensitive(), // hash of api_key
field.Bool("revoked").StructTag(`json:"revoked"`),
@ -30,6 +30,9 @@ func (Bouncer) Fields() []ent.Field {
field.Time("last_pull").
Default(types.UtcNow).StructTag(`json:"last_pull"`),
field.String("auth_type").StructTag(`json:"auth_type"`).Default(types.ApiKeyAuthType),
field.String("osname").Optional(),
field.String("osversion").Optional(),
field.String("featureflags").Optional(),
}
}

View file

@ -11,21 +11,20 @@ type ConfigItem struct {
ent.Schema
}
// Fields of the Bouncer.
func (ConfigItem) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional().StructTag(`json:"created_at"`),
Immutable().
StructTag(`json:"created_at"`),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional().StructTag(`json:"updated_at"`),
UpdateDefault(types.UtcNow).StructTag(`json:"updated_at"`),
field.String("name").Unique().StructTag(`json:"name"`),
field.String("value").StructTag(`json:"value"`), // a json object
}
}
// Edges of the Bouncer.
func (ConfigItem) Edges() []ent.Edge {
return nil
}

View file

@ -19,10 +19,10 @@ func (Decision) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
Immutable(),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
UpdateDefault(types.UtcNow),
field.Time("until").Nillable().Optional().SchemaType(map[string]string{
dialect.MySQL: "datetime",
}),

View file

@ -18,10 +18,10 @@ func (Event) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
Immutable(),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
UpdateDefault(types.UtcNow),
field.Time("time"),
field.String("serialized").MaxLen(8191),
field.Int("alert_events").Optional(),

View file

@ -12,7 +12,7 @@ type Lock struct {
func (Lock) Fields() []ent.Field {
return []ent.Field{
field.String("name").Unique().StructTag(`json:"name"`),
field.String("name").Unique().Immutable().StructTag(`json:"name"`),
field.Time("created_at").Default(types.UtcNow).StructTag(`json:"created_at"`),
}
}

View file

@ -5,6 +5,7 @@ import (
"entgo.io/ent/schema/edge"
"entgo.io/ent/schema/field"
"github.com/crowdsecurity/crowdsec/pkg/types"
"github.com/crowdsecurity/crowdsec/pkg/models"
)
// Machine holds the schema definition for the Machine entity.
@ -17,17 +18,19 @@ func (Machine) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
Immutable(),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
UpdateDefault(types.UtcNow),
field.Time("last_push").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
field.Time("last_heartbeat").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
field.String("machineId").Unique(),
field.String("machineId").
Unique().
Immutable(),
field.String("password").Sensitive(),
field.String("ipAddress"),
field.String("scenarios").MaxLen(100000).Optional(),
@ -36,9 +39,23 @@ func (Machine) Fields() []ent.Field {
Default(false),
field.String("status").Optional(),
field.String("auth_type").Default(types.PasswordAuthType).StructTag(`json:"auth_type"`),
field.String("osname").Optional(),
field.String("osversion").Optional(),
field.String("featureflags").Optional(),
field.JSON("hubstate", &models.HubItems{}).Optional(),
}
}
//type HubItemState struct {
// Version string `json:"version"`
// Status string `json:"status"`
//}
//
//type HubState struct {
// // the key is the FQName (type:author/name)
// Items map[string]HubItemState `json:"hub_items"`
//}
// Edges of the Machine.
func (Machine) Edges() []ent.Edge {
return []ent.Edge{

View file

@ -17,11 +17,10 @@ type Meta struct {
func (Meta) Fields() []ent.Field {
return []ent.Field{
field.Time("created_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
Default(types.UtcNow),
field.Time("updated_at").
Default(types.UtcNow).
UpdateDefault(types.UtcNow).Nillable().Optional(),
UpdateDefault(types.UtcNow),
field.String("key"),
field.String("value").MaxLen(4095),
field.Int("alert_metas").Optional(),

View file

@ -0,0 +1,53 @@
package schema
import (
"entgo.io/ent"
"entgo.io/ent/schema/field"
"entgo.io/ent/schema/index"
)
// Metric is actually a set of metrics collected by a device (logprocessor, bouncer, etc) at a given time.
type Metric struct {
ent.Schema
}
// TODO:
// respect unique index on (generated_type, generated_by, collected_at)
// when we send, set pushed_at
// housekeeping: retention period wrt collected_at?
// do we blindly trust collected_at? refuse if too old? refuse if too much in the future?
// Fields of the Machine.
func (Metric) Fields() []ent.Field {
return []ent.Field{
// XXX: type tout court?
field.Enum("generated_type").
Values("LP", "RC").
Immutable().
Comment("Type of the metrics source: LP=logprocessor, RC=remediation"),
field.String("generated_by").
Immutable().
Comment("Source of the metrics: machine id, bouncer name...\nIt must come from the auth middleware."),
field.Time("collected_at").
Immutable().
Comment("When the metrics are collected/calculated at the source"),
field.Time("pushed_at").
Nillable().
Optional().
Comment("When the metrics are sent to the console"),
// Can we have a json/jsonbb field? with two different schemas?
field.String("payload").
Immutable().
Comment("The actual metrics (item0)"),
}
}
func (Metric) Indexes() []ent.Index {
return []ent.Index{
// Don't store the same metrics multiple times.
index.Fields("generated_type", "generated_by", "collected_at").
Unique(),
}
// XXX: we happy with the generated index name?
}

View file

@ -28,6 +28,8 @@ type Tx struct {
Machine *MachineClient
// Meta is the client for interacting with the Meta builders.
Meta *MetaClient
// Metric is the client for interacting with the Metric builders.
Metric *MetricClient
// lazily loaded.
client *Client
@ -167,6 +169,7 @@ func (tx *Tx) init() {
tx.Lock = NewLockClient(tx.config)
tx.Machine = NewMachineClient(tx.config)
tx.Meta = NewMetaClient(tx.config)
tx.Metric = NewMetricClient(tx.config)
}
// txDriver wraps the given dialect.Tx with a nop dialect.Driver implementation.

View file

@ -7,15 +7,24 @@ import (
"github.com/go-co-op/gocron"
log "github.com/sirupsen/logrus"
"github.com/crowdsecurity/go-cs-lib/ptr"
"github.com/crowdsecurity/crowdsec/pkg/csconfig"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/alert"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/bouncer"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/decision"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/event"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
"github.com/crowdsecurity/crowdsec/pkg/types"
)
const (
// how long to keep metrics in the local database
defaultMetricsMaxAge = 7 * 24 * time.Hour
flushInterval = 1 * time.Minute
)
func (c *Client) StartFlushScheduler(config *csconfig.FlushDBCfg) (*gocron.Scheduler, error) {
maxItems := 0
@ -32,7 +41,7 @@ func (c *Client) StartFlushScheduler(config *csconfig.FlushDBCfg) (*gocron.Sched
// Init & Start cronjob every minute for alerts
scheduler := gocron.NewScheduler(time.UTC)
job, err := scheduler.Every(1).Minute().Do(c.FlushAlerts, maxAge, maxItems)
job, err := scheduler.Every(flushInterval).Do(c.FlushAlerts, maxAge, maxItems)
if err != nil {
return nil, fmt.Errorf("while starting FlushAlerts scheduler: %w", err)
}
@ -77,17 +86,45 @@ func (c *Client) StartFlushScheduler(config *csconfig.FlushDBCfg) (*gocron.Sched
log.Warning("bouncers auto-delete for login/password auth is not supported (use cert or api)")
}
}
baJob, err := scheduler.Every(1).Minute().Do(c.FlushAgentsAndBouncers, config.AgentsGC, config.BouncersGC)
baJob, err := scheduler.Every(flushInterval).Do(c.FlushAgentsAndBouncers, config.AgentsGC, config.BouncersGC)
if err != nil {
return nil, fmt.Errorf("while starting FlushAgentsAndBouncers scheduler: %w", err)
}
baJob.SingletonMode()
metricsJob, err := scheduler.Every(flushInterval).Do(c.flushMetrics, config.MetricsMaxAge)
if err != nil {
return nil, fmt.Errorf("while starting flushMetrics scheduler: %w", err)
}
metricsJob.SingletonMode()
scheduler.StartAsync()
return scheduler, nil
}
// flushMetrics deletes metrics older than maxAge, regardless if they have been pushed to CAPI or not
func (c *Client) flushMetrics(maxAge *time.Duration) {
if maxAge == nil {
maxAge = ptr.Of(defaultMetricsMaxAge)
}
c.Log.Debugf("flushing metrics older than %s", maxAge)
deleted, err := c.Ent.Metric.Delete().Where(
metric.CollectedAtLTE(time.Now().UTC().Add(-*maxAge)),
).Exec(c.CTX)
if err != nil {
c.Log.Errorf("while flushing metrics: %s", err)
return
}
if deleted > 0 {
c.Log.Debugf("flushed %d metrics snapshots", deleted)
}
}
func (c *Client) FlushOrphans() {
/* While it has only been linked to some very corner-case bug : https://github.com/crowdsecurity/crowdsec/issues/778 */

View file

@ -2,12 +2,14 @@ package database
import (
"fmt"
"strings"
"time"
"github.com/go-openapi/strfmt"
"github.com/pkg/errors"
"golang.org/x/crypto/bcrypt"
"github.com/crowdsecurity/crowdsec/pkg/models"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/machine"
"github.com/crowdsecurity/crowdsec/pkg/types"
@ -16,6 +18,29 @@ import (
const CapiMachineID = types.CAPIOrigin
const CapiListsMachineID = types.ListOrigin
func (c *Client) MachineUpdateBaseMetrics(machineID string, baseMetrics *models.BaseMetrics, hubItems *models.HubItems) error {
os := baseMetrics.Os
features := strings.Join(baseMetrics.FeatureFlags, ",")
heartbeat := time.Unix(baseMetrics.Meta.UtcNowTimestamp, 0)
_, err := c.Ent.Machine.
Update().
Where(machine.MachineIdEQ(machineID)).
SetNillableVersion(baseMetrics.Version).
SetOsname(os.Name).
SetOsversion(os.Version).
SetFeatureflags(features).
SetLastHeartbeat(heartbeat).
SetHubstate(hubItems).
// TODO: update scenarios
Save(c.CTX)
if err != nil {
return fmt.Errorf("unable to update base machine metrics in database: %s", err)
}
return nil
}
func (c *Client) CreateMachine(machineID *string, password *strfmt.Password, ipAddress string, isValidated bool, force bool, authType string) (*ent.Machine, error) {
hashPassword, err := bcrypt.GenerateFromPassword([]byte(*password), bcrypt.DefaultCost)
if err != nil {

84
pkg/database/metrics.go Normal file
View file

@ -0,0 +1,84 @@
package database
import (
"fmt"
"time"
"github.com/crowdsecurity/crowdsec/pkg/database/ent"
"github.com/crowdsecurity/crowdsec/pkg/database/ent/metric"
)
// TODO:
// what if they are alrady in the db (should get an error from the unique index)
// CollectMetricsToPush (count limit? including stale?)
// SetPushedMetrics
// RemoveOldMetrics
// avoid errors.Wrapf
func (c *Client) CreateMetric(generatedType metric.GeneratedType, generatedBy string, collectedAt time.Time, payload string) (*ent.Metric, error) {
metric, err := c.Ent.Metric.
Create().
SetGeneratedType(generatedType).
SetGeneratedBy(generatedBy).
SetCollectedAt(collectedAt).
SetPayload(payload).
Save(c.CTX)
switch {
case ent.IsConstraintError(err):
// pretty safe guess, it's the unique index
c.Log.Infof("storing metrics snapshot for '%s' at %s: already exists", generatedBy, collectedAt)
// it's polite to accept a duplicate snapshot without any error
return nil, nil
case err != nil:
c.Log.Warningf("CreateMetric: %s", err)
return nil, fmt.Errorf("storing metrics snapshot for '%s' at %s: %w", generatedBy, collectedAt, InsertFail)
}
return metric, nil
}
func (c *Client) GetLPsUsageMetrics() ([]*ent.Metric, error) {
metrics, err := c.Ent.Metric.Query().
Where(
metric.GeneratedTypeEQ(metric.GeneratedTypeLP),
metric.PushedAtIsNil(),
).
Order(ent.Desc(metric.FieldCollectedAt)).
All(c.CTX)
if err != nil {
c.Log.Warningf("GetLPsUsageMetrics: %s", err)
return nil, fmt.Errorf("getting LPs usage metrics: %w", err)
}
return metrics, nil
}
func (c *Client) GetBouncersUsageMetrics() ([]*ent.Metric, error) {
metrics, err := c.Ent.Metric.Query().
Where(
metric.GeneratedTypeEQ(metric.GeneratedTypeRC),
metric.PushedAtIsNil(),
).
Order(ent.Desc(metric.FieldCollectedAt)).
All(c.CTX)
if err != nil {
c.Log.Warningf("GetBouncersUsageMetrics: %s", err)
return nil, fmt.Errorf("getting bouncers usage metrics: %w", err)
}
return metrics, nil
}
func (c *Client) MarkUsageMetricsAsSent(ids []int) error {
_, err := c.Ent.Metric.Update().
Where(metric.IDIn(ids...)).
SetPushedAt(time.Now()).
Save(c.CTX)
if err != nil {
c.Log.Warningf("MarkUsageMetricsAsSent: %s", err)
return fmt.Errorf("marking usage metrics as sent: %w", err)
}
return nil
}

View file

@ -8,6 +8,7 @@ var ChunkedDecisionsStream = &Feature{Name: "chunked_decisions_stream", Descript
var PapiClient = &Feature{Name: "papi_client", Description: "Enable Polling API client", State: DeprecatedState}
var Re2GrokSupport = &Feature{Name: "re2_grok_support", Description: "Enable RE2 support for GROK patterns"}
var Re2RegexpInfileSupport = &Feature{Name: "re2_regexp_in_file_support", Description: "Enable RE2 support for RegexpInFile expr helper"}
var CAPIUsageMetrics = &Feature{Name: "capi_usage_metrics", Description: "Enable usage metrics push to CAPI"}
func RegisterAllFeatures() error {
err := Crowdsec.RegisterFeature(CscliSetup)
@ -40,5 +41,10 @@ func RegisterAllFeatures() error {
return err
}
err = Crowdsec.RegisterFeature(CAPIUsageMetrics)
if err != nil {
return err
}
return nil
}

234
pkg/models/all_metrics.go Normal file
View file

@ -0,0 +1,234 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// AllMetrics AllMetrics
//
// swagger:model AllMetrics
type AllMetrics struct {
// lapi
Lapi *LapiMetrics `json:"lapi,omitempty"`
// log processors metrics
LogProcessors []*LogProcessorsMetrics `json:"log_processors"`
// remediation components metrics
RemediationComponents []*RemediationComponentsMetrics `json:"remediation_components"`
}
// Validate validates this all metrics
func (m *AllMetrics) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateLapi(formats); err != nil {
res = append(res, err)
}
if err := m.validateLogProcessors(formats); err != nil {
res = append(res, err)
}
if err := m.validateRemediationComponents(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AllMetrics) validateLapi(formats strfmt.Registry) error {
if swag.IsZero(m.Lapi) { // not required
return nil
}
if m.Lapi != nil {
if err := m.Lapi.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("lapi")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("lapi")
}
return err
}
}
return nil
}
func (m *AllMetrics) validateLogProcessors(formats strfmt.Registry) error {
if swag.IsZero(m.LogProcessors) { // not required
return nil
}
for i := 0; i < len(m.LogProcessors); i++ {
if swag.IsZero(m.LogProcessors[i]) { // not required
continue
}
if m.LogProcessors[i] != nil {
if err := m.LogProcessors[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("log_processors" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("log_processors" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *AllMetrics) validateRemediationComponents(formats strfmt.Registry) error {
if swag.IsZero(m.RemediationComponents) { // not required
return nil
}
for i := 0; i < len(m.RemediationComponents); i++ {
if swag.IsZero(m.RemediationComponents[i]) { // not required
continue
}
if m.RemediationComponents[i] != nil {
if err := m.RemediationComponents[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("remediation_components" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("remediation_components" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// ContextValidate validate this all metrics based on the context it is used
func (m *AllMetrics) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateLapi(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateLogProcessors(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateRemediationComponents(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *AllMetrics) contextValidateLapi(ctx context.Context, formats strfmt.Registry) error {
if m.Lapi != nil {
if swag.IsZero(m.Lapi) { // not required
return nil
}
if err := m.Lapi.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("lapi")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("lapi")
}
return err
}
}
return nil
}
func (m *AllMetrics) contextValidateLogProcessors(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.LogProcessors); i++ {
if m.LogProcessors[i] != nil {
if swag.IsZero(m.LogProcessors[i]) { // not required
return nil
}
if err := m.LogProcessors[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("log_processors" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("log_processors" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *AllMetrics) contextValidateRemediationComponents(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.RemediationComponents); i++ {
if m.RemediationComponents[i] != nil {
if swag.IsZero(m.RemediationComponents[i]) { // not required
return nil
}
if err := m.RemediationComponents[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("remediation_components" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("remediation_components" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
// MarshalBinary interface implementation
func (m *AllMetrics) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *AllMetrics) UnmarshalBinary(b []byte) error {
var res AllMetrics
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

240
pkg/models/base_metrics.go Normal file
View file

@ -0,0 +1,240 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"strconv"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// BaseMetrics BaseMetrics
//
// swagger:model BaseMetrics
type BaseMetrics struct {
// feature flags (expected to be empty for remediation components)
FeatureFlags []string `json:"feature_flags"`
// metrics meta
// Required: true
Meta *MetricsMeta `json:"meta"`
// metrics details
Metrics []*MetricsDetailItem `json:"metrics"`
// OS information
// Required: true
Os *OSversion `json:"os"`
// version of the remediation component
// Required: true
Version *string `json:"version"`
}
// Validate validates this base metrics
func (m *BaseMetrics) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateMeta(formats); err != nil {
res = append(res, err)
}
if err := m.validateMetrics(formats); err != nil {
res = append(res, err)
}
if err := m.validateOs(formats); err != nil {
res = append(res, err)
}
if err := m.validateVersion(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *BaseMetrics) validateMeta(formats strfmt.Registry) error {
if err := validate.Required("meta", "body", m.Meta); err != nil {
return err
}
if m.Meta != nil {
if err := m.Meta.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("meta")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("meta")
}
return err
}
}
return nil
}
func (m *BaseMetrics) validateMetrics(formats strfmt.Registry) error {
if swag.IsZero(m.Metrics) { // not required
return nil
}
for i := 0; i < len(m.Metrics); i++ {
if swag.IsZero(m.Metrics[i]) { // not required
continue
}
if m.Metrics[i] != nil {
if err := m.Metrics[i].Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("metrics" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("metrics" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *BaseMetrics) validateOs(formats strfmt.Registry) error {
if err := validate.Required("os", "body", m.Os); err != nil {
return err
}
if m.Os != nil {
if err := m.Os.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("os")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("os")
}
return err
}
}
return nil
}
func (m *BaseMetrics) validateVersion(formats strfmt.Registry) error {
if err := validate.Required("version", "body", m.Version); err != nil {
return err
}
return nil
}
// ContextValidate validate this base metrics based on the context it is used
func (m *BaseMetrics) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateMeta(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateMetrics(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateOs(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *BaseMetrics) contextValidateMeta(ctx context.Context, formats strfmt.Registry) error {
if m.Meta != nil {
if err := m.Meta.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("meta")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("meta")
}
return err
}
}
return nil
}
func (m *BaseMetrics) contextValidateMetrics(ctx context.Context, formats strfmt.Registry) error {
for i := 0; i < len(m.Metrics); i++ {
if m.Metrics[i] != nil {
if swag.IsZero(m.Metrics[i]) { // not required
return nil
}
if err := m.Metrics[i].ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("metrics" + "." + strconv.Itoa(i))
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("metrics" + "." + strconv.Itoa(i))
}
return err
}
}
}
return nil
}
func (m *BaseMetrics) contextValidateOs(ctx context.Context, formats strfmt.Registry) error {
if m.Os != nil {
if err := m.Os.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("os")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("os")
}
return err
}
}
return nil
}
// MarshalBinary interface implementation
func (m *BaseMetrics) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *BaseMetrics) UnmarshalBinary(b []byte) error {
var res BaseMetrics
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -0,0 +1,27 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
)
// ConsoleOptions ConsoleOptions
//
// swagger:model ConsoleOptions
type ConsoleOptions []string
// Validate validates this console options
func (m ConsoleOptions) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this console options based on context it is used
func (m ConsoleOptions) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}

53
pkg/models/hub_item.go Normal file
View file

@ -0,0 +1,53 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// HubItem HubItem
//
// swagger:model HubItem
type HubItem struct {
// status of the hub item (official, custom, tainted, etc.)
Status string `json:"status,omitempty"`
// version of the hub item
Version string `json:"version,omitempty"`
}
// Validate validates this hub item
func (m *HubItem) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this hub item based on context it is used
func (m *HubItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *HubItem) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *HubItem) UnmarshalBinary(b []byte) error {
var res HubItem
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

67
pkg/models/hub_items.go Normal file
View file

@ -0,0 +1,67 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/validate"
)
// HubItems HubItems
//
// swagger:model HubItems
type HubItems map[string]HubItem
// Validate validates this hub items
func (m HubItems) Validate(formats strfmt.Registry) error {
var res []error
for k := range m {
if err := validate.Required(k, "body", m[k]); err != nil {
return err
}
if val, ok := m[k]; ok {
if err := val.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName(k)
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName(k)
}
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this hub items based on the context it is used
func (m HubItems) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
for k := range m {
if val, ok := m[k]; ok {
if err := val.ContextValidate(ctx, formats); err != nil {
return err
}
}
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}

157
pkg/models/lapi_metrics.go Normal file
View file

@ -0,0 +1,157 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// LapiMetrics LapiMetrics
//
// swagger:model LapiMetrics
type LapiMetrics struct {
BaseMetrics
// console options
ConsoleOptions ConsoleOptions `json:"console_options,omitempty"`
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *LapiMetrics) UnmarshalJSON(raw []byte) error {
// AO0
var aO0 BaseMetrics
if err := swag.ReadJSON(raw, &aO0); err != nil {
return err
}
m.BaseMetrics = aO0
// AO1
var dataAO1 struct {
ConsoleOptions ConsoleOptions `json:"console_options,omitempty"`
}
if err := swag.ReadJSON(raw, &dataAO1); err != nil {
return err
}
m.ConsoleOptions = dataAO1.ConsoleOptions
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m LapiMetrics) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
aO0, err := swag.WriteJSON(m.BaseMetrics)
if err != nil {
return nil, err
}
_parts = append(_parts, aO0)
var dataAO1 struct {
ConsoleOptions ConsoleOptions `json:"console_options,omitempty"`
}
dataAO1.ConsoleOptions = m.ConsoleOptions
jsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)
if errAO1 != nil {
return nil, errAO1
}
_parts = append(_parts, jsonDataAO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this lapi metrics
func (m *LapiMetrics) Validate(formats strfmt.Registry) error {
var res []error
// validation for a type composition with BaseMetrics
if err := m.BaseMetrics.Validate(formats); err != nil {
res = append(res, err)
}
if err := m.validateConsoleOptions(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *LapiMetrics) validateConsoleOptions(formats strfmt.Registry) error {
if swag.IsZero(m.ConsoleOptions) { // not required
return nil
}
if err := m.ConsoleOptions.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("console_options")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("console_options")
}
return err
}
return nil
}
// ContextValidate validate this lapi metrics based on the context it is used
func (m *LapiMetrics) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
// validation for a type composition with BaseMetrics
if err := m.BaseMetrics.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateConsoleOptions(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *LapiMetrics) contextValidateConsoleOptions(ctx context.Context, formats strfmt.Registry) error {
if err := m.ConsoleOptions.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("console_options")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("console_options")
}
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *LapiMetrics) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *LapiMetrics) UnmarshalBinary(b []byte) error {
var res LapiMetrics
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -684,6 +684,36 @@ paths:
$ref: "#/definitions/ErrorResponse"
security:
- JWTAuthorizer: []
/usage-metrics:
post:
description: Post usage metrics from a LP or a bouncer
summary: Send usage metrics
tags:
- bouncers
- watchers
operationId: usage-metrics
produces:
- application/json
parameters:
- name: body
in: body
required: true
schema:
$ref: '#/definitions/AllMetrics'
description: 'All metrics'
responses:
'200':
description: successful operation
schema:
$ref: '#/definitions/SuccessResponse'
headers: {}
'400':
description: "400 response"
schema:
$ref: "#/definitions/ErrorResponse"
security:
- APIKeyAuthorizer: []
- JWTAuthorizer: []
definitions:
WatcherRegistrationRequest:
title: WatcherRegistrationRequest
@ -994,6 +1024,168 @@ definitions:
type: string
value:
type: string
RemediationComponentsMetrics:
title: RemediationComponentsMetrics
type: object
allOf:
- $ref: '#/definitions/BaseMetrics'
- properties:
type:
type: string
description: type of the remediation component
name:
type: string
description: name of the remediation component
last_pull:
type: integer
description: last pull date
LogProcessorsMetrics:
title: LogProcessorsMetrics
type: object
allOf:
- $ref: '#/definitions/BaseMetrics'
- properties:
console_options:
$ref: '#/definitions/ConsoleOptions'
hub_items:
$ref: '#/definitions/HubItems'
datasources:
type: object
description: Number of datasources per type
additionalProperties:
type: integer
name:
type: string
description: name of the log processor
last_push:
type: integer
description: last push date
last_update:
type: integer
description: last update date
LapiMetrics:
title: LapiMetrics
type: object
allOf:
- $ref: '#/definitions/BaseMetrics'
- properties:
console_options:
$ref: '#/definitions/ConsoleOptions'
AllMetrics:
title: AllMetrics
type: object
properties:
remediation_components:
type: array
items:
$ref: '#/definitions/RemediationComponentsMetrics'
description: remediation components metrics
log_processors:
type: array
items:
$ref: '#/definitions/LogProcessorsMetrics'
description: log processors metrics
lapi:
$ref: '#/definitions/LapiMetrics'
BaseMetrics:
title: BaseMetrics
type: object
properties:
version:
type: string
description: version of the remediation component
meta:
type: object
$ref: '#/definitions/MetricsMeta'
description: metrics meta
os:
type: object
$ref: '#/definitions/OSversion'
description: OS information
metrics:
type: array
items:
$ref: '#/definitions/MetricsDetailItem'
description: metrics details
feature_flags:
type: array
items:
type: string
description: feature flags (expected to be empty for remediation components)
required:
- version
- os
- meta
OSversion:
title: OSversion
type: object
properties:
name:
type: string
description: name of the OS
version:
type: string
description: version of the OS
MetricsDetailItem:
title: MetricsDetailItem
type: object
properties:
name:
type: string
description: name of the metric
value:
type: number
description: value of the metric
unit:
type: string
description: unit of the metric
labels:
$ref: '#/definitions/MetricsLabels'
description: labels of the metric
required:
- name
- value
- unit
MetricsMeta:
title: MetricsMeta
type: object
properties:
window_size_seconds:
type: integer
description: Size, in seconds, of the window used to compute the metric
utc_startup_timestamp:
type: integer
description: UTC timestamp of the startup of the software
utc_now_timestamp:
type: integer
description: UTC timestamp of the current time
MetricsLabels:
title: MetricsLabels
type: object
additionalProperties:
type: string
description: label of the metric
ConsoleOptions:
title: ConsoleOptions
type: array
items:
type: string
description: enabled console options
HubItems:
title: HubItems
type: object
additionalProperties:
$ref: '#/definitions/HubItem'
HubItem:
title: HubItem
type: object
properties:
version:
type: string
description: version of the hub item
status:
type: string
description: status of the hub item (official, custom, tainted, etc.)
ErrorResponse:
type: "object"
required:
@ -1007,6 +1199,16 @@ definitions:
description: "more detail on individual errors"
title: "error response"
description: "error response return by the API"
SuccessResponse:
type: "object"
required:
- "message"
properties:
message:
type: "string"
description: "message"
title: "success response"
description: "success response return by the API"
tags:
- name: Remediation component
description: 'Operations about decisions : bans, captcha, rate-limit etc.'

View file

@ -0,0 +1,258 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// LogProcessorsMetrics LogProcessorsMetrics
//
// swagger:model LogProcessorsMetrics
type LogProcessorsMetrics struct {
BaseMetrics
// console options
ConsoleOptions ConsoleOptions `json:"console_options,omitempty"`
// Number of datasources per type
Datasources map[string]int64 `json:"datasources,omitempty"`
// hub items
HubItems HubItems `json:"hub_items,omitempty"`
// last push date
LastPush int64 `json:"last_push,omitempty"`
// last update date
LastUpdate int64 `json:"last_update,omitempty"`
// name of the log processor
Name string `json:"name,omitempty"`
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *LogProcessorsMetrics) UnmarshalJSON(raw []byte) error {
// AO0
var aO0 BaseMetrics
if err := swag.ReadJSON(raw, &aO0); err != nil {
return err
}
m.BaseMetrics = aO0
// AO1
var dataAO1 struct {
ConsoleOptions ConsoleOptions `json:"console_options,omitempty"`
Datasources map[string]int64 `json:"datasources,omitempty"`
HubItems HubItems `json:"hub_items,omitempty"`
LastPush int64 `json:"last_push,omitempty"`
LastUpdate int64 `json:"last_update,omitempty"`
Name string `json:"name,omitempty"`
}
if err := swag.ReadJSON(raw, &dataAO1); err != nil {
return err
}
m.ConsoleOptions = dataAO1.ConsoleOptions
m.Datasources = dataAO1.Datasources
m.HubItems = dataAO1.HubItems
m.LastPush = dataAO1.LastPush
m.LastUpdate = dataAO1.LastUpdate
m.Name = dataAO1.Name
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m LogProcessorsMetrics) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
aO0, err := swag.WriteJSON(m.BaseMetrics)
if err != nil {
return nil, err
}
_parts = append(_parts, aO0)
var dataAO1 struct {
ConsoleOptions ConsoleOptions `json:"console_options,omitempty"`
Datasources map[string]int64 `json:"datasources,omitempty"`
HubItems HubItems `json:"hub_items,omitempty"`
LastPush int64 `json:"last_push,omitempty"`
LastUpdate int64 `json:"last_update,omitempty"`
Name string `json:"name,omitempty"`
}
dataAO1.ConsoleOptions = m.ConsoleOptions
dataAO1.Datasources = m.Datasources
dataAO1.HubItems = m.HubItems
dataAO1.LastPush = m.LastPush
dataAO1.LastUpdate = m.LastUpdate
dataAO1.Name = m.Name
jsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)
if errAO1 != nil {
return nil, errAO1
}
_parts = append(_parts, jsonDataAO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this log processors metrics
func (m *LogProcessorsMetrics) Validate(formats strfmt.Registry) error {
var res []error
// validation for a type composition with BaseMetrics
if err := m.BaseMetrics.Validate(formats); err != nil {
res = append(res, err)
}
if err := m.validateConsoleOptions(formats); err != nil {
res = append(res, err)
}
if err := m.validateHubItems(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *LogProcessorsMetrics) validateConsoleOptions(formats strfmt.Registry) error {
if swag.IsZero(m.ConsoleOptions) { // not required
return nil
}
if err := m.ConsoleOptions.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("console_options")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("console_options")
}
return err
}
return nil
}
func (m *LogProcessorsMetrics) validateHubItems(formats strfmt.Registry) error {
if swag.IsZero(m.HubItems) { // not required
return nil
}
if m.HubItems != nil {
if err := m.HubItems.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("hub_items")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("hub_items")
}
return err
}
}
return nil
}
// ContextValidate validate this log processors metrics based on the context it is used
func (m *LogProcessorsMetrics) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
// validation for a type composition with BaseMetrics
if err := m.BaseMetrics.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateConsoleOptions(ctx, formats); err != nil {
res = append(res, err)
}
if err := m.contextValidateHubItems(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *LogProcessorsMetrics) contextValidateConsoleOptions(ctx context.Context, formats strfmt.Registry) error {
if err := m.ConsoleOptions.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("console_options")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("console_options")
}
return err
}
return nil
}
func (m *LogProcessorsMetrics) contextValidateHubItems(ctx context.Context, formats strfmt.Registry) error {
if swag.IsZero(m.HubItems) { // not required
return nil
}
if err := m.HubItems.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("hub_items")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("hub_items")
}
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *LogProcessorsMetrics) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *LogProcessorsMetrics) UnmarshalBinary(b []byte) error {
var res LogProcessorsMetrics
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -0,0 +1,158 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// MetricsDetailItem MetricsDetailItem
//
// swagger:model MetricsDetailItem
type MetricsDetailItem struct {
// labels of the metric
Labels MetricsLabels `json:"labels,omitempty"`
// name of the metric
// Required: true
Name *string `json:"name"`
// unit of the metric
// Required: true
Unit *string `json:"unit"`
// value of the metric
// Required: true
Value *float64 `json:"value"`
}
// Validate validates this metrics detail item
func (m *MetricsDetailItem) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateLabels(formats); err != nil {
res = append(res, err)
}
if err := m.validateName(formats); err != nil {
res = append(res, err)
}
if err := m.validateUnit(formats); err != nil {
res = append(res, err)
}
if err := m.validateValue(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *MetricsDetailItem) validateLabels(formats strfmt.Registry) error {
if swag.IsZero(m.Labels) { // not required
return nil
}
if m.Labels != nil {
if err := m.Labels.Validate(formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("labels")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("labels")
}
return err
}
}
return nil
}
func (m *MetricsDetailItem) validateName(formats strfmt.Registry) error {
if err := validate.Required("name", "body", m.Name); err != nil {
return err
}
return nil
}
func (m *MetricsDetailItem) validateUnit(formats strfmt.Registry) error {
if err := validate.Required("unit", "body", m.Unit); err != nil {
return err
}
return nil
}
func (m *MetricsDetailItem) validateValue(formats strfmt.Registry) error {
if err := validate.Required("value", "body", m.Value); err != nil {
return err
}
return nil
}
// ContextValidate validate this metrics detail item based on the context it is used
func (m *MetricsDetailItem) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
if err := m.contextValidateLabels(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *MetricsDetailItem) contextValidateLabels(ctx context.Context, formats strfmt.Registry) error {
if swag.IsZero(m.Labels) { // not required
return nil
}
if err := m.Labels.ContextValidate(ctx, formats); err != nil {
if ve, ok := err.(*errors.Validation); ok {
return ve.ValidateName("labels")
} else if ce, ok := err.(*errors.CompositeError); ok {
return ce.ValidateName("labels")
}
return err
}
return nil
}
// MarshalBinary interface implementation
func (m *MetricsDetailItem) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *MetricsDetailItem) UnmarshalBinary(b []byte) error {
var res MetricsDetailItem
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -0,0 +1,27 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
)
// MetricsLabels MetricsLabels
//
// swagger:model MetricsLabels
type MetricsLabels map[string]string
// Validate validates this metrics labels
func (m MetricsLabels) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this metrics labels based on context it is used
func (m MetricsLabels) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}

View file

@ -0,0 +1,56 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// MetricsMeta MetricsMeta
//
// swagger:model MetricsMeta
type MetricsMeta struct {
// UTC timestamp of the current time
UtcNowTimestamp int64 `json:"utc_now_timestamp,omitempty"`
// UTC timestamp of the startup of the software
UtcStartupTimestamp int64 `json:"utc_startup_timestamp,omitempty"`
// Size, in seconds, of the window used to compute the metric
WindowSizeSeconds int64 `json:"window_size_seconds,omitempty"`
}
// Validate validates this metrics meta
func (m *MetricsMeta) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this metrics meta based on context it is used
func (m *MetricsMeta) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *MetricsMeta) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *MetricsMeta) UnmarshalBinary(b []byte) error {
var res MetricsMeta
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

53
pkg/models/o_sversion.go Normal file
View file

@ -0,0 +1,53 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// OSversion OSversion
//
// swagger:model OSversion
type OSversion struct {
// name of the OS
Name string `json:"name,omitempty"`
// version of the OS
Version string `json:"version,omitempty"`
}
// Validate validates this o sversion
func (m *OSversion) Validate(formats strfmt.Registry) error {
return nil
}
// ContextValidate validates this o sversion based on context it is used
func (m *OSversion) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *OSversion) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *OSversion) UnmarshalBinary(b []byte) error {
var res OSversion
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -0,0 +1,139 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
)
// RemediationComponentsMetrics RemediationComponentsMetrics
//
// swagger:model RemediationComponentsMetrics
type RemediationComponentsMetrics struct {
BaseMetrics
// last pull date
LastPull int64 `json:"last_pull,omitempty"`
// name of the remediation component
Name string `json:"name,omitempty"`
// type of the remediation component
Type string `json:"type,omitempty"`
}
// UnmarshalJSON unmarshals this object from a JSON structure
func (m *RemediationComponentsMetrics) UnmarshalJSON(raw []byte) error {
// AO0
var aO0 BaseMetrics
if err := swag.ReadJSON(raw, &aO0); err != nil {
return err
}
m.BaseMetrics = aO0
// AO1
var dataAO1 struct {
LastPull int64 `json:"last_pull,omitempty"`
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
}
if err := swag.ReadJSON(raw, &dataAO1); err != nil {
return err
}
m.LastPull = dataAO1.LastPull
m.Name = dataAO1.Name
m.Type = dataAO1.Type
return nil
}
// MarshalJSON marshals this object to a JSON structure
func (m RemediationComponentsMetrics) MarshalJSON() ([]byte, error) {
_parts := make([][]byte, 0, 2)
aO0, err := swag.WriteJSON(m.BaseMetrics)
if err != nil {
return nil, err
}
_parts = append(_parts, aO0)
var dataAO1 struct {
LastPull int64 `json:"last_pull,omitempty"`
Name string `json:"name,omitempty"`
Type string `json:"type,omitempty"`
}
dataAO1.LastPull = m.LastPull
dataAO1.Name = m.Name
dataAO1.Type = m.Type
jsonDataAO1, errAO1 := swag.WriteJSON(dataAO1)
if errAO1 != nil {
return nil, errAO1
}
_parts = append(_parts, jsonDataAO1)
return swag.ConcatJSON(_parts...), nil
}
// Validate validates this remediation components metrics
func (m *RemediationComponentsMetrics) Validate(formats strfmt.Registry) error {
var res []error
// validation for a type composition with BaseMetrics
if err := m.BaseMetrics.Validate(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// ContextValidate validate this remediation components metrics based on the context it is used
func (m *RemediationComponentsMetrics) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
var res []error
// validation for a type composition with BaseMetrics
if err := m.BaseMetrics.ContextValidate(ctx, formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
// MarshalBinary interface implementation
func (m *RemediationComponentsMetrics) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *RemediationComponentsMetrics) UnmarshalBinary(b []byte) error {
var res RemediationComponentsMetrics
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -0,0 +1,73 @@
// Code generated by go-swagger; DO NOT EDIT.
package models
// This file was generated by the swagger tool.
// Editing this file might prove futile when you re-run the swagger generate command
import (
"context"
"github.com/go-openapi/errors"
"github.com/go-openapi/strfmt"
"github.com/go-openapi/swag"
"github.com/go-openapi/validate"
)
// SuccessResponse success response
//
// success response return by the API
//
// swagger:model SuccessResponse
type SuccessResponse struct {
// message
// Required: true
Message *string `json:"message"`
}
// Validate validates this success response
func (m *SuccessResponse) Validate(formats strfmt.Registry) error {
var res []error
if err := m.validateMessage(formats); err != nil {
res = append(res, err)
}
if len(res) > 0 {
return errors.CompositeValidationError(res...)
}
return nil
}
func (m *SuccessResponse) validateMessage(formats strfmt.Registry) error {
if err := validate.Required("message", "body", m.Message); err != nil {
return err
}
return nil
}
// ContextValidate validates this success response based on context it is used
func (m *SuccessResponse) ContextValidate(ctx context.Context, formats strfmt.Registry) error {
return nil
}
// MarshalBinary interface implementation
func (m *SuccessResponse) MarshalBinary() ([]byte, error) {
if m == nil {
return nil, nil
}
return swag.WriteJSON(m)
}
// UnmarshalBinary interface implementation
func (m *SuccessResponse) UnmarshalBinary(b []byte) error {
var res SuccessResponse
if err := swag.ReadJSON(b, &res); err != nil {
return err
}
*m = res
return nil
}

View file

@ -66,7 +66,7 @@ teardown() {
}
@test "simulate one bouncer request with a valid cert" {
rune -0 curl -s --cert "${tmpdir}/bouncer.pem" --key "${tmpdir}/bouncer-key.pem" --cacert "${tmpdir}/bundle.pem" https://localhost:8080/v1/decisions\?ip=42.42.42.42
rune -0 curl -f -s --cert "${tmpdir}/bouncer.pem" --key "${tmpdir}/bouncer-key.pem" --cacert "${tmpdir}/bundle.pem" https://localhost:8080/v1/decisions\?ip=42.42.42.42
assert_output "null"
rune -0 cscli bouncers list -o json
rune -0 jq '. | length' <(output)

View file

@ -104,3 +104,40 @@ teardown() {
rune -0 cscli machines prune
assert_output 'No machines to prune.'
}
@test "usage metrics" {
# a registered log processor can send metrics for the console
token=$(lp_login)
usage_metrics="http://localhost:8080/v1/usage-metrics"
payload=$(cat <<-EOT
remediation_components: []
log_processors:
-
- version: "v1.0"
feature_flags:
- marshmallows
meta:
window_size_seconds: 600
utc_startup_timestamp: 1707399316
utc_now_timestamp: 1707485349
os:
name: CentOS
version: "8"
metrics:
- name: logs_parsed
value: 5000
unit: count
labels: {}
console_options:
- share_context
datasources:
syslog: 1
file: 4
EOT
)
echo -e "$payload" >/tmp/bbb
rune -0 curl -f -sS -H "Authorization: Bearer ${token}" -X POST "$usage_metrics" --data "$(echo "$payload" | yq -o j)"
refute_output
}

View file

@ -24,7 +24,7 @@ setup() {
api() {
URI="$1"
curl -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
curl -f -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
}
#----------

View file

@ -24,7 +24,7 @@ setup() {
api() {
URI="$1"
curl -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
curl -f -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
}
#----------

View file

@ -24,7 +24,7 @@ setup() {
api() {
URI="$1"
curl -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
curl -f -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
}
#----------

View file

@ -24,7 +24,7 @@ setup() {
api() {
URI="$1"
curl -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
curl -f -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
}
#----------

View file

@ -26,7 +26,7 @@ setup() {
api() {
URI="$1"
curl -s -H "X-Api-Key:${API_KEY}" "${CROWDSEC_API_URL}${URI}"
curl -f -s -H "X-Api-Key:${API_KEY}" "${CROWDSEC_API_URL}${URI}"
}
output_new_decisions() {

View file

@ -25,7 +25,7 @@ setup() {
api() {
URI="$1"
curl -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
curl -f -s -H "X-Api-Key: ${API_KEY}" "${CROWDSEC_API_URL}${URI}"
}
@test "adding decisions for multiple scopes" {

Some files were not shown because too many files have changed in this diff Show more