Files
Arvindh 16ba29cf4a
Property Based Tests / api-test (push) Has been cancelled
Continuous Delivery / lint-and-build (push) Has been cancelled
Deploy GitHub Pages / swagger-ui (push) Has been cancelled
CI Pipeline / Lint Proto (push) Has been cancelled
CI Pipeline / Detect Changes (push) Has been cancelled
Continuous Delivery / Build and Push Docker Images (push) Has been cancelled
CI Pipeline / lint-and-build (push) Has been cancelled
CI Pipeline / Test ${{ matrix.module }} (push) Has been cancelled
CI Pipeline / Upload Coverage (push) Has been cancelled
MG-3537 - Migrate Magistrala to ATOM for identity & authorization (#3532)
Signed-off-by: Arvindh <arvindh91@gmail.com>
Signed-off-by: dusan <borovcanindusan1@gmail.com>
Signed-off-by: Rodney Osodo <socials@rodneyosodo.com>
Co-authored-by: Dušan Borovčanin <dusan.borovcanin@absmach.eu>
Co-authored-by: Rodney Osodo <socials@rodneyosodo.com>
Co-authored-by: dusan <borovcanindusan1@gmail.com>
2026-06-26 22:06:57 +02:00

152 lines
4.7 KiB
Go

// Copyright (c) Abstract Machines
// SPDX-License-Identifier: Apache-2.0
// Package main contains postgres-reader main function to start the postgres-reader service.
package main
import (
"context"
"fmt"
"log"
"log/slog"
"os"
chclient "github.com/absmach/callhome/pkg/client"
"github.com/absmach/magistrala"
grpcReadersV1 "github.com/absmach/magistrala/api/grpc/readers/v1"
"github.com/absmach/magistrala/internal/atom"
mglog "github.com/absmach/magistrala/logger"
atomauthn "github.com/absmach/magistrala/pkg/authn/atom"
pgclient "github.com/absmach/magistrala/pkg/postgres"
"github.com/absmach/magistrala/pkg/prometheus"
"github.com/absmach/magistrala/pkg/server"
grpcserver "github.com/absmach/magistrala/pkg/server/grpc"
httpserver "github.com/absmach/magistrala/pkg/server/http"
"github.com/absmach/magistrala/pkg/uuid"
"github.com/absmach/magistrala/readers"
readersgrpcapi "github.com/absmach/magistrala/readers/api/grpc"
httpapi "github.com/absmach/magistrala/readers/api/http"
middleware "github.com/absmach/magistrala/readers/middleware"
"github.com/absmach/magistrala/readers/postgres"
"github.com/caarlos0/env/v11"
"github.com/jmoiron/sqlx"
"golang.org/x/sync/errgroup"
"google.golang.org/grpc"
"google.golang.org/grpc/reflection"
)
const (
svcName = "postgres-reader"
envPrefixDB = "MG_POSTGRES_"
envPrefixHTTP = "MG_POSTGRES_READER_HTTP_"
defDB = "magistrala"
defSvcHTTPPort = "9009"
defSvcGRPCPort = "7009"
envPrefixGrpc = "MG_POSTGRES_READER_GRPC_"
)
type config struct {
LogLevel string `env:"MG_POSTGRES_READER_LOG_LEVEL" envDefault:"info"`
SendTelemetry bool `env:"MG_SEND_TELEMETRY" envDefault:"true"`
InstanceID string `env:"MG_POSTGRES_READER_INSTANCE_ID" envDefault:""`
}
func main() {
ctx, cancel := context.WithCancel(context.Background())
g, ctx := errgroup.WithContext(ctx)
cfg := config{}
if err := env.Parse(&cfg); err != nil {
log.Fatalf("failed to load %s configuration : %s", svcName, err)
}
logger, err := mglog.New(os.Stdout, cfg.LogLevel)
if err != nil {
log.Fatalf("failed to init logger: %s", err.Error())
}
var exitCode int
defer mglog.ExitWithError(&exitCode)
if cfg.InstanceID == "" {
if cfg.InstanceID, err = uuid.New().ID(); err != nil {
logger.Error(fmt.Sprintf("failed to generate instanceID: %s", err))
exitCode = 1
return
}
}
dbConfig := pgclient.Config{}
if err := env.ParseWithOptions(&dbConfig, env.Options{Prefix: envPrefixDB}); err != nil {
logger.Error(err.Error())
exitCode = 1
return
}
db, err := pgclient.Connect(dbConfig)
if err != nil {
logger.Error(fmt.Sprintf("failed to setup postgres database : %s", err))
exitCode = 1
return
}
defer db.Close()
repo := newService(db, logger)
grpcServerConfig := server.Config{Port: defSvcGRPCPort}
if err := env.ParseWithOptions(&grpcServerConfig, env.Options{Prefix: envPrefixGrpc}); err != nil {
logger.Error(fmt.Sprintf("failed to load %s gRPC server configuration : %s", svcName, err.Error()))
exitCode = 1
return
}
registerReadersServiceServer := func(srv *grpc.Server) {
reflection.Register(srv)
grpcReadersV1.RegisterReadersServiceServer(srv, readersgrpcapi.NewReadersServer(repo))
}
atomCfg := atom.LoadConfig()
authn := atomauthn.NewAuthentication()
clientsClient := atom.NewClientsCompat(authn)
channelsClient := atom.NewChannelsCompat(atom.NewClient(atomCfg))
logger.Info("AuthN/AuthZ configured to use Atom")
httpServerConfig := server.Config{Port: defSvcHTTPPort}
if err := env.ParseWithOptions(&httpServerConfig, env.Options{Prefix: envPrefixHTTP}); err != nil {
logger.Error(fmt.Sprintf("failed to load %s HTTP server configuration : %s", svcName, err))
exitCode = 1
return
}
hs := httpserver.NewServer(ctx, cancel, svcName, httpServerConfig, httpapi.MakeHandler(repo, authn, clientsClient, channelsClient, svcName, cfg.InstanceID), logger)
if cfg.SendTelemetry {
chc := chclient.New(svcName, magistrala.Version, logger, cancel)
go chc.CallHome(ctx)
}
gs := grpcserver.NewServer(ctx, cancel, svcName, grpcServerConfig, registerReadersServiceServer, logger)
g.Go(func() error {
return gs.Start()
})
g.Go(func() error {
return hs.Start()
})
g.Go(func() error {
return server.StopSignalHandler(ctx, cancel, logger, svcName, hs)
})
if err := g.Wait(); err != nil {
logger.Error(fmt.Sprintf("Postgres reader service terminated: %s", err))
}
}
func newService(db *sqlx.DB, logger *slog.Logger) readers.MessageRepository {
svc := postgres.New(db)
svc = middleware.LoggingMiddleware(svc, logger)
counter, latency := prometheus.MakeMetrics("postgres", "message_reader")
svc = middleware.MetricsMiddleware(svc, counter, latency)
return svc
}