Files
zitadel/cmd/initialise/init.go
T
11dbb1b277 feat(logging): add streams (#11435)
# Which Problems Are Solved

Streams allow differentiating logs produced by different components of
Zitadel.

# How the Problems Are Solved

The `backend/v3/instrumentation/logging` package now exposes convenience
function for setting and getting a logger from the context. As well as
high-level functions to emit log records at various levels. When
constructing a new logger a "stream" needs to be specified:

- **runtime**: General runtime logs, such as startup and shutdown
messages. Default for logs that do not belong to the other categories.
- **request**: Logs for incoming API and HTTP requests.
- **event_handler**: Logs for event handling in projections.
- **queue**: Logs for the job queue processing.
- **event_pusher**: Logs for event pushing to the database. Disabled by
default, contains sensitive information.

Each line from the returned logger contains a `stream` field as well as
a `version` field with the current Zitadel version.

## Runtime config

Streams can be enabled by passing an array of stream names in the
runtime config. Because some log streams may contain sensitive data
(especially events), it is now also possible to mask values by their
key.

# Additional Changes

- Wrap `slogctx` in the `logging` package. (Except API error converter
packages, because of import cycle)
- Add some docs to `logging` package so other devs understand how to add
logging to Zitadel
- Add `logging.OnError` and `logging.WithError` helper functions with
`Panic()` and `Fatal()` methods, to preserve current calls in the `cmd`
packages.
- Add instance context extractor.
- Only output request details in the request info log. Request ID
remains propagated through context.
- Moved middleware functionality into protocol specific packages. 
- Removed setting of URI to context in metric middleware. There were ony
setters and no getters. (Unused value)
- Reuse a single statusWriter in the middleware package for middlewares
that need to know the response status.

# Additional Context

- Closes #11333
- Closes #11331 
- Partly #11330

---------

Co-authored-by: Silvan <[email protected]>
2026-02-04 11:51:43 +01:00

165 lines
3.5 KiB
Go

package initialise
import (
"context"
"embed"
"errors"
"fmt"
"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/zitadel/zitadel/backend/v3/instrumentation/logging"
"github.com/zitadel/zitadel/internal/database"
)
var (
//go:embed sql/*.sql
stmts embed.FS
createUserStmt string
grantStmt string
databaseStmt string
createEventstoreStmt string
createProjectionsStmt string
createSystemStmt string
createEncryptionKeysStmt string
createEventsStmt string
createUniqueConstraints string
roleAlreadyExistsCode = "42710"
dbAlreadyExistsCode = "42P04"
)
func New() *cobra.Command {
cmd := &cobra.Command{
Use: "init",
Short: "initialize ZITADEL instance",
Long: `Sets up the minimum requirements to start ZITADEL.
Prerequisites:
- PostgreSql database
The user provided by flags needs privileges to
- create the database if it does not exist
- see other users and create a new one if the user does not exist
- grant all rights of the ZITADEL database to the user created if not yet set
`,
RunE: func(cmd *cobra.Command, args []string) (err error) {
defer func() {
logging.OnError(cmd.Context(), err).Error("zitadel init command failed")
}()
config, shutdown, err := NewConfig(cmd, viper.GetViper())
if err != nil {
return err
}
defer func() {
err = errors.Join(err, shutdown(cmd.Context()))
}()
return InitAll(cmd.Context(), config)
},
}
cmd.AddCommand(newZitadel(), newDatabase(), newUser(), newGrant())
return cmd
}
func InitAll(ctx context.Context, config *Config) error {
err := initialise(ctx, config.Database,
VerifyUser(config.Database.Username(), config.Database.Password()),
VerifyDatabase(config.Database.DatabaseName()),
VerifyGrant(config.Database.DatabaseName(), config.Database.Username()),
)
if err != nil {
return fmt.Errorf("initialize database failed: %w", err)
}
err = verifyZitadel(ctx, config.Database)
if err != nil {
return fmt.Errorf("initialize ZITADEL failed: %w", err)
}
return nil
}
func initialise(ctx context.Context, config database.Config, steps ...func(context.Context, *database.DB) error) error {
logging.Info(ctx, "initialization started")
err := ReadStmts()
if err != nil {
return err
}
db, err := database.Connect(config, true)
if err != nil {
return err
}
defer db.Close()
return Init(ctx, db, steps...)
}
func Init(ctx context.Context, db *database.DB, steps ...func(context.Context, *database.DB) error) error {
for _, step := range steps {
if err := step(ctx, db); err != nil {
return err
}
}
return nil
}
func ReadStmts() (err error) {
createUserStmt, err = readStmt("01_user")
if err != nil {
return err
}
databaseStmt, err = readStmt("02_database")
if err != nil {
return err
}
grantStmt, err = readStmt("03_grant_user")
if err != nil {
return err
}
createEventstoreStmt, err = readStmt("04_eventstore")
if err != nil {
return err
}
createProjectionsStmt, err = readStmt("05_projections")
if err != nil {
return err
}
createSystemStmt, err = readStmt("06_system")
if err != nil {
return err
}
createEncryptionKeysStmt, err = readStmt("07_encryption_keys_table")
if err != nil {
return err
}
createEventsStmt, err = readStmt("08_events_table")
if err != nil {
return err
}
createUniqueConstraints, err = readStmt("10_unique_constraints_table")
if err != nil {
return err
}
return nil
}
func readStmt(step string) (string, error) {
stmt, err := stmts.ReadFile("sql/" + step + ".sql")
return string(stmt), err
}