Add 'tools/arvbox/' from commit 'd3d368758db1f4a9fa5b89f77b5ee61d68ef5b72'
[arvados.git] / services / keepstore / keepstore.go
1 package main
2
3 import (
4         "bytes"
5         "flag"
6         "fmt"
7         "git.curoverse.com/arvados.git/sdk/go/keepclient"
8         "io/ioutil"
9         "log"
10         "net"
11         "net/http"
12         "os"
13         "os/signal"
14         "strings"
15         "syscall"
16         "time"
17 )
18
19 // ======================
20 // Configuration settings
21 //
22 // TODO(twp): make all of these configurable via command line flags
23 // and/or configuration file settings.
24
25 // Default TCP address on which to listen for requests.
26 // Initialized by the --listen flag.
27 const DefaultAddr = ":25107"
28
29 // A Keep "block" is 64MB.
30 const BlockSize = 64 * 1024 * 1024
31
32 // A Keep volume must have at least MinFreeKilobytes available
33 // in order to permit writes.
34 const MinFreeKilobytes = BlockSize / 1024
35
36 // ProcMounts /proc/mounts
37 var ProcMounts = "/proc/mounts"
38
39 // enforcePermissions controls whether permission signatures
40 // should be enforced (affecting GET and DELETE requests).
41 // Initialized by the -enforce-permissions flag.
42 var enforcePermissions bool
43
44 // blobSignatureTTL is the time duration for which new permission
45 // signatures (returned by PUT requests) will be valid.
46 // Initialized by the -permission-ttl flag.
47 var blobSignatureTTL time.Duration
48
49 // dataManagerToken represents the API token used by the
50 // Data Manager, and is required on certain privileged operations.
51 // Initialized by the -data-manager-token-file flag.
52 var dataManagerToken string
53
54 // neverDelete can be used to prevent the DELETE handler from
55 // actually deleting anything.
56 var neverDelete = true
57
58 // trashLifetime is the time duration after a block is trashed
59 // during which it can be recovered using an /untrash request
60 var trashLifetime time.Duration
61
62 var maxBuffers = 128
63 var bufs *bufferPool
64
65 // KeepError types.
66 //
67 type KeepError struct {
68         HTTPCode int
69         ErrMsg   string
70 }
71
72 var (
73         BadRequestError     = &KeepError{400, "Bad Request"}
74         UnauthorizedError   = &KeepError{401, "Unauthorized"}
75         CollisionError      = &KeepError{500, "Collision"}
76         RequestHashError    = &KeepError{422, "Hash mismatch in request"}
77         PermissionError     = &KeepError{403, "Forbidden"}
78         DiskHashError       = &KeepError{500, "Hash mismatch in stored data"}
79         ExpiredError        = &KeepError{401, "Expired permission signature"}
80         NotFoundError       = &KeepError{404, "Not Found"}
81         GenericError        = &KeepError{500, "Fail"}
82         FullError           = &KeepError{503, "Full"}
83         SizeRequiredError   = &KeepError{411, "Missing Content-Length"}
84         TooLongError        = &KeepError{413, "Block is too large"}
85         MethodDisabledError = &KeepError{405, "Method disabled"}
86         ErrNotImplemented   = &KeepError{500, "Unsupported configuration"}
87 )
88
89 func (e *KeepError) Error() string {
90         return e.ErrMsg
91 }
92
93 // ========================
94 // Internal data structures
95 //
96 // These global variables are used by multiple parts of the
97 // program. They are good candidates for moving into their own
98 // packages.
99
100 // The Keep VolumeManager maintains a list of available volumes.
101 // Initialized by the --volumes flag (or by FindKeepVolumes).
102 var KeepVM VolumeManager
103
104 // The pull list manager and trash queue are threadsafe queues which
105 // support atomic update operations. The PullHandler and TrashHandler
106 // store results from Data Manager /pull and /trash requests here.
107 //
108 // See the Keep and Data Manager design documents for more details:
109 // https://arvados.org/projects/arvados/wiki/Keep_Design_Doc
110 // https://arvados.org/projects/arvados/wiki/Data_Manager_Design_Doc
111 //
112 var pullq *WorkQueue
113 var trashq *WorkQueue
114
115 type volumeSet []Volume
116
117 var (
118         flagSerializeIO bool
119         flagReadonly    bool
120         volumes         volumeSet
121 )
122
123 func (vs *volumeSet) String() string {
124         return fmt.Sprintf("%+v", (*vs)[:])
125 }
126
127 // TODO(twp): continue moving as much code as possible out of main
128 // so it can be effectively tested. Esp. handling and postprocessing
129 // of command line flags (identifying Keep volumes and initializing
130 // permission arguments).
131
132 func main() {
133         log.Println("keepstore starting, pid", os.Getpid())
134         defer log.Println("keepstore exiting, pid", os.Getpid())
135
136         var (
137                 dataManagerTokenFile string
138                 listen               string
139                 blobSigningKeyFile   string
140                 permissionTTLSec     int
141                 pidfile              string
142         )
143         flag.StringVar(
144                 &dataManagerTokenFile,
145                 "data-manager-token-file",
146                 "",
147                 "File with the API token used by the Data Manager. All DELETE "+
148                         "requests or GET /index requests must carry this token.")
149         flag.BoolVar(
150                 &enforcePermissions,
151                 "enforce-permissions",
152                 false,
153                 "Enforce permission signatures on requests.")
154         flag.StringVar(
155                 &listen,
156                 "listen",
157                 DefaultAddr,
158                 "Listening address, in the form \"host:port\". e.g., 10.0.1.24:8000. Omit the host part to listen on all interfaces.")
159         flag.BoolVar(
160                 &neverDelete,
161                 "never-delete",
162                 true,
163                 "If true, nothing will be deleted. "+
164                         "Warning: the relevant features in keepstore and data manager have not been extensively tested. "+
165                         "You should leave this option alone unless you can afford to lose data.")
166         flag.StringVar(
167                 &blobSigningKeyFile,
168                 "permission-key-file",
169                 "",
170                 "Synonym for -blob-signing-key-file.")
171         flag.StringVar(
172                 &blobSigningKeyFile,
173                 "blob-signing-key-file",
174                 "",
175                 "File containing the secret key for generating and verifying "+
176                         "blob permission signatures.")
177         flag.IntVar(
178                 &permissionTTLSec,
179                 "permission-ttl",
180                 0,
181                 "Synonym for -blob-signature-ttl.")
182         flag.IntVar(
183                 &permissionTTLSec,
184                 "blob-signature-ttl",
185                 int(time.Duration(2*7*24*time.Hour).Seconds()),
186                 "Lifetime of blob permission signatures. "+
187                         "See services/api/config/application.default.yml.")
188         flag.BoolVar(
189                 &flagSerializeIO,
190                 "serialize",
191                 false,
192                 "Serialize read and write operations on the following volumes.")
193         flag.BoolVar(
194                 &flagReadonly,
195                 "readonly",
196                 false,
197                 "Do not write, delete, or touch anything on the following volumes.")
198         flag.StringVar(
199                 &pidfile,
200                 "pid",
201                 "",
202                 "Path to write pid file during startup. This file is kept open and locked with LOCK_EX until keepstore exits, so `fuser -k pidfile` is one way to shut down. Exit immediately if there is an error opening, locking, or writing the pid file.")
203         flag.IntVar(
204                 &maxBuffers,
205                 "max-buffers",
206                 maxBuffers,
207                 fmt.Sprintf("Maximum RAM to use for data buffers, given in multiples of block size (%d MiB). When this limit is reached, HTTP requests requiring buffers (like GET and PUT) will wait for buffer space to be released.", BlockSize>>20))
208         flag.DurationVar(
209                 &trashLifetime,
210                 "trash-lifetime",
211                 0*time.Second,
212                 "Interval after a block is trashed during which it can be recovered using an /untrash request")
213
214         flag.Parse()
215
216         if maxBuffers < 0 {
217                 log.Fatal("-max-buffers must be greater than zero.")
218         }
219         bufs = newBufferPool(maxBuffers, BlockSize)
220
221         if pidfile != "" {
222                 f, err := os.OpenFile(pidfile, os.O_RDWR|os.O_CREATE, 0777)
223                 if err != nil {
224                         log.Fatalf("open pidfile (%s): %s", pidfile, err)
225                 }
226                 err = syscall.Flock(int(f.Fd()), syscall.LOCK_EX|syscall.LOCK_NB)
227                 if err != nil {
228                         log.Fatalf("flock pidfile (%s): %s", pidfile, err)
229                 }
230                 err = f.Truncate(0)
231                 if err != nil {
232                         log.Fatalf("truncate pidfile (%s): %s", pidfile, err)
233                 }
234                 _, err = fmt.Fprint(f, os.Getpid())
235                 if err != nil {
236                         log.Fatalf("write pidfile (%s): %s", pidfile, err)
237                 }
238                 err = f.Sync()
239                 if err != nil {
240                         log.Fatalf("sync pidfile (%s): %s", pidfile, err)
241                 }
242                 defer f.Close()
243                 defer os.Remove(pidfile)
244         }
245
246         if len(volumes) == 0 {
247                 if (&unixVolumeAdder{&volumes}).Discover() == 0 {
248                         log.Fatal("No volumes found.")
249                 }
250         }
251
252         for _, v := range volumes {
253                 log.Printf("Using volume %v (writable=%v)", v, v.Writable())
254         }
255
256         // Initialize data manager token and permission key.
257         // If these tokens are specified but cannot be read,
258         // raise a fatal error.
259         if dataManagerTokenFile != "" {
260                 if buf, err := ioutil.ReadFile(dataManagerTokenFile); err == nil {
261                         dataManagerToken = strings.TrimSpace(string(buf))
262                 } else {
263                         log.Fatalf("reading data manager token: %s\n", err)
264                 }
265         }
266
267         if neverDelete != true {
268                 log.Print("never-delete is not set. Warning: the relevant features in keepstore and data manager have not " +
269                         "been extensively tested. You should leave this option alone unless you can afford to lose data.")
270         }
271
272         if blobSigningKeyFile != "" {
273                 if buf, err := ioutil.ReadFile(blobSigningKeyFile); err == nil {
274                         PermissionSecret = bytes.TrimSpace(buf)
275                 } else {
276                         log.Fatalf("reading permission key: %s\n", err)
277                 }
278         }
279
280         blobSignatureTTL = time.Duration(permissionTTLSec) * time.Second
281
282         if PermissionSecret == nil {
283                 if enforcePermissions {
284                         log.Fatal("-enforce-permissions requires a permission key")
285                 } else {
286                         log.Println("Running without a PermissionSecret. Block locators " +
287                                 "returned by this server will not be signed, and will be rejected " +
288                                 "by a server that enforces permissions.")
289                         log.Println("To fix this, use the -blob-signing-key-file flag " +
290                                 "to specify the file containing the permission key.")
291                 }
292         }
293
294         // Start a round-robin VolumeManager with the volumes we have found.
295         KeepVM = MakeRRVolumeManager(volumes)
296
297         // Tell the built-in HTTP server to direct all requests to the REST router.
298         loggingRouter := MakeLoggingRESTRouter()
299         http.HandleFunc("/", func(resp http.ResponseWriter, req *http.Request) {
300                 loggingRouter.ServeHTTP(resp, req)
301         })
302
303         // Set up a TCP listener.
304         listener, err := net.Listen("tcp", listen)
305         if err != nil {
306                 log.Fatal(err)
307         }
308
309         // Initialize Pull queue and worker
310         keepClient := &keepclient.KeepClient{
311                 Arvados:       nil,
312                 Want_replicas: 1,
313                 Client:        &http.Client{},
314         }
315
316         // Initialize the pullq and worker
317         pullq = NewWorkQueue()
318         go RunPullWorker(pullq, keepClient)
319
320         // Initialize the trashq and worker
321         trashq = NewWorkQueue()
322         go RunTrashWorker(trashq)
323
324         // Shut down the server gracefully (by closing the listener)
325         // if SIGTERM is received.
326         term := make(chan os.Signal, 1)
327         go func(sig <-chan os.Signal) {
328                 s := <-sig
329                 log.Println("caught signal:", s)
330                 listener.Close()
331         }(term)
332         signal.Notify(term, syscall.SIGTERM)
333         signal.Notify(term, syscall.SIGINT)
334
335         log.Println("listening at", listen)
336         srv := &http.Server{Addr: listen}
337         srv.Serve(listener)
338 }