20850: Fix test selector
[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 keepbalance
6
7 import (
8         "bytes"
9         "context"
10         "flag"
11         "fmt"
12         "io"
13         _ "net/http/pprof"
14
15         "git.arvados.org/arvados.git/lib/cmd"
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 )
25
26 type command struct{}
27
28 var Command = command{}
29
30 func (command) RunCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
31         var options RunOptions
32         flags := flag.NewFlagSet(prog, flag.ContinueOnError)
33         flags.BoolVar(&options.Once, "once", false,
34                 "balance once and then exit")
35         flags.BoolVar(&options.CommitPulls, "commit-pulls", false,
36                 "send pull requests (make more replicas of blocks that are underreplicated or are not in optimal rendezvous probe order)")
37         flags.BoolVar(&options.CommitTrash, "commit-trash", false,
38                 "send trash requests (delete unreferenced old blocks, and excess replicas of overreplicated blocks)")
39         flags.BoolVar(&options.CommitConfirmedFields, "commit-confirmed-fields", true,
40                 "update collection fields (replicas_confirmed, storage_classes_confirmed, etc.)")
41         flags.StringVar(&options.ChunkPrefix, "chunk-prefix", "",
42                 "operate only on blocks with the given prefix (experimental, see https://dev.arvados.org/issues/19923)")
43         // These options are implemented by service.Command, so we
44         // don't need the vars here -- we just need the flags
45         // to pass flags.Parse().
46         flags.Bool("dump", false, "dump details for each block to stdout")
47         flags.String("pprof", "", "serve Go profile data at `[addr]:port`")
48         flags.Bool("version", false, "Write version information to stdout and exit 0")
49
50         logger := ctxlog.New(stderr, "json", "info")
51         loader := config.NewLoader(&bytes.Buffer{}, logger)
52         loader.SetupFlags(flags)
53         munged := loader.MungeLegacyConfigArgs(logger, args, "-legacy-keepbalance-config")
54         if ok, code := cmd.ParseFlags(flags, prog, munged, "", stderr); !ok {
55                 return code
56         }
57
58         // Drop our custom args that would be rejected by the generic
59         // service.Command
60         args = nil
61         dropFlag := map[string]bool{
62                 "once":                    true,
63                 "commit-pulls":            true,
64                 "commit-trash":            true,
65                 "commit-confirmed-fields": true,
66                 "dump":                    true,
67         }
68         flags.Visit(func(f *flag.Flag) {
69                 if !dropFlag[f.Name] {
70                         args = append(args, "-"+f.Name+"="+f.Value.String())
71                 }
72         })
73
74         return service.Command(arvados.ServiceNameKeepbalance,
75                 func(ctx context.Context, cluster *arvados.Cluster, token string, registry *prometheus.Registry) service.Handler {
76                         if !options.Once && cluster.Collections.BalancePeriod == arvados.Duration(0) {
77                                 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)"))
78                         }
79
80                         ac, err := arvados.NewClientFromConfig(cluster)
81                         ac.AuthToken = token
82                         if err != nil {
83                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("error initializing client from cluster config: %s", err))
84                         }
85
86                         db, err := sqlx.Open("postgres", cluster.PostgreSQL.Connection.String())
87                         if err != nil {
88                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection failed: %s", err))
89                         }
90                         if p := cluster.PostgreSQL.ConnectionPool; p > 0 {
91                                 db.SetMaxOpenConns(p)
92                         }
93                         err = db.Ping()
94                         if err != nil {
95                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection succeeded but ping failed: %s", err))
96                         }
97
98                         if options.Logger == nil {
99                                 options.Logger = ctxlog.FromContext(ctx)
100                         }
101
102                         srv := &Server{
103                                 Cluster:    cluster,
104                                 ArvClient:  ac,
105                                 RunOptions: options,
106                                 Metrics:    newMetrics(registry),
107                                 Logger:     options.Logger,
108                                 Dumper:     options.Dumper,
109                                 DB:         db,
110                         }
111                         srv.Handler = &health.Handler{
112                                 Token:  cluster.ManagementToken,
113                                 Prefix: "/_health/",
114                                 Routes: health.Routes{"ping": srv.CheckHealth},
115                         }
116
117                         go srv.run(ctx)
118                         return srv
119                 }).RunCommand(prog, args, stdin, stdout, stderr)
120 }