Merge branch 'master' into 14259-pysdk-remote-block-copy
[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
62 // RunOptions controls runtime behavior. The flags/options that belong
63 // here are the ones that are useful for interactive use. For example,
64 // "CommitTrash" is a runtime option rather than a config item because
65 // it invokes a troubleshooting feature rather than expressing how
66 // balancing is meant to be done at a given site.
67 //
68 // RunOptions fields are controlled by command line flags.
69 type RunOptions struct {
70         Once        bool
71         CommitPulls bool
72         CommitTrash bool
73         Logger      *logrus.Logger
74         Dumper      *logrus.Logger
75
76         // SafeRendezvousState from the most recent balance operation,
77         // or "" if unknown. If this changes from one run to the next,
78         // we need to watch out for races. See
79         // (*Balancer)ClearTrashLists.
80         SafeRendezvousState string
81 }
82
83 type Server struct {
84         config     Config
85         runOptions RunOptions
86         metrics    *metrics
87         listening  string // for tests
88
89         Logger *logrus.Logger
90         Dumper *logrus.Logger
91 }
92
93 // NewServer returns a new Server that runs Balancers using the given
94 // config and runOptions.
95 func NewServer(config Config, runOptions RunOptions) (*Server, error) {
96         if len(config.KeepServiceList.Items) > 0 && config.KeepServiceTypes != nil {
97                 return nil, fmt.Errorf("cannot specify both KeepServiceList and KeepServiceTypes in config")
98         }
99         if !runOptions.Once && config.RunPeriod == arvados.Duration(0) {
100                 return nil, fmt.Errorf("you must either use the -once flag, or specify RunPeriod in config")
101         }
102
103         if runOptions.Logger == nil {
104                 log := logrus.New()
105                 log.Formatter = &logrus.JSONFormatter{
106                         TimestampFormat: rfc3339NanoFixed,
107                 }
108                 log.Out = os.Stderr
109                 runOptions.Logger = log
110         }
111
112         srv := &Server{
113                 config:     config,
114                 runOptions: runOptions,
115                 metrics:    newMetrics(),
116                 Logger:     runOptions.Logger,
117                 Dumper:     runOptions.Dumper,
118         }
119         return srv, srv.start()
120 }
121
122 func (srv *Server) start() error {
123         if srv.config.Listen == "" {
124                 return nil
125         }
126         server := &httpserver.Server{
127                 Server: http.Server{
128                         Handler: httpserver.LogRequests(srv.Logger,
129                                 auth.RequireLiteralToken(srv.config.ManagementToken,
130                                         srv.metrics.Handler(srv.Logger))),
131                 },
132                 Addr: srv.config.Listen,
133         }
134         err := server.Start()
135         if err != nil {
136                 return err
137         }
138         srv.Logger.Printf("listening at %s", server.Addr)
139         srv.listening = server.Addr
140         return nil
141 }
142
143 func (srv *Server) Run() (*Balancer, error) {
144         bal := &Balancer{
145                 Logger:  srv.Logger,
146                 Dumper:  srv.Dumper,
147                 Metrics: srv.metrics,
148         }
149         var err error
150         srv.runOptions, err = bal.Run(srv.config, srv.runOptions)
151         return bal, err
152 }
153
154 // RunForever runs forever, or (for testing purposes) until the given
155 // stop channel is ready to receive.
156 func (srv *Server) RunForever(stop <-chan interface{}) error {
157         logger := srv.runOptions.Logger
158
159         ticker := time.NewTicker(time.Duration(srv.config.RunPeriod))
160
161         // The unbuffered channel here means we only hear SIGUSR1 if
162         // it arrives while we're waiting in select{}.
163         sigUSR1 := make(chan os.Signal)
164         signal.Notify(sigUSR1, syscall.SIGUSR1)
165
166         logger.Printf("starting up: will scan every %v and on SIGUSR1", srv.config.RunPeriod)
167
168         for {
169                 if !srv.runOptions.CommitPulls && !srv.runOptions.CommitTrash {
170                         logger.Print("WARNING: Will scan periodically, but no changes will be committed.")
171                         logger.Print("=======  Consider using -commit-pulls and -commit-trash flags.")
172                 }
173
174                 _, err := srv.Run()
175                 if err != nil {
176                         logger.Print("run failed: ", err)
177                 } else {
178                         logger.Print("run succeeded")
179                 }
180
181                 select {
182                 case <-stop:
183                         signal.Stop(sigUSR1)
184                         return nil
185                 case <-ticker.C:
186                         logger.Print("timer went off")
187                 case <-sigUSR1:
188                         logger.Print("received SIGUSR1, resetting timer")
189                         // Reset the timer so we don't start the N+1st
190                         // run too soon after the Nth run is triggered
191                         // by SIGUSR1.
192                         ticker.Stop()
193                         ticker = time.NewTicker(time.Duration(srv.config.RunPeriod))
194                 }
195                 logger.Print("starting next run")
196         }
197 }