Skip to content

SigNoz is an open-source, OpenTelemetry-native observability platform for your team and their AI agents. Get logs, metrics, and traces in one tool with features like APM, distributed tracing, log management, infra monitoring, etc. Combined with SigNoz MCP and a native AI teammate (in SigNoz Cloud) it helps you build more resilient apps.

fix: support orgId and postgres in agents (#7327)

Nityananda Gohain84553494593d
diff --git a/ee/query-service/app/server.go b/ee/query-service/app/server.go
index 1ba66fdff1..9cb7190af2 100644
--- a/ee/query-service/app/server.go
+++ b/ee/query-service/app/server.go
@@ -122,10 +122,7 @@ func NewServer(serverOptions *ServerOptions) (*Server, error) {
}
// initiate opamp
- _, err = opAmpModel.InitDB(serverOptions.SigNoz.SQLStore.SQLxDB())
- if err != nil {
- return nil, err
- }
+ opAmpModel.InitDB(serverOptions.SigNoz.SQLStore, serverOptions.SigNoz.Instrumentation.Logger(), serverOptions.SigNoz.Modules.OrgGetter)
integrationsController, err := integrations.NewController(serverOptions.SigNoz.SQLStore)
if err != nil {
@@ -143,7 +140,8 @@ func NewServer(serverOptions *ServerOptions) (*Server, error) {
// ingestion pipelines manager
logParsingPipelineController, err := logparsingpipeline.NewLogParsingPipelinesController(
- serverOptions.SigNoz.SQLStore, integrationsController.GetPipelinesForInstalledIntegrations,
+ serverOptions.SigNoz.SQLStore,
+ integrationsController.GetPipelinesForInstalledIntegrations,
)
if err != nil {
return nil, err
@@ -151,7 +149,7 @@ func NewServer(serverOptions *ServerOptions) (*Server, error) {
// initiate agent config handler
agentConfMgr, err := agentConf.Initiate(&agentConf.ManagerOptions{
- DB: serverOptions.SigNoz.SQLStore.SQLxDB(),
+ Store: serverOptions.SigNoz.SQLStore,
AgentFeatures: []agentConf.AgentFeature{logParsingPipelineController},
})
if err != nil {
diff --git a/ee/sqlstore/postgressqlstore/dialect.go b/ee/sqlstore/postgressqlstore/dialect.go
index 7edd48dd67..4f6987bda7 100644
--- a/ee/sqlstore/postgressqlstore/dialect.go
+++ b/ee/sqlstore/postgressqlstore/dialect.go
@@ -17,19 +17,21 @@ var (
)
var (
- Org = "org"
- User = "user"
- UserNoCascade = "user_no_cascade"
- FactorPassword = "factor_password"
- CloudIntegration = "cloud_integration"
+ Org = "org"
+ User = "user"
+ UserNoCascade = "user_no_cascade"
+ FactorPassword = "factor_password"
+ CloudIntegration = "cloud_integration"
+ AgentConfigVersion = "agent_config_version"
)
var (
- OrgReference = `("org_id") REFERENCES "organizations" ("id")`
- UserReference = `("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE`
- UserReferenceNoCascade = `("user_id") REFERENCES "users" ("id")`
- FactorPasswordReference = `("password_id") REFERENCES "factor_password" ("id")`
- CloudIntegrationReference = `("cloud_integration_id") REFERENCES "cloud_integration" ("id") ON DELETE CASCADE`
+ OrgReference = `("org_id") REFERENCES "organizations" ("id")`
+ UserReference = `("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE`
+ UserReferenceNoCascade = `("user_id") REFERENCES "users" ("id")`
+ FactorPasswordReference = `("password_id") REFERENCES "factor_password" ("id")`
+ CloudIntegrationReference = `("cloud_integration_id") REFERENCES "cloud_integration" ("id") ON DELETE CASCADE`
+ AgentConfigVersionReference = `("version_id") REFERENCES "agent_config_version" ("id")`
)
type dialect struct{}
@@ -274,6 +276,8 @@ func (dialect *dialect) RenameTableAndModifyModel(ctx context.Context, bun bun.I
fkReferences = append(fkReferences, FactorPasswordReference)
} else if reference == CloudIntegration && !slices.Contains(fkReferences, CloudIntegrationReference) {
fkReferences = append(fkReferences, CloudIntegrationReference)
+ } else if reference == AgentConfigVersion && !slices.Contains(fkReferences, AgentConfigVersionReference) {
+ fkReferences = append(fkReferences, AgentConfigVersionReference)
}
}
diff --git a/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/testUtils.ts b/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/testUtils.ts
index 900cb4f12d..9a9fbf7186 100644
--- a/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/testUtils.ts
+++ b/frontend/src/container/PipelinePage/Layouts/ChangeHistory/tests/testUtils.ts
@@ -9,7 +9,7 @@ export const pipelineData: Pipeline = {
active: false,
is_valid: false,
disabled: false,
- deployStatus: 'DEPLOYED',
+ deployStatus: 'deployed',
deployResult: 'Deployment was successful',
lastHash: 'log_pipelines:24',
lastConf: 'oiwernveroi',
@@ -135,7 +135,7 @@ export const pipelineData: Pipeline = {
active: false,
isValid: false,
disabled: false,
- deployStatus: 'DEPLOYED',
+ deployStatus: 'deployed',
deployResult: 'Deployment was successful',
lastHash: 'log_pipelines:24',
lastConf: 'eovineroiv',
@@ -150,7 +150,7 @@ export const pipelineData: Pipeline = {
active: false,
isValid: false,
disabled: false,
- deployStatus: 'DEPLOYED',
+ deployStatus: 'deployed',
deployResult: 'Deployment was successful',
lastHash: 'log_pipelines:23',
lastConf: 'eivrounreovi',
@@ -169,7 +169,7 @@ export const pipelineDataHistory: Pipeline['history'] = [
active: false,
isValid: false,
disabled: false,
- deployStatus: 'DEPLOYED',
+ deployStatus: 'deployed',
deployResult: 'Deployment was successful',
lastHash: 'log_pipelines:24',
lastConf: 'eovineroiv',
@@ -184,7 +184,7 @@ export const pipelineDataHistory: Pipeline['history'] = [
active: false,
isValid: false,
disabled: false,
- deployStatus: 'IN_PROGRESS',
+ deployStatus: 'in_progress',
deployResult: 'Deployment is in progress',
lastHash: 'log_pipelines:23',
lastConf: 'eivrounreovi',
@@ -199,7 +199,7 @@ export const pipelineDataHistory: Pipeline['history'] = [
active: false,
isValid: false,
disabled: false,
- deployStatus: 'DIRTY',
+ deployStatus: 'dirty',
deployResult: 'Deployment is dirty',
lastHash: 'log_pipelines:23',
lastConf: 'eivrounreovi',
@@ -214,7 +214,7 @@ export const pipelineDataHistory: Pipeline['history'] = [
active: false,
isValid: false,
disabled: false,
- deployStatus: 'FAILED',
+ deployStatus: 'failed',
deployResult: 'Deployment failed',
lastHash: 'log_pipelines:23',
lastConf: 'eivrounreovi',
@@ -229,7 +229,7 @@ export const pipelineDataHistory: Pipeline['history'] = [
active: false,
isValid: false,
disabled: false,
- deployStatus: 'UNKNOWN',
+ deployStatus: 'unknown',
deployResult: '',
lastHash: 'log_pipelines:23',
lastConf: 'eivrounreovi',
diff --git a/frontend/src/container/PipelinePage/Layouts/ChangeHistory/utils.tsx b/frontend/src/container/PipelinePage/Layouts/ChangeHistory/utils.tsx
index 705796ffbb..dbed15dfaf 100644
--- a/frontend/src/container/PipelinePage/Layouts/ChangeHistory/utils.tsx
+++ b/frontend/src/container/PipelinePage/Layouts/ChangeHistory/utils.tsx
@@ -9,15 +9,15 @@ import { Spin } from 'antd';
export function getDeploymentStage(value: string): string {
switch (value) {
- case 'IN_PROGRESS':
+ case 'in_progress':
return 'In Progress';
- case 'DEPLOYED':
+ case 'deployed':
return 'Deployed';
- case 'DIRTY':
+ case 'dirty':
return 'Dirty';
- case 'FAILED':
+ case 'failed':
return 'Failed';
- case 'UNKNOWN':
+ case 'unknown':
return 'Unknown';
default:
return '';
@@ -26,17 +26,17 @@ export function getDeploymentStage(value: string): string {
export function getDeploymentStageIcon(value: string): JSX.Element {
switch (value) {
- case 'IN_PROGRESS':
+ case 'in_progress':
return (
<Spin indicator={<LoadingOutlined style={{ fontSize: 15 }} spin />} />
);
- case 'DEPLOYED':
+ case 'deployed':
return <CheckCircleFilled />;
- case 'DIRTY':
+ case 'dirty':
return <ExclamationCircleFilled />;
- case 'FAILED':
+ case 'failed':
return <CloseCircleFilled />;
- case 'UNKNOWN':
+ case 'unknown':
return <MinusCircleFilled />;
default:
return <span />;
diff --git a/pkg/query-service/agentConf/agent_features.go b/pkg/query-service/agentConf/agent_features.go
index c0e615a88d..9f68d579b4 100644
--- a/pkg/query-service/agentConf/agent_features.go
+++ b/pkg/query-service/agentConf/agent_features.go
@@ -1,6 +1,10 @@
package agentConf
-import "github.com/SigNoz/signoz/pkg/query-service/model"
+import (
+ "github.com/SigNoz/signoz/pkg/query-service/model"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+)
// Interface for features implemented via agent config.
// Eg: ingestion side signal pre-processing features like log processing pipelines etc
@@ -11,12 +15,13 @@ type AgentFeature interface {
// Recommend config for an agent based on its `currentConfYaml` and
// `configVersion` for the feature's settings
RecommendAgentConfig(
+ orgId valuer.UUID,
currentConfYaml []byte,
- configVersion *ConfigVersion,
+ configVersion *opamptypes.AgentConfigVersion,
) (
recommendedConfYaml []byte,
- // stored as agent_config_versions.last_config in current agentConf model
+ // stored as agent_config_version.config in current agentConf model
// TODO(Raj): maybe refactor agentConf further and clean this up
serializedSettingsUsed string,
diff --git a/pkg/query-service/agentConf/db.go b/pkg/query-service/agentConf/db.go
index f812e2dd6f..511e7f0ef9 100644
--- a/pkg/query-service/agentConf/db.go
+++ b/pkg/query-service/agentConf/db.go
@@ -4,10 +4,14 @@ import (
"context"
"database/sql"
"fmt"
+ "strings"
+ "time"
"github.com/SigNoz/signoz/pkg/query-service/model"
- "github.com/google/uuid"
- "github.com/jmoiron/sqlx"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/pkg/errors"
"go.uber.org/zap"
"golang.org/x/exp/slices"
@@ -15,42 +19,33 @@ import (
// Repo handles DDL and DML ops on ingestion rules
type Repo struct {
- db *sqlx.DB
+ store sqlstore.SQLStore
}
func (r *Repo) GetConfigHistory(
- ctx context.Context, typ ElementTypeDef, limit int,
-) ([]ConfigVersion, *model.ApiError) {
- var c []ConfigVersion
- err := r.db.SelectContext(ctx, &c, fmt.Sprintf(`SELECT
- version,
- id,
- element_type,
- COALESCE(created_by, -1) as created_by,
- created_at,
- COALESCE((SELECT display_name FROM users
- WHERE id = v.created_by), "unknown") created_by_name,
- active,
- is_valid,
- disabled,
- deploy_status,
- deploy_result,
- coalesce(last_hash, '') as last_hash,
- coalesce(last_config, '{}') as last_config
- FROM agent_config_versions AS v
- WHERE element_type = $1
- ORDER BY created_at desc, version desc
- limit %v`, limit),
- typ)
+ ctx context.Context, orgId valuer.UUID, typ opamptypes.ElementType, limit int,
+) ([]opamptypes.AgentConfigVersion, *model.ApiError) {
+ var c []opamptypes.AgentConfigVersion
+ err := r.store.BunDB().NewSelect().
+ Model(&c).
+ ColumnExpr("id, version, element_type, deploy_status, deploy_result, created_at").
+ ColumnExpr("COALESCE(created_by, '') as created_by").
+ ColumnExpr(`COALESCE((SELECT display_name FROM users WHERE users.id = acv.created_by), 'unknown') as created_by_name`).
+ ColumnExpr("COALESCE(hash, '') as hash, COALESCE(config, '{}') as config").
+ Where("acv.element_type = ?", typ).
+ Where("acv.org_id = ?", orgId).
+ OrderExpr("acv.created_at DESC, acv.version DESC").
+ Limit(limit).
+ Scan(ctx)
if err != nil {
return nil, model.InternalError(err)
}
- incompleteStatuses := []DeployStatus{DeployInitiated, Deploying}
+ incompleteStatuses := []opamptypes.DeployStatus{opamptypes.DeployInitiated, opamptypes.Deploying}
for idx := 1; idx < len(c); idx++ {
if slices.Contains(incompleteStatuses, c[idx].DeployStatus) {
- c[idx].DeployStatus = DeployStatusUnknown
+ c[idx].DeployStatus = opamptypes.DeployStatusUnknown
}
}
@@ -58,32 +53,24 @@ func (r *Repo) GetConfigHistory(
}
func (r *Repo) GetConfigVersion(
- ctx context.Context, typ ElementTypeDef, v int,
-) (*ConfigVersion, *model.ApiError) {
- var c ConfigVersion
- err := r.db.GetContext(ctx, &c, `SELECT
- id,
- version,
- element_type,
- COALESCE(created_by, -1) as created_by,
- created_at,
- COALESCE((SELECT display_name FROM users
- WHERE id = v.created_by), "unknown") created_by_name,
- active,
- is_valid,
- disabled,
- deploy_status,
- deploy_result,
- coalesce(last_hash, '') as last_hash,
- coalesce(last_config, '{}') as last_config
- FROM agent_config_versions v
- WHERE element_type = $1
- AND version = $2`, typ, v)
+ ctx context.Context, orgId valuer.UUID, typ opamptypes.ElementType, v int,
+) (*opamptypes.AgentConfigVersion, *model.ApiError) {
+ var c opamptypes.AgentConfigVersion
+ err := r.store.BunDB().NewSelect().
+ Model(&c).
+ ColumnExpr("id, version, element_type, deploy_status, deploy_result, created_at").
+ ColumnExpr("COALESCE(created_by, '') as created_by").
+ ColumnExpr(`COALESCE((SELECT display_name FROM users WHERE users.id = acv.created_by), 'unknown') as created_by_name`).
+ ColumnExpr("COALESCE(hash, '') as hash, COALESCE(config, '{}') as config").
+ Where("acv.element_type = ?", typ).
+ Where("acv.version = ?", v).
+ Where("acv.org_id = ?", orgId).
+ Scan(ctx)
- if err == sql.ErrNoRows {
- return nil, model.NotFoundError(err)
- }
if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, model.NotFoundError(err)
+ }
return nil, model.InternalError(err)
}
@@ -91,33 +78,23 @@ func (r *Repo) GetConfigVersion(
}
func (r *Repo) GetLatestVersion(
- ctx context.Context, typ ElementTypeDef,
-) (*ConfigVersion, *model.ApiError) {
- var c ConfigVersion
- err := r.db.GetContext(ctx, &c, `SELECT
- id,
- version,
- element_type,
- COALESCE(created_by, -1) as created_by,
- created_at,
- COALESCE((SELECT display_name FROM users
- WHERE id = v.created_by), "unknown") created_by_name,
- active,
- is_valid,
- disabled,
- deploy_status,
- deploy_result
- FROM agent_config_versions AS v
- WHERE element_type = $1
- AND version = (
- SELECT MAX(version)
- FROM agent_config_versions
- WHERE element_type=$2)`, typ, typ)
+ ctx context.Context, orgId valuer.UUID, typ opamptypes.ElementType,
+) (*opamptypes.AgentConfigVersion, *model.ApiError) {
+ var c opamptypes.AgentConfigVersion
+ err := r.store.BunDB().NewSelect().
+ Model(&c).
+ ColumnExpr("id, version, element_type, deploy_status, deploy_result, created_at").
+ ColumnExpr("COALESCE(created_by, '') as created_by").
+ ColumnExpr(`COALESCE((SELECT display_name FROM users WHERE users.id = acv.created_by), 'unknown') as created_by_name`).
+ Where("acv.element_type = ?", typ).
+ Where("acv.org_id = ?", orgId).
+ Where("version = (SELECT MAX(version) FROM agent_config_version WHERE acv.element_type = ?)", typ).
+ Scan(ctx)
- if err == sql.ErrNoRows {
- return nil, model.NotFoundError(err)
- }
if err != nil {
+ if errors.Is(err, sql.ErrNoRows) {
+ return nil, model.NotFoundError(err)
+ }
return nil, model.InternalError(err)
}
@@ -125,18 +102,18 @@ func (r *Repo) GetLatestVersion(
}
func (r *Repo) insertConfig(
- ctx context.Context, userId string, c *ConfigVersion, elements []string,
+ ctx context.Context, orgId valuer.UUID, userId valuer.UUID, c *opamptypes.AgentConfigVersion, elements []string,
) (fnerr *model.ApiError) {
- if string(c.ElementType) == "" {
+ if c.ElementType.StringValue() == "" {
return model.BadRequest(fmt.Errorf(
"element type is required for creating agent config version",
))
}
// allowing empty elements for logs - use case is deleting all pipelines
- if len(elements) == 0 && c.ElementType != ElementTypeLogPipelines {
- zap.L().Error("insert config called with no elements ", zap.String("ElementType", string(c.ElementType)))
+ if len(elements) == 0 && c.ElementType != opamptypes.ElementTypeLogPipelines {
+ zap.L().Error("insert config called with no elements ", zap.String("ElementType", c.ElementType.StringValue()))
return model.BadRequest(fmt.Errorf("config must have atleast one element"))
}
@@ -144,20 +121,20 @@ func (r *Repo) insertConfig(
// the version can not be set by the user, we want to auto-assign the versions
// in a monotonically increasing order starting with 1. hence, we reject insert
// requests with version anything other than 0. here, 0 indicates un-assigned
- zap.L().Error("invalid version assignment while inserting agent config", zap.Int("version", c.Version), zap.String("ElementType", string(c.ElementType)))
+ zap.L().Error("invalid version assignment while inserting agent config", zap.Int("version", c.Version), zap.String("ElementType", c.ElementType.StringValue()))
return model.BadRequest(fmt.Errorf(
"user defined versions are not supported in the agent config",
))
}
- configVersion, err := r.GetLatestVersion(ctx, c.ElementType)
+ configVersion, err := r.GetLatestVersion(ctx, orgId, c.ElementType)
if err != nil && err.Type() != model.ErrorNotFound {
zap.L().Error("failed to fetch latest config version", zap.Error(err))
return model.InternalError(fmt.Errorf("failed to fetch latest config version"))
}
if configVersion != nil {
- c.Version = updateVersion(configVersion.Version)
+ c.IncrementVersion(configVersion.Version)
} else {
// first version
c.Version = 1
@@ -166,57 +143,34 @@ func (r *Repo) insertConfig(
defer func() {
if fnerr != nil {
// remove all the damage (invalid rows from db)
- _, _ = r.db.Exec("DELETE FROM agent_config_versions WHERE id = $1", c.ID)
- _, _ = r.db.Exec("DELETE FROM agent_config_elements WHERE version_id=$1", c.ID)
+ r.store.BunDB().NewDelete().Model(new(opamptypes.AgentConfigVersion)).Where("id = ?", c.ID).Where("org_id = ?", orgId).Exec(ctx)
+ r.store.BunDB().NewDelete().Model(new(opamptypes.AgentConfigElement)).Where("version_id = ?", c.ID).Exec(ctx)
}
}()
- // insert config
- configQuery := `INSERT INTO agent_config_versions(
- id,
- version,
- created_by,
- element_type,
- active,
- is_valid,
- disabled,
- deploy_status,
- deploy_result)
- VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)`
-
- _, dbErr := r.db.ExecContext(ctx,
- configQuery,
- c.ID,
- c.Version,
- userId,
- c.ElementType,
- false,
- false,
- false,
- c.DeployStatus,
- c.DeployResult)
+ _, dbErr := r.store.
+ BunDB().
+ NewInsert().
+ Model(c).
+ Exec(ctx)
if dbErr != nil {
zap.L().Error("error in inserting config version: ", zap.Error(dbErr))
return model.InternalError(errors.Wrap(dbErr, "failed to insert ingestion rule"))
}
- elementsQuery := `INSERT INTO agent_config_elements(
- id,
- version_id,
- element_type,
- element_id)
- VALUES ($1, $2, $3, $4)`
-
for _, e := range elements {
- _, dbErr = r.db.ExecContext(
- ctx,
- elementsQuery,
- uuid.NewString(),
- c.ID,
- c.ElementType,
- e,
- )
+ agentConfigElement := &opamptypes.AgentConfigElement{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
+ },
+ VersionID: c.ID,
+ ElementType: c.ElementType.StringValue(),
+ ElementID: e,
+ }
+ _, dbErr = r.store.BunDB().NewInsert().Model(agentConfigElement).Exec(ctx)
if dbErr != nil {
return model.InternalError(dbErr)
}
@@ -226,40 +180,49 @@ func (r *Repo) insertConfig(
}
func (r *Repo) updateDeployStatus(ctx context.Context,
- elementType ElementTypeDef,
+ orgId valuer.UUID,
+ elementType opamptypes.ElementType,
version int,
status string,
result string,
lastHash string,
lastconf string) *model.ApiError {
- updateQuery := `UPDATE agent_config_versions
- set deploy_status = $1,
- deploy_result = $2,
- last_hash = COALESCE($3, last_hash),
- last_config = $4
- WHERE version=$5
- AND element_type = $6`
+ // check if it has org orgID prefix
+ // ensuring it here and also ensuring in coordinator.go
+ if !strings.HasPrefix(lastHash, orgId.String()) {
+ lastHash = orgId.String() + lastHash
+ }
- _, err := r.db.ExecContext(ctx, updateQuery, status, result, lastHash, lastconf, version, string(elementType))
+ _, err := r.store.BunDB().NewUpdate().
+ Model(new(opamptypes.AgentConfigVersion)).
+ Set("deploy_status = ?", status).
+ Set("deploy_result = ?", result).
+ Set("hash = COALESCE(?, hash)", lastHash).
+ Set("config = ?", lastconf).
+ Where("version = ?", version).
+ Where("element_type = ?", elementType).
+ Where("org_id = ?", orgId).
+ Exec(ctx)
if err != nil {
zap.L().Error("failed to update deploy status", zap.Error(err))
- return model.BadRequest(fmt.Errorf("failed to update deploy status"))
+ return model.BadRequest(fmt.Errorf("failed to update deploy status"))
}
return nil
}
func (r *Repo) updateDeployStatusByHash(
- ctx context.Context, confighash string, status string, result string,
+ ctx context.Context, orgId valuer.UUID, confighash string, status string, result string,
) *model.ApiError {
- updateQuery := `UPDATE agent_config_versions
- set deploy_status = $1,
- deploy_result = $2
- WHERE last_hash=$4`
-
- _, err := r.db.ExecContext(ctx, updateQuery, status, result, confighash)
+ _, err := r.store.BunDB().NewUpdate().
+ Model(new(opamptypes.AgentConfigVersion)).
+ Set("deploy_status = ?", status).
+ Set("deploy_result = ?", result).
+ Where("hash = ?", confighash).
+ Where("org_id = ?", orgId).
+ Exec(ctx)
if err != nil {
zap.L().Error("failed to update deploy status", zap.Error(err))
return model.InternalError(errors.Wrap(err, "failed to update deploy status"))
diff --git a/pkg/query-service/agentConf/manager.go b/pkg/query-service/agentConf/manager.go
index ba912a4e49..c69bc49b0e 100644
--- a/pkg/query-service/agentConf/manager.go
+++ b/pkg/query-service/agentConf/manager.go
@@ -12,8 +12,10 @@ import (
filterprocessor "github.com/SigNoz/signoz/pkg/query-service/app/opamp/otelconfig/filterprocessor"
tsp "github.com/SigNoz/signoz/pkg/query-service/app/opamp/otelconfig/tailsampler"
"github.com/SigNoz/signoz/pkg/query-service/model"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/google/uuid"
- "github.com/jmoiron/sqlx"
"github.com/pkg/errors"
"go.uber.org/zap"
yaml "gopkg.in/yaml.v3"
@@ -39,7 +41,7 @@ type Manager struct {
}
type ManagerOptions struct {
- DB *sqlx.DB
+ Store sqlstore.SQLStore
// When acting as opamp.AgentConfigProvider, agent conf recommendations are
// applied to the base conf in the order the features have been specified here.
@@ -60,7 +62,7 @@ func Initiate(options *ManagerOptions) (*Manager, error) {
}
m = &Manager{
- Repo: Repo{options.DB},
+ Repo: Repo{options.Store},
agentFeatures: options.AgentFeatures,
configSubscribers: map[string]func(){},
}
@@ -90,7 +92,7 @@ func (m *Manager) notifyConfigUpdateSubscribers() {
}
// Implements opamp.AgentConfigProvider
-func (m *Manager) RecommendAgentConfig(currentConfYaml []byte) (
+func (m *Manager) RecommendAgentConfig(orgId valuer.UUID, currentConfYaml []byte) (
recommendedConfYaml []byte,
// Opaque id of the recommended config, used for reporting deployment status updates
configId string,
@@ -100,13 +102,13 @@ func (m *Manager) RecommendAgentConfig(currentConfYaml []byte) (
settingVersionsUsed := []string{}
for _, feature := range m.agentFeatures {
- featureType := ElementTypeDef(feature.AgentFeatureType())
- latestConfig, apiErr := GetLatestVersion(context.Background(), featureType)
+ featureType := opamptypes.NewElementType(string(feature.AgentFeatureType()))
+ latestConfig, apiErr := GetLatestVersion(context.Background(), orgId, featureType)
if apiErr != nil && apiErr.Type() != model.ErrorNotFound {
return nil, "", errors.Wrap(apiErr.ToError(), "failed to get latest agent config version")
}
- updatedConf, serializedSettingsUsed, apiErr := feature.RecommendAgentConfig(recommendation, latestConfig)
+ updatedConf, serializedSettingsUsed, apiErr := feature.RecommendAgentConfig(orgId, recommendation, latestConfig)
if apiErr != nil {
return nil, "", errors.Wrap(apiErr.ToError(), fmt.Sprintf(
"failed to generate agent config recommendation for %s", featureType,
@@ -129,9 +131,10 @@ func (m *Manager) RecommendAgentConfig(currentConfYaml []byte) (
_ = m.updateDeployStatus(
context.Background(),
+ orgId,
featureType,
configVersion,
- string(DeployInitiated),
+ opamptypes.DeployInitiated.StringValue(),
"Deployment has started",
configId,
serializedSettingsUsed,
@@ -154,52 +157,53 @@ func (m *Manager) RecommendAgentConfig(currentConfYaml []byte) (
// Implements opamp.AgentConfigProvider
func (m *Manager) ReportConfigDeploymentStatus(
+ orgId valuer.UUID,
agentId string,
configId string,
err error,
) {
featureConfigIds := strings.Split(configId, ",")
for _, featureConfId := range featureConfigIds {
- newStatus := string(Deployed)
+ newStatus := opamptypes.Deployed.StringValue()
message := "Deployment was successful"
if err != nil {
- newStatus = string(DeployFailed)
+ newStatus = opamptypes.DeployFailed.StringValue()
message = fmt.Sprintf("%s: %s", agentId, err.Error())
}
_ = m.updateDeployStatusByHash(
- context.Background(), featureConfId, newStatus, message,
+ context.Background(), orgId, featureConfId, newStatus, message,
)
}
}
func GetLatestVersion(
- ctx context.Context, elementType ElementTypeDef,
-) (*ConfigVersion, *model.ApiError) {
- return m.GetLatestVersion(ctx, elementType)
+ ctx context.Context, orgId valuer.UUID, elementType opamptypes.ElementType,
+) (*opamptypes.AgentConfigVersion, *model.ApiError) {
+ return m.GetLatestVersion(ctx, orgId, elementType)
}
func GetConfigVersion(
- ctx context.Context, elementType ElementTypeDef, version int,
-) (*ConfigVersion, *model.ApiError) {
- return m.GetConfigVersion(ctx, elementType, version)
+ ctx context.Context, orgId valuer.UUID, elementType opamptypes.ElementType, version int,
+) (*opamptypes.AgentConfigVersion, *model.ApiError) {
+ return m.GetConfigVersion(ctx, orgId, elementType, version)
}
func GetConfigHistory(
- ctx context.Context, typ ElementTypeDef, limit int,
-) ([]ConfigVersion, *model.ApiError) {
- return m.GetConfigHistory(ctx, typ, limit)
+ ctx context.Context, orgId valuer.UUID, typ opamptypes.ElementType, limit int,
+) ([]opamptypes.AgentConfigVersion, *model.ApiError) {
+ return m.GetConfigHistory(ctx, orgId, typ, limit)
}
// StartNewVersion launches a new config version for given set of elements
func StartNewVersion(
- ctx context.Context, userId string, eleType ElementTypeDef, elementIds []string,
-) (*ConfigVersion, *model.ApiError) {
+ ctx context.Context, orgId valuer.UUID, userId valuer.UUID, eleType opamptypes.ElementType, elementIds []string,
+) (*opamptypes.AgentConfigVersion, *model.ApiError) {
// create a new version
- cfg := NewConfigVersion(eleType)
+ cfg := opamptypes.NewAgentConfigVersion(orgId, userId, eleType)
// insert new config and elements into database
- err := m.insertConfig(ctx, userId, cfg, elementIds)
+ err := m.insertConfig(ctx, orgId, userId, cfg, elementIds)
if err != nil {
return nil, err
}
@@ -213,22 +217,22 @@ func NotifyConfigUpdate(ctx context.Context) {
m.notifyConfigUpdateSubscribers()
}
-func Redeploy(ctx context.Context, typ ElementTypeDef, version int) *model.ApiError {
+func Redeploy(ctx context.Context, orgId valuer.UUID, typ opamptypes.ElementType, version int) *model.ApiError {
- configVersion, err := GetConfigVersion(ctx, typ, version)
+ configVersion, err := GetConfigVersion(ctx, orgId, typ, version)
if err != nil {
zap.L().Error("failed to fetch config version during redeploy", zap.Error(err))
return model.WrapApiError(err, "failed to fetch details of the config version")
}
- if configVersion == nil || (configVersion != nil && configVersion.LastConf == "") {
+ if configVersion == nil || (configVersion != nil && configVersion.Config == "") {
zap.L().Debug("config version has no conf yaml", zap.Any("configVersion", configVersion))
return model.BadRequest(fmt.Errorf("the config version can not be redeployed"))
}
switch typ {
- case ElementTypeSamplingRules:
+ case opamptypes.ElementTypeSamplingRules:
var config *tsp.Config
- if err := yaml.Unmarshal([]byte(configVersion.LastConf), &config); err != nil {
+ if err := yaml.Unmarshal([]byte(configVersion.Config), &config); err != nil {
zap.L().Debug("failed to read last conf correctly", zap.Error(err))
return model.BadRequest(fmt.Errorf("failed to read the stored config correctly"))
}
@@ -245,10 +249,10 @@ func Redeploy(ctx context.Context, typ ElementTypeDef, version int) *model.ApiEr
return model.InternalError(fmt.Errorf("failed to deploy the config"))
}
- _ = m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, configVersion.LastConf)
- case ElementTypeDropRules:
+ m.updateDeployStatus(ctx, orgId, opamptypes.ElementTypeSamplingRules, version, opamptypes.DeployInitiated.StringValue(), "Deployment started", configHash, configVersion.Config)
+ case opamptypes.ElementTypeDropRules:
var filterConfig *filterprocessor.Config
- if err := yaml.Unmarshal([]byte(configVersion.LastConf), &filterConfig); err != nil {
+ if err := yaml.Unmarshal([]byte(configVersion.Config), &filterConfig); err != nil {
zap.L().Error("failed to read last conf correctly", zap.Error(err))
return model.InternalError(fmt.Errorf("failed to read the stored config correctly"))
}
@@ -263,14 +267,14 @@ func Redeploy(ctx context.Context, typ ElementTypeDef, version int) *model.ApiEr
return err
}
- _ = m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, configVersion.LastConf)
+ m.updateDeployStatus(ctx, orgId, opamptypes.ElementTypeSamplingRules, version, opamptypes.DeployInitiated.StringValue(), "Deployment started", configHash, configVersion.Config)
}
return nil
}
// UpsertFilterProcessor updates the agent config with new filter processor params
-func UpsertFilterProcessor(ctx context.Context, version int, config *filterprocessor.Config) error {
+func UpsertFilterProcessor(ctx context.Context, orgId valuer.UUID, version int, config *filterprocessor.Config) error {
if !atomic.CompareAndSwapUint32(&m.lock, 0, 1) {
return fmt.Errorf("agent updater is busy")
}
@@ -294,7 +298,7 @@ func UpsertFilterProcessor(ctx context.Context, version int, config *filterproce
zap.L().Warn("unexpected error while transforming processor config to yaml", zap.Error(yamlErr))
}
- _ = m.updateDeployStatus(ctx, ElementTypeDropRules, version, string(DeployInitiated), "Deployment started", configHash, string(processorConfYaml))
+ m.updateDeployStatus(ctx, orgId, opamptypes.ElementTypeDropRules, version, opamptypes.DeployInitiated.StringValue(), "Deployment started", configHash, string(processorConfYaml))
return nil
}
@@ -303,9 +307,9 @@ func UpsertFilterProcessor(ctx context.Context, version int, config *filterproce
// successful deployment if no error is received.
// this method is currently expected to be called only once in the lifecycle
// but can be improved in future to accept continuous request status updates from opamp
-func (m *Manager) OnConfigUpdate(agentId string, hash string, err error) {
+func (m *Manager) OnConfigUpdate(orgId valuer.UUID, agentId string, hash string, err error) {
- status := string(Deployed)
+ status := opamptypes.Deployed.StringValue()
message := "Deployment was successful"
@@ -314,15 +318,15 @@ func (m *Manager) OnConfigUpdate(agentId string, hash string, err error) {
}()
if err != nil {
- status = string(DeployFailed)
+ status = opamptypes.DeployFailed.StringValue()
message = fmt.Sprintf("%s: %s", agentId, err.Error())
}
- _ = m.updateDeployStatusByHash(context.Background(), hash, status, message)
+ _ = m.updateDeployStatusByHash(context.Background(), orgId, hash, status, message)
}
// UpsertSamplingProcessor updates the agent config with new filter processor params
-func UpsertSamplingProcessor(ctx context.Context, version int, config *tsp.Config) error {
+func UpsertSamplingProcessor(ctx context.Context, orgId valuer.UUID, version int, config *tsp.Config) error {
if !atomic.CompareAndSwapUint32(&m.lock, 0, 1) {
return fmt.Errorf("agent updater is busy")
}
@@ -345,6 +349,6 @@ func UpsertSamplingProcessor(ctx context.Context, version int, config *tsp.Confi
zap.L().Warn("unexpected error while transforming processor config to yaml", zap.Error(yamlErr))
}
- _ = m.updateDeployStatus(ctx, ElementTypeSamplingRules, version, string(DeployInitiated), "Deployment started", configHash, string(processorConfYaml))
+ m.updateDeployStatus(ctx, orgId, opamptypes.ElementTypeSamplingRules, version, opamptypes.DeployInitiated.StringValue(), "Deployment started", configHash, string(processorConfYaml))
return nil
}
diff --git a/pkg/query-service/agentConf/version.go b/pkg/query-service/agentConf/version.go
deleted file mode 100644
index 73befce781..0000000000
--- a/pkg/query-service/agentConf/version.go
+++ /dev/null
@@ -1,72 +0,0 @@
-package agentConf
-
-import (
- "time"
-
- "github.com/google/uuid"
-)
-
-type ElementTypeDef string
-
-const (
- ElementTypeSamplingRules ElementTypeDef = "sampling_rules"
- ElementTypeDropRules ElementTypeDef = "drop_rules"
- ElementTypeLogPipelines ElementTypeDef = "log_pipelines"
- ElementTypeLbExporter ElementTypeDef = "lb_exporter"
-)
-
-type DeployStatus string
-
-const (
- PendingDeploy DeployStatus = "DIRTY"
- Deploying DeployStatus = "DEPLOYING"
- Deployed DeployStatus = "DEPLOYED"
- DeployInitiated DeployStatus = "IN_PROGRESS"
- DeployFailed DeployStatus = "FAILED"
- DeployStatusUnknown DeployStatus = "UNKNOWN"
-)
-
-type ConfigVersion struct {
- ID string `json:"id" db:"id"`
- Version int `json:"version" db:"version"`
- ElementType ElementTypeDef `json:"elementType" db:"element_type"`
- Active bool `json:"active" db:"active"`
- IsValid bool `json:"is_valid" db:"is_valid"`
- Disabled bool `json:"disabled" db:"disabled"`
-
- DeployStatus DeployStatus `json:"deployStatus" db:"deploy_status"`
- DeployResult string `json:"deployResult" db:"deploy_result"`
-
- LastHash string `json:"lastHash" db:"last_hash"`
- LastConf string `json:"lastConf" db:"last_config"`
-
- CreatedBy string `json:"createdBy" db:"created_by"`
- CreatedByName string `json:"createdByName" db:"created_by_name"`
- CreatedAt time.Time `json:"createdAt" db:"created_at"`
-}
-
-func NewConfigVersion(typeDef ElementTypeDef) *ConfigVersion {
- return &ConfigVersion{
- ID: uuid.NewString(),
- ElementType: typeDef,
- Active: false,
- IsValid: false,
- Disabled: false,
- DeployStatus: PendingDeploy,
- LastHash: "",
- LastConf: "{}",
- // todo: get user id from context?
- // CreatedBy
- }
-}
-
-func updateVersion(v int) int {
- return v + 1
-}
-
-type ConfigElements struct {
- VersionID string
- Version int
- ElementType ElementTypeDef
- ElementId string
-}
diff --git a/pkg/query-service/app/http_handler.go b/pkg/query-service/app/http_handler.go
index 63711c8f7c..d3ca8d47cd 100644
--- a/pkg/query-service/app/http_handler.go
+++ b/pkg/query-service/app/http_handler.go
@@ -63,6 +63,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
"github.com/SigNoz/signoz/pkg/types/licensetypes"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
ruletypes "github.com/SigNoz/signoz/pkg/types/ruletypes"
@@ -3460,10 +3461,9 @@ func (aH *APIHandler) InstallIntegration(w http.ResponseWriter, r *http.Request)
RespondError(w, model.BadRequest(err), nil)
return
}
-
- claims, errv2 := authtypes.ClaimsFromContext(r.Context())
- if errv2 != nil {
- render.Error(w, errv2)
+ claims, err := authtypes.ClaimsFromContext(r.Context())
+ if err != nil {
+ RespondError(w, model.UnauthorizedError(errors.New("unauthorized")), nil)
return
}
@@ -4142,8 +4142,6 @@ func (aH *APIHandler) logAggregate(w http.ResponseWriter, r *http.Request) {
aH.WriteJSON(w, r, res)
}
-const logPipelines = "log_pipelines"
-
func parseAgentConfigVersion(r *http.Request) (int, *model.ApiError) {
versionString := mux.Vars(r)["version"]
@@ -4191,6 +4189,12 @@ func (aH *APIHandler) ListLogsPipelinesHandler(w http.ResponseWriter, r *http.Re
return
}
+ orgID, errv2 := valuer.NewUUID(claims.OrgID)
+ if errv2 != nil {
+ render.Error(w, errv2)
+ return
+ }
+
version, err := parseAgentConfigVersion(r)
if err != nil {
RespondError(w, model.WrapApiError(err, "Failed to parse agent config version"), nil)
@@ -4201,9 +4205,9 @@ func (aH *APIHandler) ListLogsPipelinesHandler(w http.ResponseWriter, r *http.Re
var apierr *model.ApiError
if version != -1 {
- payload, apierr = aH.listLogsPipelinesByVersion(context.Background(), claims.OrgID, version)
+ payload, apierr = aH.listLogsPipelinesByVersion(context.Background(), orgID, version)
} else {
- payload, apierr = aH.listLogsPipelines(context.Background(), claims.OrgID)
+ payload, apierr = aH.listLogsPipelines(context.Background(), orgID)
}
if apierr != nil {
@@ -4214,12 +4218,12 @@ func (aH *APIHandler) ListLogsPipelinesHandler(w http.ResponseWriter, r *http.Re
}
// listLogsPipelines lists logs piplines for latest version
-func (aH *APIHandler) listLogsPipelines(ctx context.Context, orgID string) (
+func (aH *APIHandler) listLogsPipelines(ctx context.Context, orgID valuer.UUID) (
*logparsingpipeline.PipelinesResponse, *model.ApiError,
) {
// get lateset agent config
latestVersion := -1
- lastestConfig, err := agentConf.GetLatestVersion(ctx, logPipelines)
+ lastestConfig, err := agentConf.GetLatestVersion(ctx, orgID, opamptypes.ElementTypeLogPipelines)
if err != nil && err.Type() != model.ErrorNotFound {
return nil, model.WrapApiError(err, "failed to get latest agent config version")
}
@@ -4228,14 +4232,14 @@ func (aH *APIHandler) listLogsPipelines(ctx context.Context, orgID string) (
latestVersion = lastestConfig.Version
}
- payload, err := aH.LogsParsingPipelineController.GetPipelinesByVersion(ctx, latestVersion)
+ payload, err := aH.LogsParsingPipelineController.GetPipelinesByVersion(ctx, orgID, latestVersion)
if err != nil {
return nil, model.WrapApiError(err, "failed to get pipelines")
}
// todo(Nitya): make a new API for history pagination
limit := 10
- history, err := agentConf.GetConfigHistory(ctx, logPipelines, limit)
+ history, err := agentConf.GetConfigHistory(ctx, orgID, opamptypes.ElementTypeLogPipelines, limit)
if err != nil {
return nil, model.WrapApiError(err, "failed to get config history")
}
@@ -4244,17 +4248,17 @@ func (aH *APIHandler) listLogsPipelines(ctx context.Context, orgID string) (
}
// listLogsPipelinesByVersion lists pipelines along with config version history
-func (aH *APIHandler) listLogsPipelinesByVersion(ctx context.Context, orgID string, version int) (
+func (aH *APIHandler) listLogsPipelinesByVersion(ctx context.Context, orgID valuer.UUID, version int) (
*logparsingpipeline.PipelinesResponse, *model.ApiError,
) {
- payload, err := aH.LogsParsingPipelineController.GetPipelinesByVersion(ctx, version)
+ payload, err := aH.LogsParsingPipelineController.GetPipelinesByVersion(ctx, orgID, version)
if err != nil {
return nil, model.WrapApiError(err, "failed to get pipelines by version")
}
// todo(Nitya): make a new API for history pagination
limit := 10
- history, err := agentConf.GetConfigHistory(ctx, logPipelines, limit)
+ history, err := agentConf.GetConfigHistory(ctx, orgID, opamptypes.ElementTypeLogPipelines, limit)
if err != nil {
return nil, model.WrapApiError(err, "failed to retrieve agent config history")
}
@@ -4270,6 +4274,18 @@ func (aH *APIHandler) CreateLogsPipeline(w http.ResponseWriter, r *http.Request)
return
}
+ // prepare config by calling gen func
+ orgID, errv2 := valuer.NewUUID(claims.OrgID)
+ if errv2 != nil {
+ render.Error(w, errv2)
+ return
+ }
+ userID, errv2 := valuer.NewUUID(claims.UserID)
+ if errv2 != nil {
+ render.Error(w, errv2)
+ return
+ }
+
req := pipelinetypes.PostablePipelines{}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
@@ -4290,7 +4306,7 @@ func (aH *APIHandler) CreateLogsPipeline(w http.ResponseWriter, r *http.Request)
return nil, validationErr
}
- return aH.LogsParsingPipelineController.ApplyPipelines(ctx, claims.OrgID, postable)
+ return aH.LogsParsingPipelineController.ApplyPipelines(ctx, orgID, userID, postable)
}
res, err := createPipeline(r.Context(), req.Pipelines)
diff --git a/pkg/query-service/app/logparsingpipeline/controller.go b/pkg/query-service/app/logparsingpipeline/controller.go
index cc077e66e0..12a8d702e3 100644
--- a/pkg/query-service/app/logparsingpipeline/controller.go
+++ b/pkg/query-service/app/logparsingpipeline/controller.go
@@ -13,7 +13,7 @@ import (
"github.com/SigNoz/signoz/pkg/query-service/utils"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types"
- "github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
"github.com/SigNoz/signoz/pkg/valuer"
"github.com/google/uuid"
@@ -41,24 +41,19 @@ func NewLogParsingPipelinesController(
// PipelinesResponse is used to prepare http response for pipelines config related requests
type PipelinesResponse struct {
- *agentConf.ConfigVersion
+ *opamptypes.AgentConfigVersion
Pipelines []pipelinetypes.GettablePipeline `json:"pipelines"`
- History []agentConf.ConfigVersion `json:"history"`
+ History []opamptypes.AgentConfigVersion `json:"history"`
}
// ApplyPipelines stores new or changed pipelines and initiates a new config update
func (ic *LogParsingPipelineController) ApplyPipelines(
ctx context.Context,
- orgID string,
+ orgID valuer.UUID,
+ userID valuer.UUID,
postable []pipelinetypes.PostablePipeline,
) (*PipelinesResponse, *model.ApiError) {
- // get user id from context
- claims, errv2 := authtypes.ClaimsFromContext(ctx)
- if errv2 != nil {
- return nil, model.UnauthorizedError(fmt.Errorf("failed to get userId from context"))
- }
-
var pipelines []pipelinetypes.GettablePipeline
// scan through postable pipelines, to select the existing pipelines or insert missing ones
@@ -87,13 +82,12 @@ func (ic *LogParsingPipelineController) ApplyPipelines(
elements[i] = p.ID.StringValue()
}
- // prepare config by calling gen func
- cfg, err := agentConf.StartNewVersion(ctx, claims.UserID, agentConf.ElementTypeLogPipelines, elements)
+ cfg, err := agentConf.StartNewVersion(ctx, orgID, userID, opamptypes.ElementTypeLogPipelines, elements)
if err != nil || cfg == nil {
- return nil, err
+ return nil, model.InternalError(fmt.Errorf("failed to start new version: %w", err))
}
- return ic.GetPipelinesByVersion(ctx, cfg.Version)
+ return ic.GetPipelinesByVersion(ctx, orgID, cfg.Version)
}
func (ic *LogParsingPipelineController) ValidatePipelines(
@@ -142,21 +136,12 @@ func (ic *LogParsingPipelineController) ValidatePipelines(
// Returns effective list of pipelines including user created
// pipelines and pipelines for installed integrations
func (ic *LogParsingPipelineController) getEffectivePipelinesByVersion(
- ctx context.Context, version int,
+ ctx context.Context, orgID valuer.UUID, version int,
) ([]pipelinetypes.GettablePipeline, *model.ApiError) {
- result := []pipelinetypes.GettablePipeline{}
-
- // todo(nitya): remove this once we fix agents in multitenancy
- defaultOrgID, err := ic.GetDefaultOrgID(ctx)
- if err != nil {
- // we don't want to fail the request if we can't get the default org ID
- // we will just return an empty list of pipelines
- zap.L().Warn("failed to get default org ID", zap.Error(err))
- return result, nil
- }
+ result := []pipelinetypes.GettablePipeline{}
if version >= 0 {
- savedPipelines, errors := ic.getPipelinesByVersion(ctx, defaultOrgID, version)
+ savedPipelines, errors := ic.getPipelinesByVersion(ctx, orgID.String(), version)
if errors != nil {
zap.L().Error("failed to get pipelines for version", zap.Int("version", version), zap.Errors("errors", errors))
return nil, model.InternalError(fmt.Errorf("failed to get pipelines for given version %v", errors))
@@ -164,7 +149,7 @@ func (ic *LogParsingPipelineController) getEffectivePipelinesByVersion(
result = savedPipelines
}
- integrationPipelines, apiErr := ic.GetIntegrationPipelines(ctx, defaultOrgID)
+ integrationPipelines, apiErr := ic.GetIntegrationPipelines(ctx, orgID.String())
if apiErr != nil {
return nil, model.WrapApiError(
apiErr, "could not get pipelines for installed integrations",
@@ -208,18 +193,18 @@ func (ic *LogParsingPipelineController) getEffectivePipelinesByVersion(
// GetPipelinesByVersion responds with version info and associated pipelines
func (ic *LogParsingPipelineController) GetPipelinesByVersion(
- ctx context.Context, version int,
+ ctx context.Context, orgId valuer.UUID, version int,
) (*PipelinesResponse, *model.ApiError) {
- pipelines, errors := ic.getEffectivePipelinesByVersion(ctx, version)
+ pipelines, errors := ic.getEffectivePipelinesByVersion(ctx, orgId, version)
if errors != nil {
zap.L().Error("failed to get pipelines for version", zap.Int("version", version), zap.Error(errors))
return nil, model.InternalError(fmt.Errorf("failed to get pipelines for given version %v", errors))
}
- var configVersion *agentConf.ConfigVersion
+ var configVersion *opamptypes.AgentConfigVersion
if version >= 0 {
- cv, err := agentConf.GetConfigVersion(ctx, agentConf.ElementTypeLogPipelines, version)
+ cv, err := agentConf.GetConfigVersion(ctx, orgId, opamptypes.ElementTypeLogPipelines, version)
if err != nil {
zap.L().Error("failed to get config for version", zap.Int("version", version), zap.Error(err))
return nil, model.WrapApiError(err, "failed to get config for given version")
@@ -228,8 +213,8 @@ func (ic *LogParsingPipelineController) GetPipelinesByVersion(
}
return &PipelinesResponse{
- ConfigVersion: configVersion,
- Pipelines: pipelines,
+ AgentConfigVersion: configVersion,
+ Pipelines: pipelines,
}, nil
}
@@ -268,8 +253,9 @@ func (pc *LogParsingPipelineController) AgentFeatureType() agentConf.AgentFeatur
// Implements agentConf.AgentFeature interface.
func (pc *LogParsingPipelineController) RecommendAgentConfig(
+ orgId valuer.UUID,
currentConfYaml []byte,
- configVersion *agentConf.ConfigVersion,
+ configVersion *opamptypes.AgentConfigVersion,
) (
recommendedConfYaml []byte,
serializedSettingsUsed string,
@@ -281,7 +267,7 @@ func (pc *LogParsingPipelineController) RecommendAgentConfig(
}
pipelinesResp, apiErr := pc.GetPipelinesByVersion(
- context.Background(), pipelinesVersion,
+ context.Background(), orgId, pipelinesVersion,
)
if apiErr != nil {
return nil, "", apiErr
diff --git a/pkg/query-service/app/logparsingpipeline/db.go b/pkg/query-service/app/logparsingpipeline/db.go
index 719c2e2069..92196cf34a 100644
--- a/pkg/query-service/app/logparsingpipeline/db.go
+++ b/pkg/query-service/app/logparsingpipeline/db.go
@@ -32,7 +32,7 @@ func NewRepo(sqlStore sqlstore.SQLStore) Repo {
// insertPipeline stores a given postable pipeline to database
func (r *Repo) insertPipeline(
- ctx context.Context, orgID string, postable *pipelinetypes.PostablePipeline,
+ ctx context.Context, orgID valuer.UUID, postable *pipelinetypes.PostablePipeline,
) (*pipelinetypes.GettablePipeline, *model.ApiError) {
if err := postable.IsValid(); err != nil {
return nil, model.BadRequest(errors.Wrap(err,
@@ -60,7 +60,7 @@ func (r *Repo) insertPipeline(
insertRow := &pipelinetypes.GettablePipeline{
StoreablePipeline: pipelinetypes.StoreablePipeline{
- OrgID: orgID,
+ OrgID: orgID.String(),
Identifiable: types.Identifiable{
ID: valuer.GenerateUUID(),
},
@@ -102,11 +102,11 @@ func (r *Repo) getPipelinesByVersion(
storablePipelines := []pipelinetypes.StoreablePipeline{}
err := r.sqlStore.BunDB().NewSelect().
Model(&storablePipelines).
- Join("JOIN agent_config_elements e ON p.id = e.element_id").
- Join("JOIN agent_config_versions v ON v.id = e.version_id").
- Where("e.element_type = ?", logPipelines). // TODO: nitya - add org_id to this as well
- Where("v.version = ?", version). // TODO: nitya - add org_id to this as well
- Where("p.org_id = ?", orgID).
+ Join("JOIN agent_config_element e ON p.id = e.element_id").
+ Join("JOIN agent_config_version v ON v.id = e.version_id").
+ Where("e.element_type = ?", logPipelines).
+ Where("v.version = ?", version).
+ Where("v.org_id = ?", orgID).
Order("p.order_id ASC").
Scan(ctx)
if err != nil {
@@ -131,20 +131,6 @@ func (r *Repo) getPipelinesByVersion(
return gettablePipelines, errors
}
-func (r *Repo) GetDefaultOrgID(ctx context.Context) (string, *model.ApiError) {
- var orgs []types.Organization
- err := r.sqlStore.BunDB().NewSelect().
- Model(&orgs).
- Scan(ctx)
- if err != nil {
- return "", model.InternalError(errors.Wrap(err, "failed to get default org ID"))
- }
- if len(orgs) == 0 {
- return "", model.InternalError(errors.New("no orgs found"))
- }
- return orgs[0].ID.StringValue(), nil
-}
-
// GetPipelines returns pipeline and errors (if any)
func (r *Repo) GetPipeline(
ctx context.Context, orgID string, id string,
diff --git a/pkg/query-service/app/opamp/config_provider_multitenancy_test.go b/pkg/query-service/app/opamp/config_provider_multitenancy_test.go
new file mode 100644
index 0000000000..ee8d612169
--- /dev/null
+++ b/pkg/query-service/app/opamp/config_provider_multitenancy_test.go
@@ -0,0 +1 @@
+package opamp
diff --git a/pkg/query-service/app/opamp/config_provider_test.go b/pkg/query-service/app/opamp/config_provider_test.go
index 175fb102c4..2618258e5c 100644
--- a/pkg/query-service/app/opamp/config_provider_test.go
+++ b/pkg/query-service/app/opamp/config_provider_test.go
@@ -1,11 +1,20 @@
package opamp
import (
+ "context"
"fmt"
+ "log/slog"
"testing"
+ "github.com/SigNoz/signoz/pkg/instrumentation/instrumentationtest"
+ "github.com/SigNoz/signoz/pkg/modules/organization/implorganization"
"github.com/SigNoz/signoz/pkg/query-service/app/opamp/model"
"github.com/SigNoz/signoz/pkg/query-service/utils"
+ "github.com/SigNoz/signoz/pkg/sharder"
+ "github.com/SigNoz/signoz/pkg/sharder/noopsharder"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/rawbytes"
@@ -21,6 +30,9 @@ func TestOpAMPServerToAgentCommunicationWithConfigProvider(t *testing.T) {
tb := newTestbed(t)
+ orgID, err := utils.GetTestOrgId(tb.sqlStore)
+ require.Nil(err)
+
require.Equal(
0, len(tb.testConfigProvider.ConfigUpdateSubscribers),
"there should be no agent config subscribers at the start",
@@ -35,7 +47,8 @@ func TestOpAMPServerToAgentCommunicationWithConfigProvider(t *testing.T) {
// Even if there are no recommended changes to the agent's initial config
require.False(tb.testConfigProvider.HasRecommendations())
agent1Conn := &MockOpAmpConnection{}
- agent1Id := "testAgent1"
+ agent1Id := valuer.GenerateUUID().String()
+ // get orgId from the db
tb.opampServer.OnMessage(
agent1Conn,
&protobufs.AgentToServer{
@@ -57,7 +70,7 @@ func TestOpAMPServerToAgentCommunicationWithConfigProvider(t *testing.T) {
tb.testConfigProvider.ZPagesEndpoint = "localhost:55555"
require.True(tb.testConfigProvider.HasRecommendations())
- agent2Id := "testAgent2"
+ agent2Id := valuer.GenerateUUID().String()
agent2Conn := &MockOpAmpConnection{}
tb.opampServer.OnMessage(
agent2Conn,
@@ -97,10 +110,10 @@ func TestOpAMPServerToAgentCommunicationWithConfigProvider(t *testing.T) {
},
})
expectedConfId := tb.testConfigProvider.ZPagesEndpoint
- require.True(tb.testConfigProvider.HasReportedDeploymentStatus(expectedConfId, agent2Id),
+ require.True(tb.testConfigProvider.HasReportedDeploymentStatus(orgID, expectedConfId, agent2Id),
"Server should report deployment success to config provider on receiving update from agent.",
)
- require.True(tb.testConfigProvider.ReportedDeploymentStatuses[expectedConfId][agent2Id])
+ require.True(tb.testConfigProvider.ReportedDeploymentStatuses[orgID.String()+expectedConfId][agent2Id])
require.Nil(
agent2Conn.LatestMsgFromServer(),
"Server should not recommend a RemoteConfig if agent is already running it.",
@@ -130,10 +143,10 @@ func TestOpAMPServerToAgentCommunicationWithConfigProvider(t *testing.T) {
},
})
expectedConfId = tb.testConfigProvider.ZPagesEndpoint
- require.True(tb.testConfigProvider.HasReportedDeploymentStatus(expectedConfId, agent2Id),
+ require.True(tb.testConfigProvider.HasReportedDeploymentStatus(orgID, expectedConfId, agent2Id),
"Server should report deployment failure to config provider on receiving update from agent.",
)
- require.False(tb.testConfigProvider.ReportedDeploymentStatuses[expectedConfId][agent2Id])
+ require.False(tb.testConfigProvider.ReportedDeploymentStatuses[orgID.String()+expectedConfId][agent2Id])
lastAgent1Msg = agent1Conn.LatestMsgFromServer()
agent1Conn.ClearMsgsFromServer()
@@ -158,26 +171,88 @@ func TestOpAMPServerToAgentCommunicationWithConfigProvider(t *testing.T) {
)
}
+func TestOpAMPServerAgentLimit(t *testing.T) {
+ require := require.New(t)
+
+ tb := newTestbed(t)
+ // Create 51 agents and check if the first one gets deleted
+ var agentConnections []*MockOpAmpConnection
+ var agentIds []string
+ for i := 0; i < 51; i++ {
+ agentConn := &MockOpAmpConnection{}
+ agentId := valuer.GenerateUUID().String()
+ agentIds = append(agentIds, agentId)
+ tb.opampServer.OnMessage(
+ agentConn,
+ &protobufs.AgentToServer{
+ InstanceUid: agentId,
+ EffectiveConfig: &protobufs.EffectiveConfig{
+ ConfigMap: initialAgentConf(),
+ },
+ },
+ )
+ agentConnections = append(agentConnections, agentConn)
+ }
+
+ // Perform a DB level check to ensure the first agent is removed
+ count, err := tb.sqlStore.BunDB().NewSelect().
+ Model(new(opamptypes.StorableAgent)).
+ Where("agent_id = ?", agentIds[0]).
+ Count(context.Background())
+ require.Nil(err, "Error querying the database for agent count")
+ require.Equal(0, count, "First agent should be removed from the database after exceeding the limit of 50 agents")
+
+ // verify there are 50 agents in the db
+ count, err = tb.sqlStore.BunDB().NewSelect().
+ Model(new(opamptypes.StorableAgent)).
+ Count(context.Background())
+ require.Nil(err, "Error querying the database for agent count")
+ require.Equal(50, count, "There should be 50 agents in the database")
+
+ // Check if the 51st agent received a config
+ lastAgentConn := agentConnections[50]
+ lastAgentMsg := lastAgentConn.LatestMsgFromServer()
+ require.NotNil(
+ lastAgentMsg,
+ "51st agent should receive a remote config from the server",
+ )
+
+ tb.opampServer.Stop()
+ require.Equal(
+ 0, len(tb.testConfigProvider.ConfigUpdateSubscribers),
+ "Opamp server should have unsubscribed to config provider updates after shutdown",
+ )
+}
+
type testbed struct {
testConfigProvider *MockAgentConfigProvider
opampServer *Server
t *testing.T
+ sqlStore sqlstore.SQLStore
}
func newTestbed(t *testing.T) *testbed {
testDB := utils.NewQueryServiceDBForTests(t)
- _, err := model.InitDB(testDB.SQLxDB())
- if err != nil {
- t.Fatalf("could not init opamp model: %v", err)
- }
+ providerSettings := instrumentationtest.New().ToProviderSettings()
+ sharder, err := noopsharder.New(context.TODO(), providerSettings, sharder.Config{})
+ require.Nil(t, err)
+ orgGetter := implorganization.NewGetter(implorganization.NewStore(testDB), sharder)
+ model.InitDB(testDB, slog.Default(), orgGetter)
testConfigProvider := NewMockAgentConfigProvider()
opampServer := InitializeServer(nil, testConfigProvider)
+ // create a test org
+ err = utils.CreateTestOrg(t, testDB)
+ if err != nil {
+ t.Fatalf("could not create test org: %v", err)
+ }
+
return &testbed{
testConfigProvider: testConfigProvider,
opampServer: opampServer,
t: t,
+ sqlStore: testDB,
}
}
diff --git a/pkg/query-service/app/opamp/configure_ingestionRules.go b/pkg/query-service/app/opamp/configure_ingestionRules.go
index 35b81e4a3f..039fffe6db 100644
--- a/pkg/query-service/app/opamp/configure_ingestionRules.go
+++ b/pkg/query-service/app/opamp/configure_ingestionRules.go
@@ -60,13 +60,13 @@ func UpsertControlProcessors(
agenthash, err := addIngestionControlToAgent(agent, signal, processors, false)
if err != nil {
- zap.L().Error("failed to push ingestion rules config to agent", zap.String("agentID", agent.ID), zap.Error(err))
+ zap.L().Error("failed to push ingestion rules config to agent", zap.String("agentID", agent.AgentID), zap.Error(err))
continue
}
if agenthash != "" {
// subscribe callback
- model.ListenToConfigUpdate(agent.ID, agenthash, callback)
+ model.ListenToConfigUpdate(agent.OrgID, agent.AgentID, agenthash, callback)
}
hash = agenthash
@@ -78,7 +78,7 @@ func UpsertControlProcessors(
// addIngestionControlToAgent adds ingestion contorl rules to agent config
func addIngestionControlToAgent(agent *model.Agent, signal string, processors map[string]interface{}, withLB bool) (string, error) {
confHash := ""
- config := agent.EffectiveConfig
+ config := agent.Config
c, err := yaml.Parser().Unmarshal([]byte(config))
if err != nil {
return confHash, err
@@ -89,7 +89,7 @@ func addIngestionControlToAgent(agent *model.Agent, signal string, processors ma
// add ingestion control spec
err = makeIngestionControlSpec(agentConf, Signal(signal), processors)
if err != nil {
- zap.L().Error("failed to prepare ingestion control processors for agent", zap.String("agentID", agent.ID), zap.Error(err))
+ zap.L().Error("failed to prepare ingestion control processors for agent", zap.String("agentID", agent.AgentID), zap.Error(err))
return confHash, err
}
@@ -106,7 +106,7 @@ func addIngestionControlToAgent(agent *model.Agent, signal string, processors ma
return confHash, err
}
confHash = string(hash.Sum(nil))
- agent.EffectiveConfig = string(configR)
+ agent.Config = string(configR)
err = agent.Upsert()
if err != nil {
return confHash, err
diff --git a/pkg/query-service/app/opamp/mocks.go b/pkg/query-service/app/opamp/mocks.go
index c90be74b80..ea2fa53286 100644
--- a/pkg/query-service/app/opamp/mocks.go
+++ b/pkg/query-service/app/opamp/mocks.go
@@ -5,6 +5,7 @@ import (
"log"
"net"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/google/uuid"
"github.com/knadh/koanf"
"github.com/knadh/koanf/parsers/yaml"
@@ -67,7 +68,7 @@ func (ta *MockAgentConfigProvider) HasRecommendations() bool {
}
// AgentConfigProvider interface
-func (ta *MockAgentConfigProvider) RecommendAgentConfig(baseConfYaml []byte) (
+func (ta *MockAgentConfigProvider) RecommendAgentConfig(orgId valuer.UUID, baseConfYaml []byte) (
[]byte, string, error,
) {
if len(ta.ZPagesEndpoint) < 1 {
@@ -92,11 +93,14 @@ func (ta *MockAgentConfigProvider) RecommendAgentConfig(baseConfYaml []byte) (
// AgentConfigProvider interface
func (ta *MockAgentConfigProvider) ReportConfigDeploymentStatus(
+ orgId valuer.UUID,
agentId string,
configId string,
err error,
) {
- confIdReports := ta.ReportedDeploymentStatuses[configId]
+ // using orgID + configId as key to avoid collisions with other orgs
+ // check code in model/coordinator.go for more details
+ confIdReports := ta.ReportedDeploymentStatuses[orgId.String()+configId]
if confIdReports == nil {
confIdReports = map[string]bool{}
ta.ReportedDeploymentStatuses[configId] = confIdReports
@@ -106,10 +110,12 @@ func (ta *MockAgentConfigProvider) ReportConfigDeploymentStatus(
}
// Test helper.
-func (ta *MockAgentConfigProvider) HasReportedDeploymentStatus(
+func (ta *MockAgentConfigProvider) HasReportedDeploymentStatus(orgID valuer.UUID,
configId string, agentId string,
) bool {
- confIdReports := ta.ReportedDeploymentStatuses[configId]
+ // using orgID + configId as key to avoid collisions with other orgs
+ // check code in model/coordinator.go for more details
+ confIdReports := ta.ReportedDeploymentStatuses[orgID.String()+configId]
if confIdReports == nil {
return false
}
diff --git a/pkg/query-service/app/opamp/model/agent.go b/pkg/query-service/app/opamp/model/agent.go
index cf48719e80..02bc00a8d0 100644
--- a/pkg/query-service/app/opamp/model/agent.go
+++ b/pkg/query-service/app/opamp/model/agent.go
@@ -4,36 +4,24 @@ import (
"bytes"
"context"
"crypto/sha256"
+ "log/slog"
"sync"
"time"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"go.uber.org/zap"
"google.golang.org/protobuf/proto"
"github.com/open-telemetry/opamp-go/protobufs"
- "github.com/open-telemetry/opamp-go/server/types"
+ opampTypes "github.com/open-telemetry/opamp-go/server/types"
)
-type AgentStatus int
-
-const (
- AgentStatusUnknown AgentStatus = iota
- AgentStatusConnected
- AgentStatusDisconnected
-)
-
-// set in agent description when agent is capable of supporting
-// lb exporter configuration. values: 1 (true) or 0 (false)
-const lbExporterFlag = "capabilities.lbexporter"
-
type Agent struct {
- ID string `json:"agentId" yaml:"agentId" db:"agent_id"`
- StartedAt time.Time `json:"startedAt" yaml:"startedAt" db:"started_at"`
- TerminatedAt time.Time `json:"terminatedAt" yaml:"terminatedAt" db:"terminated_at"`
- EffectiveConfig string `json:"effectiveConfig" yaml:"effectiveConfig" db:"effective_config"`
- CurrentStatus AgentStatus `json:"currentStatus" yaml:"currentStatus" db:"current_status"`
- remoteConfig *protobufs.AgentRemoteConfig
- Status *protobufs.AgentToServer
+ opamptypes.StorableAgent
+ remoteConfig *protobufs.AgentRemoteConfig
+ Status *protobufs.AgentToServer
// can this agent be load balancer
CanLB bool
@@ -41,13 +29,24 @@ type Agent struct {
// is this agent setup as load balancer
IsLb bool
- conn types.Connection
+ conn opampTypes.Connection
connMutex sync.Mutex
mux sync.RWMutex
+ store sqlstore.SQLStore
+ logger *slog.Logger
}
-func New(ID string, conn types.Connection) *Agent {
- return &Agent{ID: ID, StartedAt: time.Now(), CurrentStatus: AgentStatusConnected, conn: conn}
+// set in agent description when agent is capable of supporting
+// lb exporter configuration. values: 1 (true) or 0 (false)
+const lbExporterFlag = "capabilities.lbexporter"
+
+func New(store sqlstore.SQLStore, logger *slog.Logger, orgID valuer.UUID, agentID string, conn opampTypes.Connection) *Agent {
+ return &Agent{
+ StorableAgent: opamptypes.NewStorableAgent(store, orgID, agentID, opamptypes.AgentStatusConnected),
+ conn: conn,
+ store: store,
+ logger: logger,
+ }
}
// Upsert inserts or updates the agent in the database.
@@ -55,17 +54,13 @@ func (agent *Agent) Upsert() error {
agent.mux.Lock()
defer agent.mux.Unlock()
- _, err := db.NamedExec(`INSERT OR REPLACE INTO agents (
- agent_id,
- started_at,
- effective_config,
- current_status
- ) VALUES (
- :agent_id,
- :started_at,
- :effective_config,
- :current_status
- )`, agent)
+ _, err := agent.store.BunDB().NewInsert().
+ Model(&agent.StorableAgent).
+ On("CONFLICT (agent_id) DO UPDATE").
+ Set("updated_at = EXCLUDED.updated_at").
+ Set("config = EXCLUDED.config").
+ Set("status = EXCLUDED.status").
+ Exec(context.Background())
if err != nil {
return err
}
@@ -73,6 +68,27 @@ func (agent *Agent) Upsert() error {
return nil
}
+// keep only the last 50 agents in the database
+func (agent *Agent) KeepOnlyLast50Agents(ctx context.Context) {
+ // Delete all agents except the last 50 in a single query
+ _, err := agent.store.BunDB().
+ NewDelete().
+ Model(new(opamptypes.StorableAgent)).
+ Where("org_id = ?", agent.OrgID).
+ Where("agent_id NOT IN (?)",
+ agent.store.BunDB().
+ NewSelect().
+ ColumnExpr("distinct(agent_id)").
+ Model(new(opamptypes.StorableAgent)).
+ Where("org_id = ?", agent.OrgID).
+ OrderExpr("created_at DESC").
+ Limit(50)).
+ Exec(ctx)
+ if err != nil {
+ agent.logger.Error("failed to delete old agents", "error", err)
+ }
+}
+
// extracts lb exporter support flag from agent description. the flag
// is used to decide if lb exporter can be enabled on the agent.
func ExtractLbFlag(agentDescr *protobufs.AgentDescription) bool {
@@ -135,11 +151,11 @@ func (agent *Agent) updateAgentDescription(newStatus *protobufs.AgentToServer) (
// todo: need to address multiple agent scenario here
// for now, the first response will be sent back to the UI
if agent.Status.RemoteConfigStatus.Status == protobufs.RemoteConfigStatuses_RemoteConfigStatuses_APPLIED {
- onConfigSuccess(agent.ID, string(agent.Status.RemoteConfigStatus.LastRemoteConfigHash))
+ onConfigSuccess(agent.OrgID, agent.AgentID, string(agent.Status.RemoteConfigStatus.LastRemoteConfigHash))
}
if agent.Status.RemoteConfigStatus.Status == protobufs.RemoteConfigStatuses_RemoteConfigStatuses_FAILED {
- onConfigFailure(agent.ID, string(agent.Status.RemoteConfigStatus.LastRemoteConfigHash), agent.Status.RemoteConfigStatus.ErrorMessage)
+ onConfigFailure(agent.OrgID, agent.AgentID, string(agent.Status.RemoteConfigStatus.LastRemoteConfigHash), agent.Status.RemoteConfigStatus.ErrorMessage)
}
}
}
@@ -159,7 +175,7 @@ func (agent *Agent) updateHealth(newStatus *protobufs.AgentToServer) {
agent.Status.Health = newStatus.Health
if agent.Status != nil && agent.Status.Health != nil && agent.Status.Health.Healthy {
- agent.StartedAt = time.Unix(0, int64(agent.Status.Health.StartTimeUnixNano)).UTC()
+ agent.TimeAuditable.UpdatedAt = time.Unix(0, int64(agent.Status.Health.StartTimeUnixNano)).UTC()
}
}
@@ -190,10 +206,10 @@ func (agent *Agent) updateEffectiveConfig(newStatus *protobufs.AgentToServer, re
agent.Status.EffectiveConfig = newStatus.EffectiveConfig
// Convert to string for displaying purposes.
- agent.EffectiveConfig = ""
+ agent.Config = ""
// There should be only one config in the map.
for _, cfg := range newStatus.EffectiveConfig.ConfigMap.ConfigMap {
- agent.EffectiveConfig = string(cfg.Body)
+ agent.Config = string(cfg.Body)
}
}
}
@@ -269,7 +285,8 @@ func (agent *Agent) processStatusUpdate(
agent.SendToAgent(response)
ListenToConfigUpdate(
- agent.ID,
+ agent.OrgID,
+ agent.AgentID,
string(response.RemoteConfig.ConfigHash),
configProvider.ReportConfigDeploymentStatus,
)
@@ -277,9 +294,9 @@ func (agent *Agent) processStatusUpdate(
}
func (agent *Agent) updateRemoteConfig(configProvider AgentConfigProvider) bool {
- recommendedConfig, confId, err := configProvider.RecommendAgentConfig([]byte(agent.EffectiveConfig))
+ recommendedConfig, confId, err := configProvider.RecommendAgentConfig(agent.OrgID, []byte(agent.Config))
if err != nil {
- zap.L().Error("could not generate config recommendation for agent", zap.String("agentID", agent.ID), zap.Error(err))
+ zap.L().Error("could not generate config recommendation for agent", zap.String("agentID", agent.AgentID), zap.Error(err))
return false
}
diff --git a/pkg/query-service/app/opamp/model/agents.go b/pkg/query-service/app/opamp/model/agents.go
index 2a6518f685..1f28957b71 100644
--- a/pkg/query-service/app/opamp/model/agents.go
+++ b/pkg/query-service/app/opamp/model/agents.go
@@ -1,19 +1,22 @@
package model
import (
+ "context"
"fmt"
+ "log/slog"
"sync"
"time"
- "github.com/jmoiron/sqlx"
+ "github.com/SigNoz/signoz/pkg/modules/organization"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/open-telemetry/opamp-go/protobufs"
"github.com/open-telemetry/opamp-go/server/types"
"github.com/pkg/errors"
"go.uber.org/zap"
)
-var db *sqlx.DB
-
var AllAgents = Agents{
agentsById: map[string]*Agent{},
connections: map[types.Connection]map[string]bool{},
@@ -23,6 +26,9 @@ type Agents struct {
mux sync.RWMutex
agentsById map[string]*Agent
connections map[types.Connection]map[string]bool
+ store sqlstore.SQLStore
+ OrgGetter organization.Getter
+ logger *slog.Logger
}
func (a *Agents) Count() int {
@@ -30,15 +36,16 @@ func (a *Agents) Count() int {
}
// Initialize the database and create schema if needed
-func InitDB(qsDB *sqlx.DB) (*sqlx.DB, error) {
- db = qsDB
+func InitDB(sqlStore sqlstore.SQLStore, logger *slog.Logger, orgGetter organization.Getter) {
AllAgents = Agents{
agentsById: make(map[string]*Agent),
connections: make(map[types.Connection]map[string]bool),
mux: sync.RWMutex{},
+ store: sqlStore,
+ OrgGetter: orgGetter,
+ logger: logger,
}
- return db, nil
}
// RemoveConnection removes the connection all Agent instances associated with the
@@ -49,8 +56,8 @@ func (agents *Agents) RemoveConnection(conn types.Connection) {
for instanceId := range agents.connections[conn] {
agent := agents.agentsById[instanceId]
- agent.CurrentStatus = AgentStatusDisconnected
- agent.TerminatedAt = time.Now()
+ agent.StorableAgent.Status = opamptypes.AgentStatusDisconnected
+ agent.StorableAgent.TerminatedAt = time.Now()
_ = agent.Upsert()
delete(agents.agentsById, instanceId)
}
@@ -67,27 +74,32 @@ func (agents *Agents) FindAgent(agentID string) *Agent {
// FindOrCreateAgent returns the Agent instance associated with the given agentID.
// If the Agent instance does not exist, it is created and added to the list of
// Agent instances.
-func (agents *Agents) FindOrCreateAgent(agentID string, conn types.Connection) (*Agent, bool, error) {
+func (agents *Agents) FindOrCreateAgent(agentID string, conn types.Connection, orgID valuer.UUID) (*Agent, bool, error) {
agents.mux.Lock()
defer agents.mux.Unlock()
- var created bool
agent, ok := agents.agentsById[agentID]
- var err error
- if !ok || agent == nil {
- agent = New(agentID, conn)
- err = agent.Upsert()
- if err != nil {
- return nil, created, err
- }
- agents.agentsById[agentID] = agent
- if agents.connections[conn] == nil {
- agents.connections[conn] = map[string]bool{}
- }
- agents.connections[conn][agentID] = true
- created = true
+ if ok && agent != nil {
+ return agent, false, nil
+ }
+
+ if !ok && orgID.IsZero() {
+ return nil, false, errors.New("cannot create agent without orgId")
+ }
+
+ agent = New(agents.store, agents.logger, orgID, agentID, conn)
+ err := agent.Upsert()
+ if err != nil {
+ return nil, false, err
+ }
+ agent.KeepOnlyLast50Agents(context.Background())
+ agents.agentsById[agentID] = agent
+
+ if agents.connections[conn] == nil {
+ agents.connections[conn] = map[string]bool{}
}
- return agent, created, nil
+ agents.connections[conn][agentID] = true
+ return agent, true, nil
}
func (agents *Agents) GetAllAgents() []*Agent {
@@ -108,18 +120,19 @@ func (agents *Agents) RecommendLatestConfigToAll(
) error {
for _, agent := range agents.GetAllAgents() {
newConfig, confId, err := provider.RecommendAgentConfig(
- []byte(agent.EffectiveConfig),
+ agent.OrgID,
+ []byte(agent.Config),
)
if err != nil {
return errors.Wrap(err, fmt.Sprintf(
- "could not generate conf recommendation for %v", agent.ID,
+ "could not generate conf recommendation for %v", agent.AgentID,
))
}
// Recommendation is same as current config
- if string(newConfig) == agent.EffectiveConfig {
+ if string(newConfig) == agent.Config {
zap.L().Info(
- "Recommended config same as current effective config for agent", zap.String("agentID", agent.ID),
+ "Recommended config same as current effective config for agent", zap.String("agentID", agent.AgentID),
)
return nil
}
@@ -144,7 +157,7 @@ func (agents *Agents) RecommendLatestConfigToAll(
RemoteConfig: newRemoteConfig,
})
- ListenToConfigUpdate(agent.ID, confId, provider.ReportConfigDeploymentStatus)
+ ListenToConfigUpdate(agent.OrgID, agent.AgentID, confId, provider.ReportConfigDeploymentStatus)
}
return nil
}
diff --git a/pkg/query-service/app/opamp/model/config.go b/pkg/query-service/app/opamp/model/config.go
index 026ef947c3..fddc1e80d8 100644
--- a/pkg/query-service/app/opamp/model/config.go
+++ b/pkg/query-service/app/opamp/model/config.go
@@ -1,10 +1,12 @@
package model
+import "github.com/SigNoz/signoz/pkg/valuer"
+
// Interface for source of otel collector config recommendations.
type AgentConfigProvider interface {
// Generate recommended config for an agent based on its `currentConfYaml`
// and current state of user facing settings for agent based features.
- RecommendAgentConfig(currentConfYaml []byte) (
+ RecommendAgentConfig(orgId valuer.UUID, currentConfYaml []byte) (
recommendedConfYaml []byte,
// Opaque id of the recommended config, used for reporting deployment status updates
configId string,
@@ -13,6 +15,7 @@ type AgentConfigProvider interface {
// Report deployment status for config recommendations generated by RecommendAgentConfig
ReportConfigDeploymentStatus(
+ orgId valuer.UUID,
agentId string,
configId string,
err error,
diff --git a/pkg/query-service/app/opamp/model/coordinator.go b/pkg/query-service/app/opamp/model/coordinator.go
index a1f17f43a2..8d19155a62 100644
--- a/pkg/query-service/app/opamp/model/coordinator.go
+++ b/pkg/query-service/app/opamp/model/coordinator.go
@@ -3,6 +3,8 @@ package model
import (
"fmt"
"sync"
+
+ "github.com/SigNoz/signoz/pkg/valuer"
)
// communicates with calling apis when config is applied or fails
@@ -15,7 +17,7 @@ func init() {
}
}
-type OnChangeCallback func(agentId string, hash string, err error)
+type OnChangeCallback func(orgId valuer.UUID, agentId string, hash string, err error)
// responsible for managing subscribers on config change
type Coordinator struct {
@@ -25,42 +27,49 @@ type Coordinator struct {
subscribers map[string][]OnChangeCallback
}
-func onConfigSuccess(agentId string, hash string) {
- notifySubscribers(agentId, hash, nil)
+func getSubscriberKey(orgId valuer.UUID, hash string) string {
+ return orgId.String() + hash
+}
+
+func onConfigSuccess(orgId valuer.UUID, agentId string, hash string) {
+ key := getSubscriberKey(orgId, hash)
+ notifySubscribers(orgId, agentId, key, nil)
}
-func onConfigFailure(agentId string, hash string, errorMessage string) {
- notifySubscribers(agentId, hash, fmt.Errorf(errorMessage))
+func onConfigFailure(orgId valuer.UUID, agentId string, hash string, errorMessage string) {
+ key := getSubscriberKey(orgId, hash)
+ notifySubscribers(orgId, agentId, key, fmt.Errorf(errorMessage))
}
// OnSuccess listens to config changes and notifies subscribers
-func notifySubscribers(agentId string, hash string, err error) {
+func notifySubscribers(orgId valuer.UUID, agentId string, key string, err error) {
// this method currently does not handle multi-agent scenario.
// as soon as a message is delivered, we release all the subscribers
- // for a given hash
- subs, ok := coordinator.subscribers[hash]
+ // for a given key
+ subs, ok := coordinator.subscribers[key]
if !ok {
return
}
for _, s := range subs {
- s(agentId, hash, err)
+ s(orgId, agentId, key, err)
}
- // delete all subscribers for this hash, assume future
+ // delete all subscribers for this key, assume future
// notifies will be disabled. the first response is processed
- delete(coordinator.subscribers, hash)
+ delete(coordinator.subscribers, key)
}
// callers subscribe to this function to listen on config change requests
-func ListenToConfigUpdate(agentId string, hash string, ss OnChangeCallback) {
+func ListenToConfigUpdate(orgId valuer.UUID, agentId string, hash string, ss OnChangeCallback) {
coordinator.mutex.Lock()
defer coordinator.mutex.Unlock()
- if subs, ok := coordinator.subscribers[hash]; ok {
+ key := getSubscriberKey(orgId, hash)
+ if subs, ok := coordinator.subscribers[key]; ok {
subs = append(subs, ss)
- coordinator.subscribers[hash] = subs
+ coordinator.subscribers[key] = subs
} else {
- coordinator.subscribers[hash] = []OnChangeCallback{ss}
+ coordinator.subscribers[key] = []OnChangeCallback{ss}
}
}
diff --git a/pkg/query-service/app/opamp/opamp_server.go b/pkg/query-service/app/opamp/opamp_server.go
index 835e5b811e..86acd11c05 100644
--- a/pkg/query-service/app/opamp/opamp_server.go
+++ b/pkg/query-service/app/opamp/opamp_server.go
@@ -2,8 +2,10 @@ package opamp
import (
"context"
+ "time"
model "github.com/SigNoz/signoz/pkg/query-service/app/opamp/model"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/open-telemetry/opamp-go/protobufs"
"github.com/open-telemetry/opamp-go/server"
"github.com/open-telemetry/opamp-go/server/types"
@@ -53,6 +55,7 @@ func (srv *Server) Start(listener string) error {
ListenEndpoint: listener,
}
+ // This will have to send request to all the agents of all tenants
unsubscribe := srv.agentConfigProvider.SubscribeToConfigUpdates(func() {
err := srv.agents.RecommendLatestConfigToAll(srv.agentConfigProvider)
if err != nil {
@@ -78,21 +81,47 @@ func (srv *Server) onDisconnect(conn types.Connection) {
srv.agents.RemoveConnection(conn)
}
+// When the agent sends the message for the first time, then we need to know the orgID
+// For the subsequent requests, agents don't send the attributes unless something is changed
+// but we keep them in context mapped which is mapped to the instanceID, so we would know the
+// orgID from the context
+// note :- there can only be 50 agents in the db for a given orgID, we don't have a check in-memory but we delete from the db after insert.
func (srv *Server) OnMessage(conn types.Connection, msg *protobufs.AgentToServer) *protobufs.ServerToAgent {
agentID := msg.InstanceUid
- agent, created, err := srv.agents.FindOrCreateAgent(agentID, conn)
+ // find the orgID, if nothing is found keep it empty.
+ // the find or create agent will return an error if orgID is empty
+ // thus retry will happen
+ var orgID valuer.UUID
+ orgIDs, err := srv.agents.OrgGetter.ListByOwnedKeyRange(context.Background())
+ if err == nil && len(orgIDs) == 1 {
+ orgID = orgIDs[0].ID
+ }
+
+ agent, created, err := srv.agents.FindOrCreateAgent(agentID, conn, orgID)
if err != nil {
zap.L().Error("Failed to find or create agent", zap.String("agentID", agentID), zap.Error(err))
- // TODO: handle error
+
+ // Return error response according to OpAMP protocol
+ return &protobufs.ServerToAgent{
+ InstanceUid: agentID,
+ ErrorResponse: &protobufs.ServerErrorResponse{
+ Type: protobufs.ServerErrorResponseType_ServerErrorResponseType_Unavailable,
+ Details: &protobufs.ServerErrorResponse_RetryInfo{
+ RetryInfo: &protobufs.RetryInfo{
+ RetryAfterNanoseconds: uint64(5 * time.Second), // minimum recommended retry interval
+ },
+ },
+ },
+ }
}
if created {
agent.CanLB = model.ExtractLbFlag(msg.AgentDescription)
zap.L().Debug(
"New agent added", zap.Bool("canLb", agent.CanLB),
- zap.String("ID", agent.ID),
- zap.Any("status", agent.CurrentStatus),
+ zap.String("agentID", agent.AgentID),
+ zap.Any("status", agent.Status),
)
}
@@ -119,6 +148,6 @@ func Ready() bool {
return true
}
-func Subscribe(agentId string, hash string, f model.OnChangeCallback) {
- model.ListenToConfigUpdate(agentId, hash, f)
+func Subscribe(orgId valuer.UUID, agentId string, hash string, f model.OnChangeCallback) {
+ model.ListenToConfigUpdate(orgId, agentId, hash, f)
}
diff --git a/pkg/query-service/app/server.go b/pkg/query-service/app/server.go
index 479a4df27a..eb6a317c8e 100644
--- a/pkg/query-service/app/server.go
+++ b/pkg/query-service/app/server.go
@@ -179,13 +179,10 @@ func NewServer(serverOptions *ServerOptions) (*Server, error) {
s.privateHTTP = privateServer
- _, err = opAmpModel.InitDB(serverOptions.SigNoz.SQLStore.SQLxDB())
- if err != nil {
- return nil, err
- }
+ opAmpModel.InitDB(serverOptions.SigNoz.SQLStore, serverOptions.SigNoz.Instrumentation.Logger(), serverOptions.SigNoz.Modules.OrgGetter)
agentConfMgr, err := agentConf.Initiate(&agentConf.ManagerOptions{
- DB: serverOptions.SigNoz.SQLStore.SQLxDB(),
+ Store: serverOptions.SigNoz.SQLStore,
AgentFeatures: []agentConf.AgentFeature{
logParsingPipelineController,
},
diff --git a/pkg/query-service/tests/integration/logparsingpipeline_test.go b/pkg/query-service/tests/integration/logparsingpipeline_test.go
index 17eff8cae5..7adf891056 100644
--- a/pkg/query-service/tests/integration/logparsingpipeline_test.go
+++ b/pkg/query-service/tests/integration/logparsingpipeline_test.go
@@ -5,6 +5,7 @@ import (
"encoding/json"
"fmt"
"io"
+ "log/slog"
"net/http/httptest"
"runtime/debug"
"strings"
@@ -24,7 +25,7 @@ import (
"github.com/SigNoz/signoz/pkg/query-service/app/integrations"
"github.com/SigNoz/signoz/pkg/query-service/app/logparsingpipeline"
"github.com/SigNoz/signoz/pkg/query-service/app/opamp"
- opampModel "github.com/SigNoz/signoz/pkg/query-service/app/opamp/model"
+ "github.com/SigNoz/signoz/pkg/query-service/app/opamp/model"
"github.com/SigNoz/signoz/pkg/query-service/constants"
v3 "github.com/SigNoz/signoz/pkg/query-service/model/v3"
"github.com/SigNoz/signoz/pkg/query-service/queryBuilderToExpr"
@@ -35,7 +36,9 @@ import (
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/types"
"github.com/SigNoz/signoz/pkg/types/authtypes"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
"github.com/google/uuid"
"github.com/gorilla/mux"
"github.com/knadh/koanf/parsers/yaml"
@@ -47,7 +50,8 @@ import (
)
func TestLogPipelinesLifecycle(t *testing.T) {
- testbed := NewLogPipelinesTestBed(t, nil)
+ agentID := valuer.GenerateUUID().String()
+ testbed := NewLogPipelinesTestBed(t, nil, agentID)
require := require.New(t)
getPipelinesResp := testbed.GetPipelinesFromQS()
@@ -134,19 +138,19 @@ func TestLogPipelinesLifecycle(t *testing.T) {
"pipelines config history should not be empty after 1st configuration",
)
require.Equal(
- agentConf.DeployInitiated, getPipelinesResp.History[0].DeployStatus,
+ opamptypes.DeployInitiated, getPipelinesResp.History[0].DeployStatus,
"pipelines deployment should be in progress after 1st configuration",
)
// Deployment status should get updated after acknowledgement from opamp client
- testbed.simulateOpampClientAcknowledgementForLatestConfig()
+ testbed.simulateOpampClientAcknowledgementForLatestConfig(agentID)
getPipelinesResp = testbed.GetPipelinesFromQS()
assertPipelinesResponseMatchesPostedPipelines(
t, postablePipelines, getPipelinesResp,
)
require.Equal(
- agentConf.Deployed,
+ opamptypes.Deployed,
getPipelinesResp.History[0].DeployStatus,
"pipeline deployment should be complete after acknowledgment from opamp client",
)
@@ -166,19 +170,19 @@ func TestLogPipelinesLifecycle(t *testing.T) {
"there should be 2 history entries after posting pipelines config for the 2nd time",
)
require.Equal(
- agentConf.DeployInitiated, getPipelinesResp.History[0].DeployStatus,
+ opamptypes.DeployInitiated, getPipelinesResp.History[0].DeployStatus,
"deployment should be in progress for latest pipeline config",
)
// Deployment status should get updated again on receiving msg from client.
- testbed.simulateOpampClientAcknowledgementForLatestConfig()
+ testbed.simulateOpampClientAcknowledgementForLatestConfig(agentID)
getPipelinesResp = testbed.GetPipelinesFromQS()
assertPipelinesResponseMatchesPostedPipelines(
t, postablePipelines, getPipelinesResp,
)
require.Equal(
- agentConf.Deployed,
+ opamptypes.Deployed,
getPipelinesResp.History[0].DeployStatus,
"deployment for latest pipeline config should be complete after acknowledgment from opamp client",
)
@@ -186,7 +190,8 @@ func TestLogPipelinesLifecycle(t *testing.T) {
func TestLogPipelinesHistory(t *testing.T) {
require := require.New(t)
- testbed := NewLogPipelinesTestBed(t, nil)
+ agentID := valuer.GenerateUUID().String()
+ testbed := NewLogPipelinesTestBed(t, nil, agentID)
// Only the latest config version can be "IN_PROGRESS",
// other incomplete deployments should have status "UNKNOWN"
@@ -232,7 +237,7 @@ func TestLogPipelinesHistory(t *testing.T) {
testbed.PostPipelinesToQS(postablePipelines)
getPipelinesResp = testbed.GetPipelinesFromQS()
require.Equal(1, len(getPipelinesResp.History))
- require.Equal(agentConf.DeployInitiated, getPipelinesResp.History[0].DeployStatus)
+ require.Equal(opamptypes.DeployInitiated, getPipelinesResp.History[0].DeployStatus)
postablePipelines.Pipelines[0].Config = append(
postablePipelines.Pipelines[0].Config,
@@ -251,8 +256,8 @@ func TestLogPipelinesHistory(t *testing.T) {
getPipelinesResp = testbed.GetPipelinesFromQS()
require.Equal(2, len(getPipelinesResp.History))
- require.Equal(agentConf.DeployInitiated, getPipelinesResp.History[0].DeployStatus)
- require.Equal(agentConf.DeployStatusUnknown, getPipelinesResp.History[1].DeployStatus)
+ require.Equal(opamptypes.DeployInitiated, getPipelinesResp.History[0].DeployStatus)
+ require.Equal(opamptypes.DeployStatusUnknown, getPipelinesResp.History[1].DeployStatus)
}
func TestLogPipelinesValidation(t *testing.T) {
@@ -389,7 +394,8 @@ func TestLogPipelinesValidation(t *testing.T) {
for _, tc := range testCases {
t.Run(tc.Name, func(t *testing.T) {
- testbed := NewLogPipelinesTestBed(t, nil)
+ agentID := valuer.GenerateUUID().String()
+ testbed := NewLogPipelinesTestBed(t, nil, agentID)
testbed.PostPipelinesToQSExpectingStatusCode(
pipelinetypes.PostablePipelines{
Pipelines: []pipelinetypes.PostablePipeline{tc.Pipeline},
@@ -460,6 +466,7 @@ type LogPipelinesTestBed struct {
agentConfMgr *agentConf.Manager
opampServer *opamp.Server
opampClientConn *opamp.MockOpAmpConnection
+ store sqlstore.SQLStore
userModule user.Module
}
@@ -469,9 +476,6 @@ func NewTestbedWithoutOpamp(t *testing.T, sqlStore sqlstore.SQLStore) *LogPipeli
sqlStore = utils.NewQueryServiceDBForTests(t)
}
- // create test org
- // utils.CreateTestOrg(t, sqlStore)
-
ic, err := integrations.NewController(sqlStore)
if err != nil {
t.Fatalf("could not create integrations controller: %v", err)
@@ -508,17 +512,17 @@ func NewTestbedWithoutOpamp(t *testing.T, sqlStore sqlstore.SQLStore) *LogPipeli
t.Fatalf("could not create a new ApiHandler: %v", err)
}
+ // organizationModule := implorganization.NewModule(implorganization.NewStore(store))
user, apiErr := createTestUser(modules.OrgSetter, modules.User)
if apiErr != nil {
t.Fatalf("could not create a test user: %v", apiErr)
}
// Mock an available opamp agent
- testDB, err := opampModel.InitDB(sqlStore.SQLxDB())
require.Nil(t, err, "failed to init opamp model")
agentConfMgr, err := agentConf.Initiate(&agentConf.ManagerOptions{
- DB: testDB,
+ Store: sqlStore,
AgentFeatures: []agentConf.AgentFeature{
apiHandler.LogsParsingPipelineController,
}})
@@ -529,15 +533,22 @@ func NewTestbedWithoutOpamp(t *testing.T, sqlStore sqlstore.SQLStore) *LogPipeli
testUser: user,
apiHandler: apiHandler,
agentConfMgr: agentConfMgr,
+ store: sqlStore,
userModule: modules.User,
}
}
-func NewLogPipelinesTestBed(t *testing.T, testDB sqlstore.SQLStore) *LogPipelinesTestBed {
+func NewLogPipelinesTestBed(t *testing.T, testDB sqlstore.SQLStore, agentID string) *LogPipelinesTestBed {
testbed := NewTestbedWithoutOpamp(t, testDB)
+ providerSettings := instrumentationtest.New().ToProviderSettings()
+ sharder, err := noopsharder.New(context.TODO(), providerSettings, sharder.Config{})
+ orgGetter := implorganization.NewGetter(implorganization.NewStore(testbed.store), sharder)
+
+ model.InitDB(testbed.store, slog.Default(), orgGetter)
+
opampServer := opamp.InitializeServer(nil, testbed.agentConfMgr)
- err := opampServer.Start(opamp.GetAvailableLocalAddress())
+ err = opampServer.Start(opamp.GetAvailableLocalAddress())
require.Nil(t, err, "failed to start opamp server")
t.Cleanup(func() {
@@ -548,7 +559,7 @@ func NewLogPipelinesTestBed(t *testing.T, testDB sqlstore.SQLStore) *LogPipeline
opampServer.OnMessage(
opampClientConnection,
&protobufs.AgentToServer{
- InstanceUid: "test",
+ InstanceUid: agentID,
EffectiveConfig: &protobufs.EffectiveConfig{
ConfigMap: newInitialAgentConfigMap(),
},
@@ -743,10 +754,10 @@ func assertPipelinesRecommendedInRemoteConfig(
}
}
-func (tb *LogPipelinesTestBed) simulateOpampClientAcknowledgementForLatestConfig() {
+func (tb *LogPipelinesTestBed) simulateOpampClientAcknowledgementForLatestConfig(agentID string) {
lastMsg := tb.opampClientConn.LatestMsgFromServer()
tb.opampServer.OnMessage(tb.opampClientConn, &protobufs.AgentToServer{
- InstanceUid: "test",
+ InstanceUid: agentID,
EffectiveConfig: &protobufs.EffectiveConfig{
ConfigMap: lastMsg.RemoteConfig.Config,
},
diff --git a/pkg/query-service/tests/integration/signoz_integrations_test.go b/pkg/query-service/tests/integration/signoz_integrations_test.go
index 1eefde36a5..74e2347297 100644
--- a/pkg/query-service/tests/integration/signoz_integrations_test.go
+++ b/pkg/query-service/tests/integration/signoz_integrations_test.go
@@ -32,6 +32,7 @@ import (
"github.com/SigNoz/signoz/pkg/types/authtypes"
"github.com/SigNoz/signoz/pkg/types/dashboardtypes"
"github.com/SigNoz/signoz/pkg/types/pipelinetypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
mockhouse "github.com/srikanthccv/ClickHouse-go-mock"
"github.com/stretchr/testify/require"
)
@@ -42,6 +43,9 @@ func TestSignozIntegrationLifeCycle(t *testing.T) {
require := require.New(t)
testbed := NewIntegrationsTestBed(t, nil)
+ merr := utils.CreateTestOrg(t, testbed.store)
+ require.NoError(merr)
+
installedResp := testbed.GetInstalledIntegrationsFromQS()
require.Equal(
len(installedResp.Integrations), 0,
@@ -125,8 +129,12 @@ func TestLogPipelinesForInstalledSignozIntegrations(t *testing.T) {
require := require.New(t)
testDB := utils.NewQueryServiceDBForTests(t)
+ utils.CreateTestOrg(t, testDB)
+
+ agentID := valuer.GenerateUUID().String()
+
integrationsTB := NewIntegrationsTestBed(t, testDB)
- pipelinesTB := NewLogPipelinesTestBed(t, testDB)
+ pipelinesTB := NewLogPipelinesTestBed(t, testDB, agentID)
availableIntegrationsResp := integrationsTB.GetAvailableIntegrationsFromQS()
availableIntegrations := availableIntegrationsResp.Integrations
@@ -380,6 +388,7 @@ type IntegrationsTestBed struct {
testUser *types.User
qsHttpHandler http.Handler
mockClickhouse mockhouse.ClickConnMockCommon
+ store sqlstore.SQLStore
userModule user.Module
}
@@ -618,6 +627,7 @@ func NewIntegrationsTestBed(t *testing.T, testDB sqlstore.SQLStore) *Integration
testUser: user,
qsHttpHandler: router,
mockClickhouse: mockClickhouse,
+ store: testDB,
userModule: modules.User,
}
}
diff --git a/pkg/query-service/utils/testutils.go b/pkg/query-service/utils/testutils.go
index ebad37a9ab..54bb34e813 100644
--- a/pkg/query-service/utils/testutils.go
+++ b/pkg/query-service/utils/testutils.go
@@ -11,6 +11,8 @@ import (
"github.com/SigNoz/signoz/pkg/sqlmigrator"
"github.com/SigNoz/signoz/pkg/sqlstore"
"github.com/SigNoz/signoz/pkg/sqlstore/sqlitesqlstore"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/valuer"
_ "github.com/mattn/go-sqlite3"
)
@@ -69,6 +71,7 @@ func NewTestSqliteDB(t *testing.T) (sqlStore sqlstore.SQLStore, testDBFilePath s
sqlmigration.NewUpdateApiMonitoringFiltersFactory(sqlStore),
sqlmigration.NewAddKeyOrganizationFactory(sqlStore),
sqlmigration.NewUpdateDashboardFactory(sqlStore),
+ sqlmigration.NewUpdateAgentsFactory(sqlStore),
),
)
if err != nil {
@@ -87,3 +90,30 @@ func NewQueryServiceDBForTests(t *testing.T) sqlstore.SQLStore {
sqlStore, _ := NewTestSqliteDB(t)
return sqlStore
}
+
+func CreateTestOrg(t *testing.T, store sqlstore.SQLStore) error {
+ org := &types.Organization{
+ Identifiable: types.Identifiable{
+ ID: valuer.GenerateUUID(),
+ },
+ Name: "testOrg",
+ }
+ _, err := store.BunDB().NewInsert().Model(org).Exec(context.Background())
+ if err != nil {
+ return err
+ }
+ return nil
+}
+
+func GetTestOrgId(store sqlstore.SQLStore) (valuer.UUID, error) {
+ var orgID valuer.UUID
+ err := store.BunDB().NewSelect().
+ Model(&types.Organization{}).
+ Column("id").
+ Limit(1).
+ Scan(context.Background(), &orgID)
+ if err != nil {
+ return orgID, err
+ }
+ return orgID, nil
+}
diff --git a/pkg/signoz/provider.go b/pkg/signoz/provider.go
index 85a1c46583..3f7e1ae9d1 100644
--- a/pkg/signoz/provider.go
+++ b/pkg/signoz/provider.go
@@ -110,6 +110,7 @@ func NewSQLMigrationProviderFactories(sqlstore sqlstore.SQLStore) factory.NamedM
sqlmigration.NewUpdateDashboardFactory(sqlstore),
sqlmigration.NewDropFeatureSetFactory(),
sqlmigration.NewDropDeprecatedTablesFactory(),
+ sqlmigration.NewUpdateAgentsFactory(sqlstore),
)
}
diff --git a/pkg/sqlmigration/041_update_agents.go b/pkg/sqlmigration/041_update_agents.go
new file mode 100644
index 0000000000..3652929c15
--- /dev/null
+++ b/pkg/sqlmigration/041_update_agents.go
@@ -0,0 +1,323 @@
+package sqlmigration
+
+import (
+ "context"
+ "database/sql"
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/errors"
+ "github.com/SigNoz/signoz/pkg/factory"
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/types/opamptypes"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/uptrace/bun"
+ "github.com/uptrace/bun/migrate"
+)
+
+type updateAgents struct {
+ store sqlstore.SQLStore
+}
+
+type existingAgent41 struct {
+ bun.BaseModel `bun:"table:agents"`
+ AgentID string `bun:"agent_id,pk,type:text,unique"`
+ StartedAt time.Time `bun:"started_at,notnull"`
+ TerminatedAt time.Time `bun:"terminated_at"`
+ CurrentStatus opamptypes.AgentStatus `bun:"current_status,type:text,notnull"`
+ EffectiveConfig string `bun:"effective_config,type:text,notnull"`
+}
+
+type newAgent41 struct {
+ bun.BaseModel `bun:"table:agent"`
+
+ types.Identifiable
+ types.TimeAuditable
+ // AgentID is needed as the ID from opamp client is ULID and not UUID, so we are keeping it like this
+ AgentID string `json:"agentId" yaml:"agentId" bun:"agent_id,type:text,notnull,unique"`
+ OrgID string `json:"orgId" yaml:"orgId" bun:"org_id,type:text,notnull"`
+ TerminatedAt time.Time `json:"terminatedAt" yaml:"terminatedAt" bun:"terminated_at"`
+ Status opamptypes.AgentStatus `json:"currentStatus" yaml:"currentStatus" bun:"status,type:text,notnull"`
+ Config string `bun:"config,type:text,notnull"`
+}
+
+type existingAgentConfigVersions41 struct {
+ bun.BaseModel `bun:"table:agent_config_versions"`
+ ID string `bun:"id,pk,type:text"`
+ CreatedBy string `bun:"created_by,type:text"`
+ CreatedAt time.Time `bun:"created_at,default:CURRENT_TIMESTAMP"`
+ UpdatedBy string `bun:"updated_by,type:text"`
+ UpdatedAt time.Time `bun:"updated_at,default:CURRENT_TIMESTAMP"`
+ Version int `bun:"version,default:1,unique:element_version_idx"`
+ Active int `bun:"active"`
+ IsValid int `bun:"is_valid"`
+ Disabled int `bun:"disabled"`
+ ElementType opamptypes.ElementType `bun:"element_type,notnull,type:varchar(120),unique:element_version_idx"`
+ DeployStatus opamptypes.DeployStatus `bun:"deploy_status,notnull,type:varchar(80),default:'DIRTY'"`
+ DeploySequence int `bun:"deploy_sequence"`
+ DeployResult string `bun:"deploy_result,type:text"`
+ LastHash string `bun:"last_hash,type:text"`
+ LastConfig string `bun:"last_config,type:text"`
+}
+
+type newAgentConfigVersion41 struct {
+ bun.BaseModel `bun:"table:agent_config_version"`
+
+ types.Identifiable
+ types.TimeAuditable
+ types.UserAuditable
+ OrgID string `json:"orgId" bun:"org_id,type:text,notnull,unique:element_version_org_idx"`
+ Version int `json:"version" bun:"version,unique:element_version_org_idx"`
+ ElementType opamptypes.ElementType `json:"elementType" bun:"element_type,type:text,notnull,unique:element_version_org_idx"`
+ DeployStatus opamptypes.DeployStatus `json:"deployStatus" bun:"deploy_status,type:text,notnull,default:'dirty'"`
+ DeploySequence int `json:"deploySequence" bun:"deploy_sequence"`
+ DeployResult string `json:"deployResult" bun:"deploy_result,type:text"`
+ Hash string `json:"lastHash" bun:"hash,type:text"`
+ Config string `json:"config" bun:"config,type:text"`
+}
+
+type existingAgentConfigElement41 struct {
+ bun.BaseModel `bun:"table:agent_config_elements"`
+
+ ID string `bun:"id,pk,type:text"`
+ CreatedBy string `bun:"created_by,type:text"`
+ CreatedAt time.Time `bun:"created_at,default:CURRENT_TIMESTAMP"`
+ UpdatedBy string `bun:"updated_by,type:text"`
+ UpdatedAt time.Time `bun:"updated_at,default:CURRENT_TIMESTAMP"`
+ ElementID string `bun:"element_id,type:text,notnull,unique:agent_config_elements_u1"`
+ ElementType string `bun:"element_type,type:varchar(120),notnull,unique:agent_config_elements_u1"`
+ VersionID string `bun:"version_id,type:text,notnull,unique:agent_config_elements_u1"`
+}
+
+type newAgentConfigElement41 struct {
+ bun.BaseModel `bun:"table:agent_config_element"`
+
+ types.Identifiable
+ types.TimeAuditable
+ ElementID string `bun:"element_id,type:text,notnull,unique:element_type_version_idx"`
+ ElementType string `bun:"element_type,type:text,notnull,unique:element_type_version_idx"`
+ VersionID string `bun:"version_id,type:text,notnull,unique:element_type_version_idx"`
+}
+
+func NewUpdateAgentsFactory(sqlstore sqlstore.SQLStore) factory.ProviderFactory[SQLMigration, Config] {
+ return factory.NewProviderFactory(factory.MustNewName("update_agents"), func(ctx context.Context, ps factory.ProviderSettings, c Config) (SQLMigration, error) {
+ return newUpdateAgents(ctx, ps, c, sqlstore)
+ })
+}
+
+func newUpdateAgents(_ context.Context, _ factory.ProviderSettings, _ Config, store sqlstore.SQLStore) (SQLMigration, error) {
+ return &updateAgents{
+ store: store,
+ }, nil
+}
+
+func (migration *updateAgents) Register(migrations *migrate.Migrations) error {
+ if err := migrations.Register(migration.Up, migration.Down); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (migration *updateAgents) Up(ctx context.Context, db *bun.DB) error {
+
+ // begin transaction
+ tx, err := db.BeginTx(ctx, nil)
+ if err != nil {
+ return err
+ }
+
+ defer func() {
+ _ = tx.Rollback()
+ }()
+
+ // get all org ids
+ var orgIDs []string
+ if err := tx.NewSelect().Model(new(types.Organization)).Column("id").Scan(ctx, &orgIDs); err != nil {
+ return err
+ }
+
+ // there are multiple orgs, so we don't need to update the agents table
+ if len(orgIDs) > 1 {
+ return errors.Newf(errors.TypeInternal, errors.CodeInternal, "multiple orgs found: %v", orgIDs)
+ }
+
+ err = migration.
+ store.
+ Dialect().
+ RenameTableAndModifyModel(ctx, tx, new(existingAgent41), new(newAgent41), []string{OrgReference}, func(ctx context.Context) error {
+ existingAgents := make([]*existingAgent41, 0)
+ err = tx.
+ NewSelect().
+ Model(&existingAgents).
+ Scan(ctx)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ if err == nil && len(existingAgents) > 0 {
+ newAgents, err := migration.
+ CopyOldAgentToNewAgent(ctx, tx, existingAgents, orgIDs[0])
+ if err != nil {
+ return err
+ }
+ _, err = tx.
+ NewInsert().
+ Model(&newAgents).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ err = migration.
+ store.
+ Dialect().
+ RenameTableAndModifyModel(ctx, tx, new(existingAgentConfigVersions41), new(newAgentConfigVersion41), []string{OrgReference}, func(ctx context.Context) error {
+ existingAgentConfigVersions := make([]*existingAgentConfigVersions41, 0)
+ err = tx.
+ NewSelect().
+ Model(&existingAgentConfigVersions).
+ Scan(ctx)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ if err == nil && len(existingAgentConfigVersions) > 0 {
+ newAgentConfigVersions, err := migration.
+ CopyOldAgentConfigVersionToNewAgentConfigVersion(ctx, tx, existingAgentConfigVersions, orgIDs[0])
+ if err != nil {
+ return err
+ }
+ _, err = tx.
+ NewInsert().
+ Model(&newAgentConfigVersions).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ err = migration.
+ store.
+ Dialect().
+ RenameTableAndModifyModel(ctx, tx, new(existingAgentConfigElement41), new(newAgentConfigElement41), []string{AgentConfigVersionReference}, func(ctx context.Context) error {
+ existingAgentConfigElements := make([]*existingAgentConfigElement41, 0)
+ err = tx.
+ NewSelect().
+ Model(&existingAgentConfigElements).
+ Scan(ctx)
+ if err != nil && err != sql.ErrNoRows {
+ return err
+ }
+
+ if err == nil && len(existingAgentConfigElements) > 0 {
+ newAgentConfigElements, err := migration.
+ CopyOldAgentConfigElementToNewAgentConfigElement(ctx, tx, existingAgentConfigElements, orgIDs[0])
+ if err != nil {
+ return err
+ }
+ _, err = tx.
+ NewInsert().
+ Model(&newAgentConfigElements).
+ Exec(ctx)
+ if err != nil {
+ return err
+ }
+ }
+ return nil
+ })
+ if err != nil {
+ return err
+ }
+
+ if err := tx.Commit(); err != nil {
+ return err
+ }
+
+ return nil
+}
+
+func (migration *updateAgents) Down(ctx context.Context, db *bun.DB) error {
+ return nil
+}
+
+func (migration *updateAgents) CopyOldAgentToNewAgent(ctx context.Context, tx bun.IDB, existingAgents []*existingAgent41, orgID string) ([]*newAgent41, error) {
+ newAgents := make([]*newAgent41, 0)
+ for _, existingAgent := range existingAgents {
+ newAgents = append(newAgents, &newAgent41{
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ AgentID: existingAgent.AgentID,
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: time.Unix(existingAgent.StartedAt.Unix(), 0),
+ UpdatedAt: time.Unix(existingAgent.StartedAt.Unix(), 0),
+ },
+ Status: existingAgent.CurrentStatus,
+ Config: existingAgent.EffectiveConfig,
+ TerminatedAt: existingAgent.TerminatedAt,
+ OrgID: orgID,
+ })
+ }
+ return newAgents, nil
+}
+
+func (migration *updateAgents) CopyOldAgentConfigVersionToNewAgentConfigVersion(ctx context.Context, tx bun.IDB, existingAgentConfigVersions []*existingAgentConfigVersions41, orgID string) ([]*newAgentConfigVersion41, error) {
+ newAgentConfigVersions := make([]*newAgentConfigVersion41, 0)
+ for _, existingAgentConfigVersion := range existingAgentConfigVersions {
+ versionID, err := valuer.NewUUID(existingAgentConfigVersion.ID)
+ if err != nil {
+ return nil, err
+ }
+ newAgentConfigVersions = append(newAgentConfigVersions, &newAgentConfigVersion41{
+ Identifiable: types.Identifiable{ID: versionID},
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: time.Unix(existingAgentConfigVersion.CreatedAt.Unix(), 0),
+ UpdatedAt: time.Unix(existingAgentConfigVersion.UpdatedAt.Unix(), 0),
+ },
+ UserAuditable: types.UserAuditable{
+ CreatedBy: existingAgentConfigVersion.CreatedBy,
+ UpdatedBy: existingAgentConfigVersion.UpdatedBy,
+ },
+ OrgID: orgID,
+ Version: existingAgentConfigVersion.Version,
+ ElementType: existingAgentConfigVersion.ElementType,
+ DeployStatus: existingAgentConfigVersion.DeployStatus,
+ DeploySequence: existingAgentConfigVersion.DeploySequence,
+ DeployResult: existingAgentConfigVersion.DeployResult,
+ Hash: orgID + existingAgentConfigVersion.LastHash,
+ Config: existingAgentConfigVersion.LastConfig,
+ })
+ }
+ return newAgentConfigVersions, nil
+}
+
+func (migration *updateAgents) CopyOldAgentConfigElementToNewAgentConfigElement(ctx context.Context, tx bun.IDB, existingAgentConfigElements []*existingAgentConfigElement41, orgID string) ([]*newAgentConfigElement41, error) {
+ newAgentConfigElements := make([]*newAgentConfigElement41, 0)
+ for _, existingAgentConfigElement := range existingAgentConfigElements {
+ elementID, err := valuer.NewUUID(existingAgentConfigElement.ElementID)
+ if err != nil {
+ return nil, err
+ }
+ newAgentConfigElements = append(newAgentConfigElements, &newAgentConfigElement41{
+ Identifiable: types.Identifiable{ID: elementID},
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: time.Unix(existingAgentConfigElement.CreatedAt.Unix(), 0),
+ UpdatedAt: time.Unix(existingAgentConfigElement.UpdatedAt.Unix(), 0),
+ },
+ VersionID: existingAgentConfigElement.VersionID,
+ ElementID: existingAgentConfigElement.ElementID,
+ ElementType: existingAgentConfigElement.ElementType,
+ })
+ }
+ return newAgentConfigElements, nil
+}
diff --git a/pkg/sqlmigration/sqlmigration.go b/pkg/sqlmigration/sqlmigration.go
index 7a5b5eb70d..5ec189090c 100644
--- a/pkg/sqlmigration/sqlmigration.go
+++ b/pkg/sqlmigration/sqlmigration.go
@@ -25,11 +25,12 @@ var (
)
var (
- OrgReference = "org"
- UserReference = "user"
- UserReferenceNoCascade = "user_no_cascade"
- FactorPasswordReference = "factor_password"
- CloudIntegrationReference = "cloud_integration"
+ OrgReference = "org"
+ UserReference = "user"
+ UserReferenceNoCascade = "user_no_cascade"
+ FactorPasswordReference = "factor_password"
+ CloudIntegrationReference = "cloud_integration"
+ AgentConfigVersionReference = "agent_config_version"
)
func New(
diff --git a/pkg/sqlstore/sqlitesqlstore/dialect.go b/pkg/sqlstore/sqlitesqlstore/dialect.go
index 0e5ee364cf..9e267a0eef 100644
--- a/pkg/sqlstore/sqlitesqlstore/dialect.go
+++ b/pkg/sqlstore/sqlitesqlstore/dialect.go
@@ -18,19 +18,21 @@ const (
)
const (
- Org string = "org"
- User string = "user"
- UserNoCascade string = "user_no_cascade"
- FactorPassword string = "factor_password"
- CloudIntegration string = "cloud_integration"
+ Org string = "org"
+ User string = "user"
+ UserNoCascade string = "user_no_cascade"
+ FactorPassword string = "factor_password"
+ CloudIntegration string = "cloud_integration"
+ AgentConfigVersion string = "agent_config_version"
)
const (
- OrgReference string = `("org_id") REFERENCES "organizations" ("id")`
- UserReference string = `("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE`
- UserNoCascadeReference string = `("user_id") REFERENCES "users" ("id")`
- FactorPasswordReference string = `("password_id") REFERENCES "factor_password" ("id")`
- CloudIntegrationReference string = `("cloud_integration_id") REFERENCES "cloud_integration" ("id") ON DELETE CASCADE`
+ OrgReference string = `("org_id") REFERENCES "organizations" ("id")`
+ UserReference string = `("user_id") REFERENCES "users" ("id") ON DELETE CASCADE ON UPDATE CASCADE`
+ UserNoCascadeReference string = `("user_id") REFERENCES "users" ("id")`
+ FactorPasswordReference string = `("password_id") REFERENCES "factor_password" ("id")`
+ CloudIntegrationReference string = `("cloud_integration_id") REFERENCES "cloud_integration" ("id") ON DELETE CASCADE`
+ AgentConfigVersionReference string = `("version_id") REFERENCES "agent_config_version" ("id")`
)
const (
@@ -269,6 +271,8 @@ func (dialect *dialect) RenameTableAndModifyModel(ctx context.Context, bun bun.I
fkReferences = append(fkReferences, FactorPasswordReference)
} else if reference == CloudIntegration && !slices.Contains(fkReferences, CloudIntegrationReference) {
fkReferences = append(fkReferences, CloudIntegrationReference)
+ } else if reference == AgentConfigVersion && !slices.Contains(fkReferences, AgentConfigVersionReference) {
+ fkReferences = append(fkReferences, AgentConfigVersionReference)
}
}
diff --git a/pkg/sqlstore/sqlstoretest/dialect.go b/pkg/sqlstore/sqlstoretest/dialect.go
index 087ed1444e..4b92d9e530 100644
--- a/pkg/sqlstore/sqlstoretest/dialect.go
+++ b/pkg/sqlstore/sqlstoretest/dialect.go
@@ -53,10 +53,6 @@ func (dialect *dialect) AddPrimaryKey(ctx context.Context, bun bun.IDB, oldModel
return nil
}
-func (dialect *dialect) IndexExists(ctx context.Context, bun bun.IDB, table string, index string) (bool, error) {
- return false, nil
-}
-
func (dialect *dialect) DropColumnWithForeignKeyConstraint(ctx context.Context, bun bun.IDB, model interface{}, column string) error {
return nil
}
diff --git a/pkg/types/agent.go b/pkg/types/agent.go
deleted file mode 100644
index eb869a4983..0000000000
--- a/pkg/types/agent.go
+++ /dev/null
@@ -1,49 +0,0 @@
-package types
-
-import (
- "time"
-
- "github.com/uptrace/bun"
-)
-
-type Agent struct {
- bun.BaseModel `bun:"table:agents"`
- AgentID string `bun:"agent_id,pk,type:text"`
- StartedAt time.Time `bun:"started_at,type:datetime,notnull"`
- TerminatedAt time.Time `bun:"terminated_at,type:datetime"`
- CurrentStatus string `bun:"current_status,type:text,notnull"`
- EffectiveConfig string `bun:"effective_config,type:text,notnull"`
-}
-
-type AgentConfigVersion struct {
- bun.BaseModel `bun:"table:agent_config_versions"`
-
- ID string `bun:"id,pk,type:text"`
- CreatedBy string `bun:"created_by,type:text"`
- CreatedAt time.Time `bun:"created_at,default:CURRENT_TIMESTAMP"`
- UpdatedBy string `bun:"updated_by,type:text"`
- UpdatedAt time.Time `bun:"updated_at,default:CURRENT_TIMESTAMP"`
- Version int `bun:"version,default:1,unique:element_version_idx"`
- Active int `bun:"active"`
- IsValid int `bun:"is_valid"`
- Disabled int `bun:"disabled"`
- ElementType string `bun:"element_type,notnull,type:varchar(120),unique:element_version_idx"`
- DeployStatus string `bun:"deploy_status,notnull,type:varchar(80),default:'DIRTY'"`
- DeploySequence int `bun:"deploy_sequence"`
- DeployResult string `bun:"deploy_result,type:text"`
- LastHash string `bun:"last_hash,type:text"`
- LastConfig string `bun:"last_config,type:text"`
-}
-
-type AgentConfigElement struct {
- bun.BaseModel `bun:"table:agent_config_elements"`
-
- ID string `bun:"id,pk,type:text"`
- CreatedBy string `bun:"created_by,type:text"`
- CreatedAt time.Time `bun:"created_at,default:CURRENT_TIMESTAMP"`
- UpdatedBy string `bun:"updated_by,type:text"`
- UpdatedAt time.Time `bun:"updated_at,default:CURRENT_TIMESTAMP"`
- ElementID string `bun:"element_id,type:text,notnull,unique:agent_config_elements_u1"`
- ElementType string `bun:"element_type,type:varchar(120),notnull,unique:agent_config_elements_u1"`
- VersionID string `bun:"version_id,type:text,notnull,unique:agent_config_elements_u1"`
-}
diff --git a/pkg/types/auditable.go b/pkg/types/auditable.go
index 29c2021575..31c4e4da73 100644
--- a/pkg/types/auditable.go
+++ b/pkg/types/auditable.go
@@ -8,6 +8,6 @@ type TimeAuditable struct {
}
type UserAuditable struct {
- CreatedBy string `bun:"created_by" json:"createdBy"`
- UpdatedBy string `bun:"updated_by" json:"updatedBy"`
+ CreatedBy string `bun:"created_by,type:text" json:"createdBy"`
+ UpdatedBy string `bun:"updated_by,type:text" json:"updatedBy"`
}
diff --git a/pkg/types/opamptypes/agent.go b/pkg/types/opamptypes/agent.go
new file mode 100644
index 0000000000..8d61bceacc
--- /dev/null
+++ b/pkg/types/opamptypes/agent.go
@@ -0,0 +1,129 @@
+package opamptypes
+
+import (
+ "time"
+
+ "github.com/SigNoz/signoz/pkg/sqlstore"
+ "github.com/SigNoz/signoz/pkg/types"
+ "github.com/SigNoz/signoz/pkg/valuer"
+ "github.com/uptrace/bun"
+)
+
+type AgentStatus int
+
+const (
+ AgentStatusUnknown AgentStatus = iota
+ AgentStatusConnected
+ AgentStatusDisconnected
+)
+
+type StorableAgent struct {
+ bun.BaseModel `bun:"table:agent"`
+
+ types.Identifiable
+ types.TimeAuditable
+ // AgentID is needed as the ID from opamp client is ULID and not UUID, so we are keeping it like this
+ AgentID string `json:"agentId" yaml:"agentId" bun:"agent_id,type:text,notnull,unique"`
+ OrgID valuer.UUID `json:"orgId" yaml:"orgId" bun:"org_id,type:text,notnull"`
+ TerminatedAt time.Time `json:"terminatedAt" yaml:"terminatedAt" bun:"terminated_at"`
+ Status AgentStatus `json:"currentStatus" yaml:"currentStatus" bun:"status,type:text,notnull"`
+ Config string `bun:"config,type:text,notnull"`
+}
+
+func NewStorableAgent(store sqlstore.SQLStore, orgID valuer.UUID, agentID string, status AgentStatus) StorableAgent {
+ return StorableAgent{
+ OrgID: orgID,
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ AgentID: agentID,
+ TimeAuditable: types.TimeAuditable{CreatedAt: time.Now(), UpdatedAt: time.Now()},
+ Status: status,
+ }
+}
+
+type ElementType struct{ valuer.String }
+
+var (
+ ElementTypeSamplingRules = ElementType{valuer.NewString("sampling_rules")}
+ ElementTypeDropRules = ElementType{valuer.NewString("drop_rules")}
+ ElementTypeLogPipelines = ElementType{valuer.NewString("log_pipelines")}
+ ElementTypeLbExporter = ElementType{valuer.NewString("lb_exporter")}
+)
+
+// NewElementType creates a new ElementType from a string value.
+// Returns the corresponding ElementType constant if the string matches,
+// otherwise returns an empty ElementType.
+func NewElementType(value string) ElementType {
+ switch valuer.NewString(value) {
+ case ElementTypeSamplingRules.String:
+ return ElementTypeSamplingRules
+ case ElementTypeDropRules.String:
+ return ElementTypeDropRules
+ case ElementTypeLogPipelines.String:
+ return ElementTypeLogPipelines
+ case ElementTypeLbExporter.String:
+ return ElementTypeLbExporter
+ default:
+ return ElementType{valuer.NewString("")}
+ }
+}
+
+type DeployStatus struct{ valuer.String }
+
+var (
+ PendingDeploy = DeployStatus{valuer.NewString("dirty")}
+ Deploying = DeployStatus{valuer.NewString("deploying")}
+ Deployed = DeployStatus{valuer.NewString("deployed")}
+ DeployInitiated = DeployStatus{valuer.NewString("in_progress")}
+ DeployFailed = DeployStatus{valuer.NewString("failed")}
+ DeployStatusUnknown = DeployStatus{valuer.NewString("unknown")}
+)
+
+type AgentConfigVersion struct {
+ bun.BaseModel `bun:"table:agent_config_version,alias:acv"`
+
+ // this is only for reading
+ // keeping it here since we query the actual data from users table
+ CreatedByName string `json:"createdByName" bun:"created_by_name,scanonly"`
+
+ types.Identifiable
+ types.TimeAuditable
+ types.UserAuditable
+ OrgID valuer.UUID `json:"orgId" bun:"org_id,type:text,notnull,unique:element_version_org_idx"`
+ Version int `json:"version" bun:"version,unique:element_version_org_idx"`
+ ElementType ElementType `json:"elementType" bun:"element_type,type:text,notnull,unique:element_version_org_idx"`
+ DeployStatus DeployStatus `json:"deployStatus" bun:"deploy_status,type:text,notnull,default:'dirty'"`
+ DeploySequence int `json:"deploySequence" bun:"deploy_sequence"`
+ DeployResult string `json:"deployResult" bun:"deploy_result,type:text"`
+ Hash string `json:"lastHash" bun:"hash,type:text"`
+ Config string `json:"config" bun:"config,type:text"`
+}
+
+func NewAgentConfigVersion(orgId valuer.UUID, userId valuer.UUID, elementType ElementType) *AgentConfigVersion {
+ return &AgentConfigVersion{
+ TimeAuditable: types.TimeAuditable{
+ CreatedAt: time.Now(),
+ UpdatedAt: time.Now(),
+ },
+ UserAuditable: types.UserAuditable{CreatedBy: userId.String(), UpdatedBy: userId.String()},
+ OrgID: orgId,
+ Identifiable: types.Identifiable{ID: valuer.GenerateUUID()},
+ ElementType: elementType,
+ DeployStatus: PendingDeploy,
+ Hash: "",
+ Config: "{}",
+ }
+}
+
+func (a *AgentConfigVersion) IncrementVersion(lastVersion int) {
+ a.Version = lastVersion + 1
+}
+
+type AgentConfigElement struct {
+ bun.BaseModel `bun:"table:agent_config_element"`
+
+ types.Identifiable
+ types.TimeAuditable
+ ElementID string `bun:"element_id,type:text,notnull,unique:element_type_version_idx"`
+ ElementType string `bun:"element_type,type:text,notnull,unique:element_type_version_idx"`
+ VersionID valuer.UUID `bun:"version_id,type:text,notnull,unique:element_type_version_idx"`
+}