1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
16 "git.arvados.org/arvados.git/lib/cmd"
17 "git.arvados.org/arvados.git/lib/config"
18 "git.arvados.org/arvados.git/lib/service"
19 "git.arvados.org/arvados.git/sdk/go/arvados"
20 "git.arvados.org/arvados.git/sdk/go/ctxlog"
21 "git.arvados.org/arvados.git/sdk/go/health"
22 "github.com/jmoiron/sqlx"
24 "github.com/prometheus/client_golang/prometheus"
25 "github.com/sirupsen/logrus"
29 os.Exit(runCommand(os.Args[0], os.Args[1:], os.Stdin, os.Stdout, os.Stderr))
32 func runCommand(prog string, args []string, stdin io.Reader, stdout, stderr io.Writer) int {
33 logger := ctxlog.FromContext(context.Background())
35 var options RunOptions
36 flags := flag.NewFlagSet(prog, flag.ContinueOnError)
37 flags.BoolVar(&options.Once, "once", false,
38 "balance once and then exit")
39 flags.BoolVar(&options.CommitPulls, "commit-pulls", false,
40 "send pull requests (make more replicas of blocks that are underreplicated or are not in optimal rendezvous probe order)")
41 flags.BoolVar(&options.CommitTrash, "commit-trash", false,
42 "send trash requests (delete unreferenced old blocks, and excess replicas of overreplicated blocks)")
43 flags.BoolVar(&options.CommitConfirmedFields, "commit-confirmed-fields", true,
44 "update collection fields (replicas_confirmed, storage_classes_confirmed, etc.)")
45 dumpFlag := flags.Bool("dump", false, "dump details for each block to stdout")
46 pprofAddr := flags.String("pprof", "", "serve Go profile data at `[addr]:port`")
47 // "show version" is implemented by service.Command, so we
48 // don't need the var here -- we just need the -version flag
49 // to pass flags.Parse().
50 flags.Bool("version", false, "Write version information to stdout and exit 0")
54 logrus.Println(http.ListenAndServe(*pprofAddr, nil))
58 loader := config.NewLoader(os.Stdin, logger)
59 loader.SetupFlags(flags)
61 munged := loader.MungeLegacyConfigArgs(logger, args, "-legacy-keepbalance-config")
62 if ok, code := cmd.ParseFlags(flags, prog, munged, "", stderr); !ok {
67 dumper := logrus.New()
68 dumper.Out = os.Stdout
69 dumper.Formatter = &logrus.TextFormatter{}
70 options.Dumper = dumper
73 // Drop our custom args that would be rejected by the generic
76 dropFlag := map[string]bool{
80 "commit-confirmed-fields": true,
83 flags.Visit(func(f *flag.Flag) {
84 if !dropFlag[f.Name] {
85 args = append(args, "-"+f.Name+"="+f.Value.String())
89 return service.Command(arvados.ServiceNameKeepbalance,
90 func(ctx context.Context, cluster *arvados.Cluster, token string, registry *prometheus.Registry) service.Handler {
91 if !options.Once && cluster.Collections.BalancePeriod == arvados.Duration(0) {
92 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)"))
95 ac, err := arvados.NewClientFromConfig(cluster)
98 return service.ErrorHandler(ctx, cluster, fmt.Errorf("error initializing client from cluster config: %s", err))
101 db, err := sqlx.Open("postgres", cluster.PostgreSQL.Connection.String())
103 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection failed: %s", err))
105 if p := cluster.PostgreSQL.ConnectionPool; p > 0 {
106 db.SetMaxOpenConns(p)
110 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection succeeded but ping failed: %s", err))
113 if options.Logger == nil {
114 options.Logger = ctxlog.FromContext(ctx)
121 Metrics: newMetrics(registry),
122 Logger: options.Logger,
123 Dumper: options.Dumper,
126 srv.Handler = &health.Handler{
127 Token: cluster.ManagementToken,
129 Routes: health.Routes{"ping": srv.CheckHealth},
134 }).RunCommand(prog, args, stdin, stdout, stderr)