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