Skip to content

Commit

Permalink
fix: #239 set up loger instance for self-hosted installation
Browse files Browse the repository at this point in the history
  • Loading branch information
bohdan-shulha committed Oct 18, 2024
1 parent 6414637 commit e6703d6
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 14 deletions.
10 changes: 7 additions & 3 deletions internal/app/ptah-agent/metrics.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,9 +82,13 @@ func (m *MetricsAgent) ScrapeMetrics(ctx context.Context) ([]string, error) {
}

func (m *MetricsAgent) Start(ctx context.Context) error {
log := Logger(ctx)

log.Info("starting metrics agent")

metrics, err := m.ScrapeMetrics(ctx)
if err != nil {
log.Printf("failed to collect metrics: %v", err)
log.Info("failed to collect metrics", "error", err)
}

err = m.client.SendMetrics(ctx, metrics)
Expand All @@ -107,14 +111,14 @@ func (m *MetricsAgent) Start(ctx context.Context) error {

metrics, err := m.ScrapeMetrics(ctx)
if err != nil {
log.Printf("failed to collect metrics: %v", err)
log.Error("failed to collect metrics", "error", err)

continue
}

err = m.client.SendMetrics(ctx, metrics)
if err != nil {
log.Printf("failed to send metrics: %v", err)
log.Error("failed to send metrics", "error", err)
}
}
}
Expand Down
19 changes: 18 additions & 1 deletion internal/app/ptah-agent/ptah_client.go
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,9 @@ func New(version string, baseUrl string, ptahToken string, rootDir string) (*Age
// Create a background context for API version negotiation
ctx := context.Background()

slog.Debug("negotiating API version with Docker")
docker.NegotiateAPIVersion(ctx)
slog.Debug("negotiated API version with Docker", "version", docker.ClientVersion())

caddy := caddyClient.New("http://127.0.0.1:2019", http.DefaultClient)

Expand Down Expand Up @@ -172,6 +174,8 @@ func (a *Agent) Start(ctx context.Context) error {
ctx = WithLogger(ctx, slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level})))
log := Logger(ctx)

log.Info("starting ptah agent", "version", a.Version)

a.cancel = cancel

defer a.safeClient.Close()
Expand Down Expand Up @@ -279,6 +283,19 @@ func (a *Agent) getNextTask(ctx context.Context) (taskId int, task interface{},
}

func (a *Agent) ExecTasks(ctx context.Context, jsonFilePath string) error {
// FIXME: de-duplicate logger instantiation with Start()
ptahDebug := os.Getenv("PTAH_DEBUG")

var level slog.Level
if ptahDebug == "true" {
level = slog.LevelDebug
} else {
level = slog.LevelInfo
}

ctx = WithLogger(ctx, slog.New(slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{Level: level})))
log := Logger(ctx)

// Docker client should already be initialized and version negotiated in New()
if a.docker == nil {
return fmt.Errorf("docker client not initialized")
Expand Down Expand Up @@ -322,7 +339,7 @@ func (a *Agent) ExecTasks(ctx context.Context, jsonFilePath string) error {
return fmt.Errorf("error executing task %d: %w", taskRes.ID, err)
}

slog.Info("Task %d (Type: %d) executed successfully. Result: %+v", "task_id", taskRes.ID, "task_type", taskRes.TaskType, "result", result)
log.Info("task executed successfully", "task_id", taskRes.ID, "task_type", taskRes.TaskType, "result", result)
}

return nil
Expand Down
27 changes: 18 additions & 9 deletions internal/app/ptah-agent/service.go
Original file line number Diff line number Diff line change
Expand Up @@ -140,25 +140,34 @@ func (e *taskExecutor) prepareServicePayload(ctx context.Context, servicePayload
secret.SecretID = foundSecret.ID
}

if servicePayload.ReleaseCommand.Command != "" {
image, _, err := e.docker.ImageInspectWithRaw(ctx, spec.TaskTemplate.ContainerSpec.Image)
if err != nil {
return nil, errors.Wrapf(err, "get image %s", spec.TaskTemplate.ContainerSpec.Image)
}
image, _, err := e.docker.ImageInspectWithRaw(ctx, spec.TaskTemplate.ContainerSpec.Image)
if err != nil {
return nil, errors.Wrapf(err, "get image %s", spec.TaskTemplate.ContainerSpec.Image)
}

entrypoint := strings.Join(image.Config.Entrypoint, " ")
command := strings.Join(image.Config.Cmd, " ")
// FIXME: original entrypoint overrides custom command if both (release cmd & cmd) are set
entrypoint := strings.Join(image.Config.Entrypoint, " ")
command := strings.Join(image.Config.Cmd, " ")

originalEntrypoint := entrypoint + " " + command
spec.TaskTemplate.ContainerSpec.Env = append(spec.TaskTemplate.ContainerSpec.Env, fmt.Sprintf("ENTRYPOINT=%s %s", entrypoint, command))

if spec.TaskTemplate.ContainerSpec.Command != nil {
entrypoint = strings.Join(spec.TaskTemplate.ContainerSpec.Command, " ")
}

if spec.TaskTemplate.ContainerSpec.Args != nil {
command = strings.Join(spec.TaskTemplate.ContainerSpec.Args, " ")
}

if servicePayload.ReleaseCommand.Command != "" {
script := []string{
"#!/bin/sh",
"set -e",
"echo 'Starting release command'",
servicePayload.ReleaseCommand.Command,
"echo 'Release command finished'",
"echo 'Starting original entrypoint'",
originalEntrypoint,
fmt.Sprintf("exec %s %s", entrypoint, command),
}

config := swarm.ConfigSpec{
Expand Down
5 changes: 4 additions & 1 deletion internal/app/ptah-agent/service_monitor.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,7 +53,7 @@ func (e *taskExecutor) monitorDaemonServiceLaunch(ctx context.Context, service *
defer ticker.Stop()

// TODO: make timeout configurable
timeout := time.After(time.Duration(10) * time.Minute)
timeout := time.After(time.Duration(1) * time.Minute)

successfullChecks := 0

Expand Down Expand Up @@ -106,6 +106,9 @@ func (e *taskExecutor) monitorDaemonServiceLaunch(ctx context.Context, service *
log.Debug("service inspected", "state", service.UpdateStatus.State)

switch service.UpdateStatus.State {
case swarm.UpdateStatePaused:
// FIXME: rollback the service?
return errors.Errorf("service update paused: %s", service.UpdateStatus.Message)
case swarm.UpdateStateCompleted:
return nil
case swarm.UpdateStateRollbackCompleted:
Expand Down

0 comments on commit e6703d6

Please sign in to comment.