17840: Fix duplicate error message re parsing command line args.
[arvados.git] / services / keep-balance / main.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package main
6
7 import (
8         "context"
9         "flag"
10         "fmt"
11         "io"
12         "net/http"
13         _ "net/http/pprof"
14         "os"
15
16         "git.arvados.org/arvados.git/lib/config"
17         "git.arvados.org/arvados.git/lib/service"
18         "git.arvados.org/arvados.git/sdk/go/arvados"
19         "git.arvados.org/arvados.git/sdk/go/ctxlog"
20         "git.arvados.org/arvados.git/sdk/go/health"
21         "github.com/jmoiron/sqlx"
22         _ "github.com/lib/pq"
23         "github.com/prometheus/client_golang/prometheus"
24         "github.com/sirupsen/logrus"
25 )
26
27 func main() {
28         os.Exit(runCommand(os.Args[0], os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
29 }
30
31 func runCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
32         logger := ctxlog.FromContext(context.Background())
33
34         var options RunOptions
35         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
36         flags.BoolVar(&options.Once, "once", false,
37                 "balance once and then exit")
38         flags.BoolVar(&options.CommitPulls, "commit-pulls", false,
39                 "send pull requests (make more replicas of blocks that are underreplicated or are not in optimal rendezvous probe order)")
40         flags.BoolVar(&options.CommitTrash, "commit-trash", false,
41                 "send trash requests (delete unreferenced old blocks, and excess replicas of overreplicated blocks)")
42         flags.BoolVar(&options.CommitConfirmedFields, "commit-confirmed-fields", true,
43                 "update collection fields (replicas_confirmed, storage_classes_confirmed, etc.)")
44         dumpFlag := flags.Bool("dump", false, "dump details for each block to stdout")
45         pprofAddr := flags.String("pprof", "", "serve Go profile data at `[addr]:port`")
46         // "show version" is implemented by service.Command, so we
47         // don't need the var here -- we just need the -version flag
48         // to pass flags.Parse().
49         flags.Bool("version", false, "Write version information to stdout and exit 0")
50
51         if *pprofAddr != "" {
52                 go func() {
53                         logrus.Println(http.ListenAndServe(*pprofAddr, nil))
54                 }()
55         }
56
57         loader := config.NewLoader(os.Stdin, logger)
58         loader.SetupFlags(flags)
59
60         munged := loader.MungeLegacyConfigArgs(logger, args, "-legacy-keepbalance-config")
61         err := flags.Parse(munged)
62         if err == flag.ErrHelp {
63                 return 0
64         } else if err != nil {
65                 return 2
66         } else if flags.NArg() != 0 {
67                 fmt.Fprintf(stderr, "unrecognized command line arguments: %v", flags.Args())
68                 return 2
69         }
70
71         if *dumpFlag {
72                 dumper := logrus.New()
73                 dumper.Out = os.Stdout
74                 dumper.Formatter = &logrus.TextFormatter{}
75                 options.Dumper = dumper
76         }
77
78         // Drop our custom args that would be rejected by the generic
79         // service.Command
80         args = nil
81         dropFlag := map[string]bool{
82                 "once":                    true,
83                 "commit-pulls":            true,
84                 "commit-trash":            true,
85                 "commit-confirmed-fields": true,
86                 "dump":                    true,
87         }
88         flags.Visit(func(f *flag.Flag) {
89                 if !dropFlag[f.Name] {
90                         args = append(args, "-"+f.Name+"="+f.Value.String())
91                 }
92         })
93
94         return service.Command(arvados.ServiceNameKeepbalance,
95                 func(ctx context.Context, cluster *arvados.Cluster, token string, registry *prometheus.Registry) service.Handler {
96                         if !options.Once && cluster.Collections.BalancePeriod == arvados.Duration(0) {
97                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("cannot start service: Collections.BalancePeriod is zero (if you want to run once and then exit, use the -once flag)"))
98                         }
99
100                         ac, err := arvados.NewClientFromConfig(cluster)
101                         ac.AuthToken = token
102                         if err != nil {
103                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("error initializing client from cluster config: %s", err))
104                         }
105
106                         db, err := sqlx.Open("postgres", cluster.PostgreSQL.Connection.String())
107                         if err != nil {
108                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection failed: %s", err))
109                         }
110                         if p := cluster.PostgreSQL.ConnectionPool; p > 0 {
111                                 db.SetMaxOpenConns(p)
112                         }
113                         err = db.Ping()
114                         if err != nil {
115                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection succeeded but ping failed: %s", err))
116                         }
117
118                         if options.Logger == nil {
119                                 options.Logger = ctxlog.FromContext(ctx)
120                         }
121
122                         srv := &Server{
123                                 Cluster:    cluster,
124                                 ArvClient:  ac,
125                                 RunOptions: options,
126                                 Metrics:    newMetrics(registry),
127                                 Logger:     options.Logger,
128                                 Dumper:     options.Dumper,
129                                 DB:         db,
130                         }
131                         srv.Handler = &health.Handler{
132                                 Token:  cluster.ManagementToken,
133                                 Prefix: "/_health/",
134                                 Routes: health.Routes{"ping": srv.CheckHealth},
135                         }
136
137                         go srv.run()
138                         return srv
139                 }).RunCommand(prog, args, stdin, stdout, stderr)
140 }