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