18 // ======================
19 // Configuration settings
21 // TODO(twp): make all of these configurable via command line flags
22 // and/or configuration file settings.
24 // Default TCP address on which to listen for requests.
25 // Initialized by the --listen flag.
26 const DEFAULT_ADDR = ":25107"
28 // A Keep "block" is 64MB.
29 const BLOCKSIZE = 64 * 1024 * 1024
31 // A Keep volume must have at least MIN_FREE_KILOBYTES available
32 // in order to permit writes.
33 const MIN_FREE_KILOBYTES = BLOCKSIZE / 1024
35 var PROC_MOUNTS = "/proc/mounts"
37 // enforce_permissions controls whether permission signatures
38 // should be enforced (affecting GET and DELETE requests).
39 // Initialized by the --enforce-permissions flag.
40 var enforce_permissions bool
42 // permission_ttl is the time duration for which new permission
43 // signatures (returned by PUT requests) will be valid.
44 // Initialized by the --permission-ttl flag.
45 var permission_ttl time.Duration
47 // data_manager_token represents the API token used by the
48 // Data Manager, and is required on certain privileged operations.
49 // Initialized by the --data-manager-token-file flag.
50 var data_manager_token string
52 // never_delete can be used to prevent the DELETE handler from
53 // actually deleting anything.
54 var never_delete = false
59 type KeepError struct {
65 BadRequestError = &KeepError{400, "Bad Request"}
66 UnauthorizedError = &KeepError{401, "Unauthorized"}
67 CollisionError = &KeepError{500, "Collision"}
68 RequestHashError = &KeepError{422, "Hash mismatch in request"}
69 PermissionError = &KeepError{403, "Forbidden"}
70 DiskHashError = &KeepError{500, "Hash mismatch in stored data"}
71 ExpiredError = &KeepError{401, "Expired permission signature"}
72 NotFoundError = &KeepError{404, "Not Found"}
73 GenericError = &KeepError{500, "Fail"}
74 FullError = &KeepError{503, "Full"}
75 TooLongError = &KeepError{504, "Timeout"}
76 MethodDisabledError = &KeepError{405, "Method disabled"}
79 func (e *KeepError) Error() string {
83 // ========================
84 // Internal data structures
86 // These global variables are used by multiple parts of the
87 // program. They are good candidates for moving into their own
90 // The Keep VolumeManager maintains a list of available volumes.
91 // Initialized by the --volumes flag (or by FindKeepVolumes).
92 var KeepVM VolumeManager
94 // The pull list manager and trash queue are threadsafe queues which
95 // support atomic update operations. The PullHandler and TrashHandler
96 // store results from Data Manager /pull and /trash requests here.
98 // See the Keep and Data Manager design documents for more details:
99 // https://arvados.org/projects/arvados/wiki/Keep_Design_Doc
100 // https://arvados.org/projects/arvados/wiki/Data_Manager_Design_Doc
103 var trashq *WorkQueue
105 // TODO(twp): continue moving as much code as possible out of main
106 // so it can be effectively tested. Esp. handling and postprocessing
107 // of command line flags (identifying Keep volumes and initializing
108 // permission arguments).
111 log.Println("Keep started: pid", os.Getpid())
113 // Parse command-line flags:
115 // -listen=ipaddr:port
116 // Interface on which to listen for requests. Use :port without
117 // an ipaddr to listen on all network interfaces.
119 // -listen=127.0.0.1:4949
120 // -listen=10.0.1.24:8000
121 // -listen=:25107 (to listen to port 25107 on all interfaces)
124 // A comma-separated list of directories to use as Keep volumes.
126 // -volumes=/var/keep01,/var/keep02,/var/keep03/subdir
128 // If -volumes is empty or is not present, Keep will select volumes
129 // by looking at currently mounted filesystems for /keep top-level
133 data_manager_token_file string
135 permission_key_file string
136 permission_ttl_sec int
142 &data_manager_token_file,
143 "data-manager-token-file",
145 "File with the API token used by the Data Manager. All DELETE "+
146 "requests or GET /index requests must carry this token.")
148 &enforce_permissions,
149 "enforce-permissions",
151 "Enforce permission signatures on requests.")
156 "Interface on which to listen for requests, in the format "+
157 "ipaddr:port. e.g. -listen=10.0.1.24:8000. Use -listen=:port "+
158 "to listen on all network interfaces.")
163 "If set, nothing will be deleted. HTTP 405 will be returned "+
164 "for valid DELETE requests.")
166 &permission_key_file,
167 "permission-key-file",
169 "File containing the secret key for generating and verifying "+
170 "permission signatures.")
175 "Expiration time (in seconds) for newly generated permission "+
181 "If set, all read and write operations on local Keep volumes will "+
187 "Comma-separated list of directories to use for Keep volumes, "+
188 "e.g. -volumes=/var/keep1,/var/keep2. If empty or not "+
189 "supplied, Keep will scan mounted filesystems for volumes "+
190 "with a /keep top-level directory.")
196 "Path to write pid file")
200 // Look for local keep volumes.
201 var keepvols []string
203 // TODO(twp): decide whether this is desirable default behavior.
204 // In production we may want to require the admin to specify
205 // Keep volumes explicitly.
206 keepvols = FindKeepVolumes()
208 keepvols = strings.Split(volumearg, ",")
211 // Check that the specified volumes actually exist.
212 var goodvols []Volume = nil
213 for _, v := range keepvols {
214 if _, err := os.Stat(v); err == nil {
215 log.Println("adding Keep volume:", v)
216 newvol := MakeUnixVolume(v, serialize_io)
217 goodvols = append(goodvols, &newvol)
219 log.Printf("bad Keep volume: %s\n", err)
223 if len(goodvols) == 0 {
224 log.Fatal("could not find any keep volumes")
227 // Initialize data manager token and permission key.
228 // If these tokens are specified but cannot be read,
229 // raise a fatal error.
230 if data_manager_token_file != "" {
231 if buf, err := ioutil.ReadFile(data_manager_token_file); err == nil {
232 data_manager_token = strings.TrimSpace(string(buf))
234 log.Fatalf("reading data manager token: %s\n", err)
237 if permission_key_file != "" {
238 if buf, err := ioutil.ReadFile(permission_key_file); err == nil {
239 PermissionSecret = bytes.TrimSpace(buf)
241 log.Fatalf("reading permission key: %s\n", err)
245 // Initialize permission TTL
246 permission_ttl = time.Duration(permission_ttl_sec) * time.Second
248 // If --enforce-permissions is true, we must have a permission key
250 if PermissionSecret == nil {
251 if enforce_permissions {
252 log.Fatal("--enforce-permissions requires a permission key")
254 log.Println("Running without a PermissionSecret. Block locators " +
255 "returned by this server will not be signed, and will be rejected " +
256 "by a server that enforces permissions.")
257 log.Println("To fix this, run Keep with --permission-key-file=<path> " +
258 "to define the location of a file containing the permission key.")
262 // Start a round-robin VolumeManager with the volumes we have found.
263 KeepVM = MakeRRVolumeManager(goodvols)
265 // Tell the built-in HTTP server to direct all requests to the REST
267 http.Handle("/", MakeRESTRouter())
269 // Set up a TCP listener.
270 listener, err := net.Listen("tcp", listen)
275 // Shut down the server gracefully (by closing the listener)
276 // if SIGTERM is received.
277 term := make(chan os.Signal, 1)
278 go func(sig <-chan os.Signal) {
280 log.Println("caught signal:", s)
283 signal.Notify(term, syscall.SIGTERM)
286 f, err := os.Create(pidfile)
288 fmt.Fprint(f, os.Getpid())
291 log.Printf("Error writing pid file (%s): %s", pidfile, err.Error())
295 // Start listening for requests.
296 srv := &http.Server{Addr: listen}
299 log.Println("shutting down")