-
Notifications
You must be signed in to change notification settings - Fork 27
Expand file tree
/
Copy pathconfig_loader.go
More file actions
266 lines (227 loc) · 11.5 KB
/
config_loader.go
File metadata and controls
266 lines (227 loc) · 11.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
// Copyright (c) 2026, WSO2 LLC. (https://www.wso2.com).
//
// WSO2 LLC. licenses this file to you under the Apache License,
// Version 2.0 (the "License"); you may not use this file except
// in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
package config
import (
"fmt"
"log/slog"
"os"
"github.com/joho/godotenv"
)
var (
config *Config
agentWorkloadConfig *AgentWorkload
)
func GetConfig() *Config {
return config
}
func GetAgentWorkloadConfig() *AgentWorkload {
return agentWorkloadConfig
}
func init() {
loadEnvs()
}
func loadEnvs() {
config = &Config{}
agentWorkloadConfig = &AgentWorkload{}
envFilePath := os.Getenv("ENV_FILE_PATH")
if envFilePath != "" {
err := godotenv.Load(envFilePath)
if err != nil {
panic(err)
}
}
r := &configReader{}
config.ServerHost = r.readOptionalString("SERVER_HOST", "")
config.ServerPort = int(r.readOptionalInt64("SERVER_PORT", 8080))
config.AuthHeader = r.readOptionalString("AUTH_HEADER", "Authorization")
config.AutoMaxProcsEnabled = r.readOptionalBool("AUTO_MAX_PROCS_ENABLED", true)
config.CORSAllowedOrigin = r.readOptionalString("CORS_ALLOWED_ORIGIN", "http://localhost:3000")
agentWorkloadConfig.CORS = CORSConfig{
AllowOrigin: r.readOptionalString("AGENT_WORKLOAD_CORS_ALLOWED_ORIGIN", "http://localhost:3000"),
AllowMethods: r.readOptionalString("AGENT_WORKLOAD_CORS_ALLOWED_METHODS", "GET,POST,PUT,DELETE,PATCH,OPTIONS"),
AllowHeaders: r.readOptionalString("AGENT_WORKLOAD_CORS_ALLOWED_HEADERS", "authorization,Content-Type,Origin"),
}
// Logging configuration
config.LogLevel = r.readOptionalString("LOG_LEVEL", "INFO")
// read database configs
config.POSTGRESQL = POSTGRESQL{
Host: r.readRequiredString("DB_HOST"),
Port: int(r.readOptionalInt64("DB_PORT", 5432)),
User: r.readRequiredString("DB_USER"),
Password: r.readRequiredString("DB_PASSWORD"),
DBName: r.readRequiredString("DB_NAME"),
}
config.POSTGRESQL.DbConfigs = DbConfigs{
// gorm configs
SkipDefaultTransaction: r.readOptionalBool("GORM_SKIP_DEFAULT_TRANSACTION", true),
SlowThresholdMilliseconds: r.readOptionalInt64("GORM_SLOW_THRESHOLD_MILLISECONDS", 200),
// sql.DB configs
MaxIdleCount: r.readNullableInt64("DB_MAX_IDLE_COUNT"),
MaxOpenCount: r.readNullableInt64("DB_MAX_OPEN_COUNT"),
MaxIdleTimeSeconds: r.readNullableInt64("DB_MAX_IDLE_TIME_SECONDS"),
MaxLifetimeSeconds: r.readNullableInt64("DB_MAX_LIFETIME_SECONDS"),
}
// HTTP Server timeout configurations
config.ReadTimeoutSeconds = int(r.readOptionalInt64("HTTP_READ_TIMEOUT_SECONDS", 10))
config.WriteTimeoutSeconds = int(r.readOptionalInt64("HTTP_WRITE_TIMEOUT_SECONDS", 90))
config.IdleTimeoutSeconds = int(r.readOptionalInt64("HTTP_IDLE_TIMEOUT_SECONDS", 60))
config.MaxHeaderBytes = int(r.readOptionalInt64("HTTP_MAX_HEADER_BYTES", 65536)) // 1024 * 64
// Database operation timeout configuration
config.DbOperationTimeoutSeconds = int(r.readOptionalInt64("DB_OPERATION_TIMEOUT_SECONDS", 10))
config.HealthCheckTimeoutSeconds = int(r.readOptionalInt64("HEALTH_CHECK_TIMEOUT_SECONDS", 5))
config.DefaultChatAPI = DefaultChatAPIConfig{
DefaultHTTPPort: int32(r.readOptionalInt64("DEFAULT_CHAT_API_HTTP_PORT", 8000)),
DefaultBasePath: r.readOptionalString("DEFAULT_CHAT_API_BASE_PATH", "/"),
}
// OpenTelemetry configuration
// Use Version from ldflags or environment variable override
config.PackageVersion = r.readOptionalString("AMP_VERSION", Version)
config.OTEL = OTELConfig{
SDKVolumeName: r.readOptionalString("OTEL_SDK_VOLUME_NAME", "otel-tracing-sdk-volume"),
SDKMountPath: r.readOptionalString("OTEL_SDK_MOUNT_PATH", "/otel-tracing-sdk"),
// Tracing configuration
IsTraceContentEnabled: r.readOptionalBool("OTEL_TRACELOOP_TRACE_CONTENT", true),
// OTLP Exporter configuration
ExporterEndpoint: r.readOptionalString("OTEL_EXPORTER_OTLP_ENDPOINT", "http://api-platform-default-default-gateway-gateway-runtime.openchoreo-data-plane.svc.cluster.local:22893/otel"),
}
// Observer service configuration - temporarily use localhost for agent-manager-service to access observer service
config.Observer = ObserverConfig{
URL: r.readOptionalString("OBSERVER_URL", "http://localhost:8085"),
}
config.IsLocalDevEnv = r.readOptionalBool("IS_LOCAL_DEV_ENV", false)
config.DefaultGatewayPort = int(r.readOptionalInt64("DEFAULT_GATEWAY_PORT", 19080))
config.KeyManagerConfigurations = KeyManagerConfigurations{
// Comma-separated list of allowed issuers and audiences
Issuer: r.readOptionalStringList("KEY_MANAGER_ISSUER", "Agent Management Platform Local"),
Audience: r.readOptionalStringList("KEY_MANAGER_AUDIENCE", "localhost"),
JWKSUrl: r.readOptionalString("KEY_MANAGER_JWKS_URL", ""),
}
config.IsOnPremDeployment = r.readOptionalBool("IS_ON_PREM_DEPLOYMENT", true)
// IDP OAuth2 client credentials for service-to-service auth
config.IDP = IDPConfig{
TokenURL: r.readOptionalString("IDP_TOKEN_URL", "http://thunder.amp.localhost:8080/oauth2/token"),
ClientID: r.readOptionalString("IDP_CLIENT_ID", "amp-api-client"),
ClientSecret: r.readOptionalString("IDP_CLIENT_SECRET", "amp-api-client-secret"),
}
// JWT Signing configuration for agent API tokens
config.JWTSigning = JWTSigningConfig{
PrivateKeyPath: r.readOptionalString("JWT_SIGNING_PRIVATE_KEY_PATH", "keys/private.pem"),
PublicKeysConfigPath: r.readOptionalString("JWT_SIGNING_PUBLIC_KEYS_CONFIG", "keys/public-keys-config.json"),
ActiveKeyID: r.readOptionalString("JWT_SIGNING_ACTIVE_KEY_ID", "key-1"),
DefaultExpiryDuration: r.readOptionalString("JWT_SIGNING_DEFAULT_EXPIRY", "8760h"), // 1 year default
Issuer: r.readOptionalString("JWT_SIGNING_ISSUER", "agent-manager-service"),
DefaultEnvironment: r.readOptionalString("JWT_SIGNING_DEFAULT_ENVIRONMENT", "default"),
}
// GitHub configuration for repository API access
config.GitHub = GitHubConfig{
Token: r.readOptionalString("GITHUB_TOKEN", ""),
}
config.OpenChoreo = OpenChoreoConfig{
BaseURL: r.readRequiredString("OPEN_CHOREO_BASE_URL"),
}
// Internal Server configuration (for WebSocket and gateway internal APIs)
config.InternalServer = InternalServerConfig{
Host: r.readOptionalString("INTERNAL_SERVER_HOST", ""),
Port: int(r.readOptionalInt64("INTERNAL_SERVER_PORT", 9243)),
TLSEnabled: r.readOptionalBool("INTERNAL_SERVER_TLS_ENABLED", true),
CertDir: r.readOptionalString("INTERNAL_SERVER_CERT_DIR", "./data/certs"),
ReadTimeoutSeconds: int(r.readOptionalInt64("INTERNAL_SERVER_READ_TIMEOUT_SECONDS", 10)),
WriteTimeoutSeconds: int(r.readOptionalInt64("INTERNAL_SERVER_WRITE_TIMEOUT_SECONDS", 90)),
IdleTimeoutSeconds: int(r.readOptionalInt64("INTERNAL_SERVER_IDLE_TIMEOUT_SECONDS", 60)),
MaxHeaderBytes: int(r.readOptionalInt64("INTERNAL_SERVER_MAX_HEADER_BYTES", 65536)),
}
// WebSocket configuration
config.WebSocket = WebSocketConfig{
MaxConnections: int(r.readOptionalInt64("WEBSOCKET_MAX_CONNECTIONS", 1000)),
ConnectionTimeout: int(r.readOptionalInt64("WEBSOCKET_CONNECTION_TIMEOUT", 30)),
RateLimitPerMin: int(r.readOptionalInt64("WEBSOCKET_RATE_LIMIT_PER_MIN", 10)),
}
config.SecretManager = SecretManagerConfig{
Provider: r.readOptionalString("SECRET_MANAGER_PROVIDER", "openbao"),
RefreshInterval: r.readOptionalString("OPENBAO_REFRESH_INTERVAL", "1h"),
BaseURL: r.readOptionalString("SECRET_MANAGER_API_URL", ""),
Timeout: int(r.readOptionalInt64("SECRET_MANAGER_API_TIMEOUT", 30)),
}
// OpenBao KV store configuration (data plane - for deployment secrets)
config.OpenBao = OpenBaoConfig{
URL: r.readOptionalString("OPENBAO_URL", "http://localhost:8200"),
Token: r.readOptionalString("OPENBAO_TOKEN", ""),
Path: r.readOptionalString("OPENBAO_PATH", "secret"),
}
// Workflow plane OpenBao KV store configuration (for git secrets)
config.WorkflowPlaneOpenBao = OpenBaoConfig{
URL: r.readOptionalString("WORKFLOW_PLANE_OPENBAO_URL", "http://localhost:8201"),
Token: r.readOptionalString("WORKFLOW_PLANE_OPENBAO_TOKEN", ""),
}
// Thunder admin API configuration for provisioning per-org OAuth apps
config.Thunder = ThunderConfig{
BaseURL: r.readOptionalString("THUNDER_BASE_URL", ""),
ClientID: r.readOptionalString("THUNDER_CLIENT_ID", ""),
ClientSecret: r.readOptionalString("THUNDER_CLIENT_SECRET", ""),
}
if config.Thunder.BaseURL != "" && (config.Thunder.ClientID == "" || config.Thunder.ClientSecret == "") {
r.errors = append(r.errors, fmt.Errorf("THUNDER_BASE_URL is set but THUNDER_CLIENT_ID and/or THUNDER_CLIENT_SECRET are missing"))
}
config.TLSConfig = TLSConfig{
EnableTLS: r.readOptionalBool("TLS_ENABLED", false),
}
// Encryption key for secrets at rest (hex-encoded 32-byte AES-256 key)
// Encryption key for secrets at rest (hex-encoded 32-byte AES-256 key).
// Validated at runtime in wiring.ProvideEncryptionKey() so that
// non-server commands (e.g. --migrate) can run without the key.
config.EncryptionKey = r.readOptionalString("ENCRYPTION_KEY", "")
// Validate HTTP server configurations
validateHTTPServerConfigs(config, r)
// Validate Internal server configurations
validateInternalServerConfigs(config, r)
r.logAndExitIfErrorsFound()
slog.Info("configReader: configs loaded")
}
func validateHTTPServerConfigs(cfg *Config, r *configReader) {
if cfg.ServerPort < 1 || cfg.ServerPort > 65535 {
r.errors = append(r.errors, fmt.Errorf("SERVER_PORT must be between 1 and 65535, got %d", cfg.ServerPort))
}
if cfg.ReadTimeoutSeconds <= 0 {
r.errors = append(r.errors, fmt.Errorf("HTTP_READ_TIMEOUT_SECONDS must be greater than 0, got %d", cfg.ReadTimeoutSeconds))
}
if cfg.WriteTimeoutSeconds <= 0 {
r.errors = append(r.errors, fmt.Errorf("HTTP_WRITE_TIMEOUT_SECONDS must be greater than 0, got %d", cfg.WriteTimeoutSeconds))
}
if cfg.ReadTimeoutSeconds >= cfg.WriteTimeoutSeconds {
r.errors = append(r.errors, fmt.Errorf("HTTP_READ_TIMEOUT_SECONDS (%d) must be < HTTP_WRITE_TIMEOUT_SECONDS (%d)",
cfg.ReadTimeoutSeconds, cfg.WriteTimeoutSeconds))
}
if cfg.IdleTimeoutSeconds <= 0 {
r.errors = append(r.errors, fmt.Errorf("HTTP_IDLE_TIMEOUT_SECONDS must be greater than 0, got %d", cfg.IdleTimeoutSeconds))
}
if cfg.MaxHeaderBytes < 1024 || cfg.MaxHeaderBytes > 1048576 { // 1KB to 1MB
r.errors = append(r.errors, fmt.Errorf("HTTP_MAX_HEADER_BYTES must be between 1024 and 1048576, got %d", cfg.MaxHeaderBytes))
}
}
func validateInternalServerConfigs(cfg *Config, r *configReader) {
if cfg.InternalServer.Port < 1 || cfg.InternalServer.Port > 65535 {
r.errors = append(r.errors, fmt.Errorf("INTERNAL_SERVER_PORT must be between 1 and 65535, got %d", cfg.InternalServer.Port))
}
if cfg.InternalServer.ReadTimeoutSeconds <= 0 {
r.errors = append(r.errors, fmt.Errorf("INTERNAL_SERVER_READ_TIMEOUT_SECONDS must be greater than 0, got %d", cfg.InternalServer.ReadTimeoutSeconds))
}
if cfg.InternalServer.WriteTimeoutSeconds <= 0 {
r.errors = append(r.errors, fmt.Errorf("INTERNAL_SERVER_WRITE_TIMEOUT_SECONDS must be greater than 0, got %d", cfg.InternalServer.WriteTimeoutSeconds))
}
if cfg.InternalServer.CertDir == "" {
r.errors = append(r.errors, fmt.Errorf("INTERNAL_SERVER_CERT_DIR must be non-empty"))
}
}