Add 'sdk/java-v2/' from commit '55f103e336ca9fb8bf1720d2ef4ee8dd4e221118'
[arvados.git] / services / keepstore / keepstore.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         "flag"
9         "fmt"
10         "net"
11         "os"
12         "os/signal"
13         "syscall"
14         "time"
15
16         "git.curoverse.com/arvados.git/sdk/go/arvados"
17         "git.curoverse.com/arvados.git/sdk/go/arvadosclient"
18         "git.curoverse.com/arvados.git/sdk/go/config"
19         "git.curoverse.com/arvados.git/sdk/go/keepclient"
20         "github.com/coreos/go-systemd/daemon"
21         "github.com/prometheus/client_golang/prometheus"
22 )
23
24 var version = "dev"
25
26 // A Keep "block" is 64MB.
27 const BlockSize = 64 * 1024 * 1024
28
29 // A Keep volume must have at least MinFreeKilobytes available
30 // in order to permit writes.
31 const MinFreeKilobytes = BlockSize / 1024
32
33 // ProcMounts /proc/mounts
34 var ProcMounts = "/proc/mounts"
35
36 var bufs *bufferPool
37
38 // KeepError types.
39 //
40 type KeepError struct {
41         HTTPCode int
42         ErrMsg   string
43 }
44
45 var (
46         BadRequestError     = &KeepError{400, "Bad Request"}
47         UnauthorizedError   = &KeepError{401, "Unauthorized"}
48         CollisionError      = &KeepError{500, "Collision"}
49         RequestHashError    = &KeepError{422, "Hash mismatch in request"}
50         PermissionError     = &KeepError{403, "Forbidden"}
51         DiskHashError       = &KeepError{500, "Hash mismatch in stored data"}
52         ExpiredError        = &KeepError{401, "Expired permission signature"}
53         NotFoundError       = &KeepError{404, "Not Found"}
54         VolumeBusyError     = &KeepError{503, "Volume backend busy"}
55         GenericError        = &KeepError{500, "Fail"}
56         FullError           = &KeepError{503, "Full"}
57         SizeRequiredError   = &KeepError{411, "Missing Content-Length"}
58         TooLongError        = &KeepError{413, "Block is too large"}
59         MethodDisabledError = &KeepError{405, "Method disabled"}
60         ErrNotImplemented   = &KeepError{500, "Unsupported configuration"}
61         ErrClientDisconnect = &KeepError{503, "Client disconnected"}
62 )
63
64 func (e *KeepError) Error() string {
65         return e.ErrMsg
66 }
67
68 // ========================
69 // Internal data structures
70 //
71 // These global variables are used by multiple parts of the
72 // program. They are good candidates for moving into their own
73 // packages.
74
75 // The Keep VolumeManager maintains a list of available volumes.
76 // Initialized by the --volumes flag (or by FindKeepVolumes).
77 var KeepVM VolumeManager
78
79 // The pull list manager and trash queue are threadsafe queues which
80 // support atomic update operations. The PullHandler and TrashHandler
81 // store results from Data Manager /pull and /trash requests here.
82 //
83 // See the Keep and Data Manager design documents for more details:
84 // https://arvados.org/projects/arvados/wiki/Keep_Design_Doc
85 // https://arvados.org/projects/arvados/wiki/Data_Manager_Design_Doc
86 //
87 var pullq *WorkQueue
88 var trashq *WorkQueue
89
90 func main() {
91         deprecated.beforeFlagParse(theConfig)
92
93         dumpConfig := flag.Bool("dump-config", false, "write current configuration to stdout and exit (useful for migrating from command line flags to config file)")
94         getVersion := flag.Bool("version", false, "Print version information and exit.")
95
96         defaultConfigPath := "/etc/arvados/keepstore/keepstore.yml"
97         var configPath string
98         flag.StringVar(
99                 &configPath,
100                 "config",
101                 defaultConfigPath,
102                 "YAML or JSON configuration file `path`")
103         flag.Usage = usage
104         flag.Parse()
105
106         // Print version information if requested
107         if *getVersion {
108                 fmt.Printf("keepstore %s\n", version)
109                 return
110         }
111
112         deprecated.afterFlagParse(theConfig)
113
114         err := config.LoadFile(theConfig, configPath)
115         if err != nil && (!os.IsNotExist(err) || configPath != defaultConfigPath) {
116                 log.Fatal(err)
117         }
118
119         if *dumpConfig {
120                 log.Fatal(config.DumpAndExit(theConfig))
121         }
122
123         log.Printf("keepstore %s started", version)
124
125         metricsRegistry := prometheus.NewRegistry()
126
127         err = theConfig.Start(metricsRegistry)
128         if err != nil {
129                 log.Fatal(err)
130         }
131
132         if pidfile := theConfig.PIDFile; pidfile != "" {
133                 f, err := os.OpenFile(pidfile, os.O_RDWR|os.O_CREATE, 0777)
134                 if err != nil {
135                         log.Fatalf("open pidfile (%s): %s", pidfile, err)
136                 }
137                 defer f.Close()
138                 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
139                 if err != nil {
140                         log.Fatalf("flock pidfile (%s): %s", pidfile, err)
141                 }
142                 defer os.Remove(pidfile)
143                 err = f.Truncate(0)
144                 if err != nil {
145                         log.Fatalf("truncate pidfile (%s): %s", pidfile, err)
146                 }
147                 _, err = fmt.Fprint(f, os.Getpid())
148                 if err != nil {
149                         log.Fatalf("write pidfile (%s): %s", pidfile, err)
150                 }
151                 err = f.Sync()
152                 if err != nil {
153                         log.Fatalf("sync pidfile (%s): %s", pidfile, err)
154                 }
155         }
156
157         var cluster *arvados.Cluster
158         cfg, err := arvados.GetConfig(arvados.DefaultConfigFile)
159         if err != nil && os.IsNotExist(err) {
160                 log.Warnf("DEPRECATED: proceeding without cluster configuration file %q (%s)", arvados.DefaultConfigFile, err)
161                 cluster = &arvados.Cluster{
162                         ClusterID: "xxxxx",
163                 }
164         } else if err != nil {
165                 log.Fatalf("load config %q: %s", arvados.DefaultConfigFile, err)
166         } else {
167                 cluster, err = cfg.GetCluster("")
168                 if err != nil {
169                         log.Fatalf("config error in %q: %s", arvados.DefaultConfigFile, err)
170                 }
171         }
172
173         log.Println("keepstore starting, pid", os.Getpid())
174         defer log.Println("keepstore exiting, pid", os.Getpid())
175
176         // Start a round-robin VolumeManager with the volumes we have found.
177         KeepVM = MakeRRVolumeManager(theConfig.Volumes)
178
179         // Middleware/handler stack
180         router := MakeRESTRouter(cluster, metricsRegistry)
181
182         // Set up a TCP listener.
183         listener, err := net.Listen("tcp", theConfig.Listen)
184         if err != nil {
185                 log.Fatal(err)
186         }
187
188         // Initialize keepclient for pull workers
189         keepClient := &keepclient.KeepClient{
190                 Arvados:       &arvadosclient.ArvadosClient{},
191                 Want_replicas: 1,
192         }
193
194         // Initialize the pullq and workers
195         pullq = NewWorkQueue()
196         for i := 0; i < 1 || i < theConfig.PullWorkers; i++ {
197                 go RunPullWorker(pullq, keepClient)
198         }
199
200         // Initialize the trashq and workers
201         trashq = NewWorkQueue()
202         for i := 0; i < 1 || i < theConfig.TrashWorkers; i++ {
203                 go RunTrashWorker(trashq)
204         }
205
206         // Start emptyTrash goroutine
207         doneEmptyingTrash := make(chan bool)
208         go emptyTrash(doneEmptyingTrash, theConfig.TrashCheckInterval.Duration())
209
210         // Shut down the server gracefully (by closing the listener)
211         // if SIGTERM is received.
212         term := make(chan os.Signal, 1)
213         go func(sig <-chan os.Signal) {
214                 s := <-sig
215                 log.Println("caught signal:", s)
216                 doneEmptyingTrash <- true
217                 listener.Close()
218         }(term)
219         signal.Notify(term, syscall.SIGTERM)
220         signal.Notify(term, syscall.SIGINT)
221
222         if _, err := daemon.SdNotify(false, "READY=1"); err != nil {
223                 log.Printf("Error notifying init daemon: %v", err)
224         }
225         log.Println("listening at", listener.Addr())
226         srv := &server{}
227         srv.Handler = router
228         srv.Serve(listener)
229 }
230
231 // Periodically (once per interval) invoke EmptyTrash on all volumes.
232 func emptyTrash(done <-chan bool, interval time.Duration) {
233         ticker := time.NewTicker(interval)
234
235         for {
236                 select {
237                 case <-ticker.C:
238                         for _, v := range theConfig.Volumes {
239                                 if v.Writable() {
240                                         v.EmptyTrash()
241                                 }
242                         }
243                 case <-done:
244                         ticker.Stop()
245                         return
246                 }
247         }
248 }