15112: Add config option to save list of lost blocks to a file.
[arvados.git] / services / keep-balance / server.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         "fmt"
9         "net/http"
10         "os"
11         "os/signal"
12         "syscall"
13         "time"
14
15         "git.curoverse.com/arvados.git/sdk/go/arvados"
16         "git.curoverse.com/arvados.git/sdk/go/auth"
17         "git.curoverse.com/arvados.git/sdk/go/httpserver"
18         "github.com/sirupsen/logrus"
19 )
20
21 var version = "dev"
22
23 const (
24         defaultConfigPath = "/etc/arvados/keep-balance/keep-balance.yml"
25         rfc3339NanoFixed  = "2006-01-02T15:04:05.000000000Z07:00"
26 )
27
28 // Config specifies site configuration, like API credentials and the
29 // choice of which servers are to be balanced.
30 //
31 // Config is loaded from a JSON config file (see usage()).
32 type Config struct {
33         // Arvados API endpoint and credentials.
34         Client arvados.Client
35
36         // List of service types (e.g., "disk") to balance.
37         KeepServiceTypes []string
38
39         KeepServiceList arvados.KeepServiceList
40
41         // address, address:port, or :port for management interface
42         Listen string
43
44         // token for management APIs
45         ManagementToken string
46
47         // How often to check
48         RunPeriod arvados.Duration
49
50         // Number of collections to request in each API call
51         CollectionBatchSize int
52
53         // Max collections to buffer in memory (bigger values consume
54         // more memory, but can reduce store-and-forward latency when
55         // fetching pages)
56         CollectionBuffers int
57
58         // Timeout for outgoing http request/response cycle.
59         RequestTimeout arvados.Duration
60
61         // Destination filename for the list of lost block hashes, one
62         // per line. Updated atomically during each successful run.
63         LostBlocksFile string
64 }
65
66 // RunOptions controls runtime behavior. The flags/options that belong
67 // here are the ones that are useful for interactive use. For example,
68 // "CommitTrash" is a runtime option rather than a config item because
69 // it invokes a troubleshooting feature rather than expressing how
70 // balancing is meant to be done at a given site.
71 //
72 // RunOptions fields are controlled by command line flags.
73 type RunOptions struct {
74         Once        bool
75         CommitPulls bool
76         CommitTrash bool
77         Logger      logrus.FieldLogger
78         Dumper      logrus.FieldLogger
79
80         // SafeRendezvousState from the most recent balance operation,
81         // or "" if unknown. If this changes from one run to the next,
82         // we need to watch out for races. See
83         // (*Balancer)ClearTrashLists.
84         SafeRendezvousState string
85 }
86
87 type Server struct {
88         config     Config
89         runOptions RunOptions
90         metrics    *metrics
91         listening  string // for tests
92
93         Logger logrus.FieldLogger
94         Dumper logrus.FieldLogger
95 }
96
97 // NewServer returns a new Server that runs Balancers using the given
98 // config and runOptions.
99 func NewServer(config Config, runOptions RunOptions) (*Server, error) {
100         if len(config.KeepServiceList.Items) > 0 && config.KeepServiceTypes != nil {
101                 return nil, fmt.Errorf("cannot specify both KeepServiceList and KeepServiceTypes in config")
102         }
103         if !runOptions.Once && config.RunPeriod == arvados.Duration(0) {
104                 return nil, fmt.Errorf("you must either use the -once flag, or specify RunPeriod in config")
105         }
106
107         if runOptions.Logger == nil {
108                 log := logrus.New()
109                 log.Formatter = &logrus.JSONFormatter{
110                         TimestampFormat: rfc3339NanoFixed,
111                 }
112                 log.Out = os.Stderr
113                 runOptions.Logger = log
114         }
115
116         srv := &Server{
117                 config:     config,
118                 runOptions: runOptions,
119                 metrics:    newMetrics(),
120                 Logger:     runOptions.Logger,
121                 Dumper:     runOptions.Dumper,
122         }
123         return srv, srv.start()
124 }
125
126 func (srv *Server) start() error {
127         if srv.config.Listen == "" {
128                 return nil
129         }
130         server := &httpserver.Server{
131                 Server: http.Server{
132                         Handler: httpserver.LogRequests(srv.Logger,
133                                 auth.RequireLiteralToken(srv.config.ManagementToken,
134                                         srv.metrics.Handler(srv.Logger))),
135                 },
136                 Addr: srv.config.Listen,
137         }
138         err := server.Start()
139         if err != nil {
140                 return err
141         }
142         srv.Logger.Printf("listening at %s", server.Addr)
143         srv.listening = server.Addr
144         return nil
145 }
146
147 func (srv *Server) Run() (*Balancer, error) {
148         bal := &Balancer{
149                 Logger:         srv.Logger,
150                 Dumper:         srv.Dumper,
151                 Metrics:        srv.metrics,
152                 LostBlocksFile: srv.config.LostBlocksFile,
153         }
154         var err error
155         srv.runOptions, err = bal.Run(srv.config, srv.runOptions)
156         return bal, err
157 }
158
159 // RunForever runs forever, or (for testing purposes) until the given
160 // stop channel is ready to receive.
161 func (srv *Server) RunForever(stop <-chan interface{}) error {
162         logger := srv.runOptions.Logger
163
164         ticker := time.NewTicker(time.Duration(srv.config.RunPeriod))
165
166         // The unbuffered channel here means we only hear SIGUSR1 if
167         // it arrives while we're waiting in select{}.
168         sigUSR1 := make(chan os.Signal)
169         signal.Notify(sigUSR1, syscall.SIGUSR1)
170
171         logger.Printf("starting up: will scan every %v and on SIGUSR1", srv.config.RunPeriod)
172
173         for {
174                 if !srv.runOptions.CommitPulls && !srv.runOptions.CommitTrash {
175                         logger.Print("WARNING: Will scan periodically, but no changes will be committed.")
176                         logger.Print("=======  Consider using -commit-pulls and -commit-trash flags.")
177                 }
178
179                 _, err := srv.Run()
180                 if err != nil {
181                         logger.Print("run failed: ", err)
182                 } else {
183                         logger.Print("run succeeded")
184                 }
185
186                 select {
187                 case <-stop:
188                         signal.Stop(sigUSR1)
189                         return nil
190                 case <-ticker.C:
191                         logger.Print("timer went off")
192                 case <-sigUSR1:
193                         logger.Print("received SIGUSR1, resetting timer")
194                         // Reset the timer so we don't start the N+1st
195                         // run too soon after the Nth run is triggered
196                         // by SIGUSR1.
197                         ticker.Stop()
198                         ticker = time.NewTicker(time.Duration(srv.config.RunPeriod))
199                 }
200                 logger.Print("starting next run")
201         }
202 }