17857: Fix bsub args so containers can use multiple CPU cores.
[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.ExitOnError)
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         flags.Bool("version", false, "Write version information to stdout and exit 0")
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
48         if *pprofAddr != "" {
49                 go func() {
50                         logrus.Println(http.ListenAndServe(*pprofAddr, nil))
51                 }()
52         }
53
54         loader := config.NewLoader(os.Stdin, logger)
55         loader.SetupFlags(flags)
56
57         munged := loader.MungeLegacyConfigArgs(logger, args, "-legacy-keepbalance-config")
58         flags.Parse(munged)
59
60         if *dumpFlag {
61                 dumper := logrus.New()
62                 dumper.Out = os.Stdout
63                 dumper.Formatter = &logrus.TextFormatter{}
64                 options.Dumper = dumper
65         }
66
67         // Drop our custom args that would be rejected by the generic
68         // service.Command
69         args = nil
70         dropFlag := map[string]bool{
71                 "once":                    true,
72                 "commit-pulls":            true,
73                 "commit-trash":            true,
74                 "commit-confirmed-fields": true,
75                 "dump":                    true,
76         }
77         flags.Visit(func(f *flag.Flag) {
78                 if !dropFlag[f.Name] {
79                         args = append(args, "-"+f.Name, f.Value.String())
80                 }
81         })
82
83         return service.Command(arvados.ServiceNameKeepbalance,
84                 func(ctx context.Context, cluster *arvados.Cluster, token string, registry *prometheus.Registry) service.Handler {
85                         if !options.Once && cluster.Collections.BalancePeriod == arvados.Duration(0) {
86                                 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)"))
87                         }
88
89                         ac, err := arvados.NewClientFromConfig(cluster)
90                         ac.AuthToken = token
91                         if err != nil {
92                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("error initializing client from cluster config: %s", err))
93                         }
94
95                         db, err := sqlx.Open("postgres", cluster.PostgreSQL.Connection.String())
96                         if err != nil {
97                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection failed: %s", err))
98                         }
99                         if p := cluster.PostgreSQL.ConnectionPool; p > 0 {
100                                 db.SetMaxOpenConns(p)
101                         }
102                         err = db.Ping()
103                         if err != nil {
104                                 return service.ErrorHandler(ctx, cluster, fmt.Errorf("postgresql connection succeeded but ping failed: %s", err))
105                         }
106
107                         if options.Logger == nil {
108                                 options.Logger = ctxlog.FromContext(ctx)
109                         }
110
111                         srv := &Server{
112                                 Cluster:    cluster,
113                                 ArvClient:  ac,
114                                 RunOptions: options,
115                                 Metrics:    newMetrics(registry),
116                                 Logger:     options.Logger,
117                                 Dumper:     options.Dumper,
118                                 DB:         db,
119                         }
120                         srv.Handler = &health.Handler{
121                                 Token:  cluster.ManagementToken,
122                                 Prefix: "/_health/",
123                                 Routes: health.Routes{"ping": srv.CheckHealth},
124                         }
125
126                         go srv.run()
127                         return srv
128                 }).RunCommand(prog, args, stdin, stdout, stderr)
129 }