7179: several golint suggested updates such as "don't use ALL_CAPS in Go names; use...
authorradhika <radhika@curoverse.com>
Sat, 12 Sep 2015 15:02:22 +0000 (11:02 -0400)
committerradhika <radhika@curoverse.com>
Sat, 12 Sep 2015 15:02:22 +0000 (11:02 -0400)
Now keepstore.go and handlers.go are almost lint free; a few such as blob_signature_ttl are not renamed at this time.

services/keepstore/bufferpool_test.go
services/keepstore/handler_test.go
services/keepstore/handlers.go
services/keepstore/keepstore.go
services/keepstore/keepstore_test.go
services/keepstore/volume.go
services/keepstore/volume_unix.go

index 95d118e221de6b8516654f8a133b871da00c5cd2..8726a19150c7faf2f309cc6b3ba647d9aa40dd54 100644 (file)
@@ -18,12 +18,12 @@ type BufferPoolSuite struct{}
 // Initialize a default-sized buffer pool for the benefit of test
 // suites that don't run main().
 func init() {
-       bufs = newBufferPool(maxBuffers, BLOCKSIZE)
+       bufs = newBufferPool(maxBuffers, BlockSize)
 }
 
 // Restore sane default after bufferpool's own tests
 func (s *BufferPoolSuite) TearDownTest(c *C) {
-       bufs = newBufferPool(maxBuffers, BLOCKSIZE)
+       bufs = newBufferPool(maxBuffers, BlockSize)
 }
 
 func (s *BufferPoolSuite) TestBufferPoolBufSize(c *C) {
index 68e80c410c0ba37a7a7f72c327e90cd53d4ddb62..8191466af634da400e94cf35b25ac6363311a196 100644 (file)
@@ -52,7 +52,7 @@ func TestGetHandler(t *testing.T) {
 
        // Create locators for testing.
        // Turn on permission settings so we can generate signed locators.
-       enforce_permissions = true
+       enforcePermissions = true
        PermissionSecret = []byte(known_key)
        blob_signature_ttl = 300 * time.Second
 
@@ -66,7 +66,7 @@ func TestGetHandler(t *testing.T) {
 
        // -----------------
        // Test unauthenticated request with permissions off.
-       enforce_permissions = false
+       enforcePermissions = false
 
        // Unauthenticated request, unsigned locator
        // => OK
@@ -90,7 +90,7 @@ func TestGetHandler(t *testing.T) {
 
        // ----------------
        // Permissions: on.
-       enforce_permissions = true
+       enforcePermissions = true
 
        // Authenticated request, signed locator
        // => OK
@@ -274,7 +274,7 @@ func TestPutAndDeleteSkipReadonlyVolumes(t *testing.T) {
 //   - authenticated   /index/prefix request | superuser
 //
 // The only /index requests that should succeed are those issued by the
-// superuser. They should pass regardless of the value of enforce_permissions.
+// superuser. They should pass regardless of the value of enforcePermissions.
 //
 func TestIndexHandler(t *testing.T) {
        defer teardown()
@@ -326,15 +326,15 @@ func TestIndexHandler(t *testing.T) {
        // Only the superuser should be allowed to issue /index requests.
 
        // ---------------------------
-       // enforce_permissions enabled
+       // enforcePermissions enabled
        // This setting should not affect tests passing.
-       enforce_permissions = true
+       enforcePermissions = true
 
        // unauthenticated /index request
        // => UnauthorizedError
        response := IssueRequest(unauthenticatedReq)
        ExpectStatusCode(t,
-               "enforce_permissions on, unauthenticated request",
+               "enforcePermissions on, unauthenticated request",
                UnauthorizedError.HTTPCode,
                response)
 
@@ -371,9 +371,9 @@ func TestIndexHandler(t *testing.T) {
                response)
 
        // ----------------------------
-       // enforce_permissions disabled
+       // enforcePermissions disabled
        // Valid Request should still pass.
-       enforce_permissions = false
+       enforcePermissions = false
 
        // superuser /index request
        // => OK
@@ -822,7 +822,7 @@ func TestPutNeedsOnlyOneBuffer(t *testing.T) {
        defer func(orig *bufferPool) {
                bufs = orig
        }(bufs)
-       bufs = newBufferPool(1, BLOCKSIZE)
+       bufs = newBufferPool(1, BlockSize)
 
        ok := make(chan struct{})
        go func() {
index 3dcc6e1a2daf266a35edc399a47182c4d89a24cc..0974549fdb2c5a0042913cc0a950369665eb08c6 100644 (file)
@@ -60,12 +60,14 @@ func MakeRESTRouter() *mux.Router {
        return rest
 }
 
+// BadRequestHandler is a HandleFunc to address bad requests.
 func BadRequestHandler(w http.ResponseWriter, r *http.Request) {
        http.Error(w, BadRequestError.Error(), BadRequestError.HTTPCode)
 }
 
+// GetBlockHandler is a HandleFunc to address Get block requests.
 func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
-       if enforce_permissions {
+       if enforcePermissions {
                locator := req.URL.Path[1:] // strip leading slash
                if err := VerifySignature(locator, GetApiToken(req)); err != nil {
                        http.Error(resp, err.Error(), err.(*KeepError).HTTPCode)
@@ -87,6 +89,7 @@ func GetBlockHandler(resp http.ResponseWriter, req *http.Request) {
        resp.Write(block)
 }
 
+// PutBlockHandler is a HandleFunc to address Put block requests.
 func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
        hash := mux.Vars(req)["hash"]
 
@@ -99,7 +102,7 @@ func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
                return
        }
 
-       if req.ContentLength > BLOCKSIZE {
+       if req.ContentLength > BlockSize {
                http.Error(resp, TooLongError.Error(), TooLongError.HTTPCode)
                return
        }
@@ -128,18 +131,16 @@ func PutBlockHandler(resp http.ResponseWriter, req *http.Request) {
 
        // Success; add a size hint, sign the locator if possible, and
        // return it to the client.
-       return_hash := fmt.Sprintf("%s+%d", hash, req.ContentLength)
-       api_token := GetApiToken(req)
-       if PermissionSecret != nil && api_token != "" {
+       returnHash := fmt.Sprintf("%s+%d", hash, req.ContentLength)
+       apiToken := GetApiToken(req)
+       if PermissionSecret != nil && apiToken != "" {
                expiry := time.Now().Add(blob_signature_ttl)
-               return_hash = SignLocator(return_hash, api_token, expiry)
+               returnHash = SignLocator(returnHash, apiToken, expiry)
        }
-       resp.Write([]byte(return_hash + "\n"))
+       resp.Write([]byte(returnHash + "\n"))
 }
 
-// IndexHandler
-//     A HandleFunc to address /index and /index/{prefix} requests.
-//
+// IndexHandler is a HandleFunc to address /index and /index/{prefix} requests.
 func IndexHandler(resp http.ResponseWriter, req *http.Request) {
        // Reject unauthorized requests.
        if !IsDataManagerToken(GetApiToken(req)) {
@@ -178,12 +179,14 @@ func IndexHandler(resp http.ResponseWriter, req *http.Request) {
 //            * bytes_free
 //            * bytes_used
 
+// PoolStatus struct
 type PoolStatus struct {
        Alloc uint64 `json:"BytesAllocated"`
        Cap   int    `json:"BuffersMax"`
        Len   int    `json:"BuffersInUse"`
 }
 
+// NodeStatus struct
 type NodeStatus struct {
        Volumes    []*VolumeStatus `json:"volumes"`
        BufferPool PoolStatus
@@ -195,6 +198,7 @@ type NodeStatus struct {
 var st NodeStatus
 var stLock sync.Mutex
 
+// StatusHandler addresses /status.json requests.
 func StatusHandler(resp http.ResponseWriter, req *http.Request) {
        stLock.Lock()
        readNodeStatus(&st)
@@ -353,11 +357,13 @@ func DeleteHandler(resp http.ResponseWriter, req *http.Request) {
    If the JSON unmarshalling fails, return 400 Bad Request.
 */
 
+// PullRequest consists of a block locator and an ordered list of servers
 type PullRequest struct {
        Locator string   `json:"locator"`
        Servers []string `json:"servers"`
 }
 
+// PullHandler processes "PUT /pull" requests for the data manager.
 func PullHandler(resp http.ResponseWriter, req *http.Request) {
        // Reject unauthorized requests.
        if !IsDataManagerToken(GetApiToken(req)) {
@@ -387,11 +393,13 @@ func PullHandler(resp http.ResponseWriter, req *http.Request) {
        pullq.ReplaceQueue(plist)
 }
 
+// TrashRequest consists of a block locator and it's Mtime
 type TrashRequest struct {
        Locator    string `json:"locator"`
        BlockMtime int64  `json:"block_mtime"`
 }
 
+// TrashHandler processes /trash requests.
 func TrashHandler(resp http.ResponseWriter, req *http.Request) {
        // Reject unauthorized requests.
        if !IsDataManagerToken(GetApiToken(req)) {
@@ -432,8 +440,8 @@ func TrashHandler(resp http.ResponseWriter, req *http.Request) {
 // should be the only part of the code that cares about which volume a
 // block is stored on, so it should be responsible for figuring out
 // which volume to check for fetching blocks, storing blocks, etc.
-
 // ==============================
+
 // GetBlock fetches and returns the block identified by "hash".
 //
 // On success, GetBlock returns a byte slice with the block data, and
@@ -444,10 +452,9 @@ func TrashHandler(resp http.ResponseWriter, req *http.Request) {
 // If the block found does not have the correct MD5 hash, returns
 // DiskHashError.
 //
-
 func GetBlock(hash string) ([]byte, error) {
        // Attempt to read the requested hash from a keep volume.
-       error_to_caller := NotFoundError
+       errorToCaller := NotFoundError
 
        for _, vol := range KeepVM.AllReadable() {
                buf, err := vol.Get(hash)
@@ -470,45 +477,46 @@ func GetBlock(hash string) ([]byte, error) {
                        // this.
                        log.Printf("%s: checksum mismatch for request %s (actual %s)",
                                vol, hash, filehash)
-                       error_to_caller = DiskHashError
+                       errorToCaller = DiskHashError
                        bufs.Put(buf)
                        continue
                }
-               if error_to_caller == DiskHashError {
+               if errorToCaller == DiskHashError {
                        log.Printf("%s: checksum mismatch for request %s but a good copy was found on another volume and returned",
                                vol, hash)
                }
                return buf, nil
        }
-       return nil, error_to_caller
+       return nil, errorToCaller
 }
 
-/* PutBlock(block, hash)
-   Stores the BLOCK (identified by the content id HASH) in Keep.
-
-   The MD5 checksum of the block must be identical to the content id HASH.
-   If not, an error is returned.
-
-   PutBlock stores the BLOCK on the first Keep volume with free space.
-   A failure code is returned to the user only if all volumes fail.
-
-   On success, PutBlock returns nil.
-   On failure, it returns a KeepError with one of the following codes:
-
-   500 Collision
-          A different block with the same hash already exists on this
-          Keep server.
-   422 MD5Fail
-          The MD5 hash of the BLOCK does not match the argument HASH.
-   503 Full
-          There was not enough space left in any Keep volume to store
-          the object.
-   500 Fail
-          The object could not be stored for some other reason (e.g.
-          all writes failed). The text of the error message should
-          provide as much detail as possible.
-*/
-
+// PutBlock Stores the BLOCK (identified by the content id HASH) in Keep.
+//
+// PutBlock(block, hash)
+//   Stores the BLOCK (identified by the content id HASH) in Keep.
+//
+//   The MD5 checksum of the block must be identical to the content id HASH.
+//   If not, an error is returned.
+//
+//   PutBlock stores the BLOCK on the first Keep volume with free space.
+//   A failure code is returned to the user only if all volumes fail.
+//
+//   On success, PutBlock returns nil.
+//   On failure, it returns a KeepError with one of the following codes:
+//
+//   500 Collision
+//          A different block with the same hash already exists on this
+//          Keep server.
+//   422 MD5Fail
+//          The MD5 hash of the BLOCK does not match the argument HASH.
+//   503 Full
+//          There was not enough space left in any Keep volume to store
+//          the object.
+//   500 Fail
+//          The object could not be stored for some other reason (e.g.
+//          all writes failed). The text of the error message should
+//          provide as much detail as possible.
+//
 func PutBlock(block []byte, hash string) error {
        // Check that BLOCK's checksum matches HASH.
        blockhash := fmt.Sprintf("%x", md5.Sum(block))
@@ -556,10 +564,9 @@ func PutBlock(block []byte, hash string) error {
        if allFull {
                log.Print("All volumes are full.")
                return FullError
-       } else {
-               // Already logged the non-full errors.
-               return GenericError
        }
+       // Already logged the non-full errors.
+       return GenericError
 }
 
 // CompareAndTouch returns nil if one of the volumes already has the
@@ -601,10 +608,9 @@ func CompareAndTouch(hash string, buf []byte) error {
 
 var validLocatorRe = regexp.MustCompile(`^[0-9a-f]{32}$`)
 
-// IsValidLocator
-//     Return true if the specified string is a valid Keep locator.
-//     When Keep is extended to support hash types other than MD5,
-//     this should be updated to cover those as well.
+// IsValidLocator returns true if the specified string is a valid Keep locator.
+//   When Keep is extended to support hash types other than MD5,
+//   this should be updated to cover those as well.
 //
 func IsValidLocator(loc string) bool {
        return validLocatorRe.MatchString(loc)
@@ -612,7 +618,7 @@ func IsValidLocator(loc string) bool {
 
 var authRe = regexp.MustCompile(`^OAuth2\s+(.*)`)
 
-// GetApiToken returns the OAuth2 token from the Authorization
+// GetAPIToken returns the OAuth2 token from the Authorization
 // header of a HTTP request, or an empty string if no matching
 // token is found.
 func GetApiToken(req *http.Request) string {
@@ -625,10 +631,10 @@ func GetApiToken(req *http.Request) string {
 }
 
 // IsExpired returns true if the given Unix timestamp (expressed as a
-// hexadecimal string) is in the past, or if timestamp_hex cannot be
+// hexadecimal string) is in the past, or if timestampHex cannot be
 // parsed as a hexadecimal string.
-func IsExpired(timestamp_hex string) bool {
-       ts, err := strconv.ParseInt(timestamp_hex, 16, 0)
+func IsExpired(timestampHex string) bool {
+       ts, err := strconv.ParseInt(timestampHex, 16, 0)
        if err != nil {
                log.Printf("IsExpired: %s", err)
                return true
@@ -636,25 +642,25 @@ func IsExpired(timestamp_hex string) bool {
        return time.Unix(ts, 0).Before(time.Now())
 }
 
-// CanDelete returns true if the user identified by api_token is
+// CanDelete returns true if the user identified by apiToken is
 // allowed to delete blocks.
-func CanDelete(api_token string) bool {
-       if api_token == "" {
+func CanDelete(apiToken string) bool {
+       if apiToken == "" {
                return false
        }
        // Blocks may be deleted only when Keep has been configured with a
        // data manager.
-       if IsDataManagerToken(api_token) {
+       if IsDataManagerToken(apiToken) {
                return true
        }
-       // TODO(twp): look up api_token with the API server
+       // TODO(twp): look up apiToken with the API server
        // return true if is_admin is true and if the token
        // has unlimited scope
        return false
 }
 
-// IsDataManagerToken returns true if api_token represents the data
+// IsDataManagerToken returns true if apiToken represents the data
 // manager's token.
-func IsDataManagerToken(api_token string) bool {
-       return data_manager_token != "" && api_token == data_manager_token
+func IsDataManagerToken(apiToken string) bool {
+       return data_manager_token != "" && apiToken == data_manager_token
 }
index 53cf7be6ca09c62828787f1c9229cce13193b480..9c84534a02430acc4fc3fac632980c1201891b4f 100644 (file)
@@ -27,21 +27,22 @@ import (
 
 // Default TCP address on which to listen for requests.
 // Initialized by the --listen flag.
-const DEFAULT_ADDR = ":25107"
+const DefaultAddr = ":25107"
 
 // A Keep "block" is 64MB.
-const BLOCKSIZE = 64 * 1024 * 1024
+const BlockSize = 64 * 1024 * 1024
 
-// A Keep volume must have at least MIN_FREE_KILOBYTES available
+// A Keep volume must have at least MinFreeKilobytes available
 // in order to permit writes.
-const MIN_FREE_KILOBYTES = BLOCKSIZE / 1024
+const MinFreeKilobytes = BlockSize / 1024
 
-var PROC_MOUNTS = "/proc/mounts"
+// ProcMounts /proc/mounts
+var ProcMounts = "/proc/mounts"
 
-// enforce_permissions controls whether permission signatures
+// enforcePermissions controls whether permission signatures
 // should be enforced (affecting GET and DELETE requests).
 // Initialized by the -enforce-permissions flag.
-var enforce_permissions bool
+var enforcePermissions bool
 
 // blob_signature_ttl is the time duration for which new permission
 // signatures (returned by PUT requests) will be valid.
@@ -60,8 +61,7 @@ var never_delete = true
 var maxBuffers = 128
 var bufs *bufferPool
 
-// ==========
-// Error types.
+// KeepError types.
 //
 type KeepError struct {
        HTTPCode int
@@ -161,15 +161,15 @@ func (vs *volumeSet) String() string {
 // other than "/". It returns the number of volumes added.
 func (vs *volumeSet) Discover() int {
        added := 0
-       f, err := os.Open(PROC_MOUNTS)
+       f, err := os.Open(ProcMounts)
        if err != nil {
-               log.Fatalf("opening %s: %s", PROC_MOUNTS, err)
+               log.Fatalf("opening %s: %s", ProcMounts, err)
        }
        scanner := bufio.NewScanner(f)
        for scanner.Scan() {
                args := strings.Fields(scanner.Text())
                if err := scanner.Err(); err != nil {
-                       log.Fatalf("reading %s: %s", PROC_MOUNTS, err)
+                       log.Fatalf("reading %s: %s", ProcMounts, err)
                }
                dev, mount := args[0], args[1]
                if mount == "/" {
@@ -225,14 +225,14 @@ func main() {
                "File with the API token used by the Data Manager. All DELETE "+
                        "requests or GET /index requests must carry this token.")
        flag.BoolVar(
-               &enforce_permissions,
+               &enforcePermissions,
                "enforce-permissions",
                false,
                "Enforce permission signatures on requests.")
        flag.StringVar(
                &listen,
                "listen",
-               DEFAULT_ADDR,
+               DefaultAddr,
                "Listening address, in the form \"host:port\". e.g., 10.0.1.24:8000. Omit the host part to listen on all interfaces.")
        flag.BoolVar(
                &never_delete,
@@ -289,7 +289,7 @@ func main() {
                &maxBuffers,
                "max-buffers",
                maxBuffers,
-               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))
+               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))
 
        flag.Parse()
 
@@ -300,7 +300,7 @@ func main() {
        if maxBuffers < 0 {
                log.Fatal("-max-buffers must be greater than zero.")
        }
-       bufs = newBufferPool(maxBuffers, BLOCKSIZE)
+       bufs = newBufferPool(maxBuffers, BlockSize)
 
        if pidfile != "" {
                f, err := os.OpenFile(pidfile, os.O_RDWR|os.O_CREATE, 0777)
@@ -358,7 +358,7 @@ func main() {
        blob_signature_ttl = time.Duration(permission_ttl_sec) * time.Second
 
        if PermissionSecret == nil {
-               if enforce_permissions {
+               if enforcePermissions {
                        log.Fatal("-enforce-permissions requires a permission key")
                } else {
                        log.Println("Running without a PermissionSecret. Block locators " +
index b89925f5bd20568137b178e9861570c173c8d2f0..eaf35604d44048ec230b501c61a79196f15baeff 100644 (file)
@@ -309,7 +309,7 @@ func TestDiscoverTmpfs(t *testing.T) {
                }
        }
 
-       // Set up a bogus PROC_MOUNTS file.
+       // Set up a bogus ProcMounts file.
        f, err := ioutil.TempFile("", "keeptest")
        if err != nil {
                t.Fatal(err)
@@ -327,7 +327,7 @@ func TestDiscoverTmpfs(t *testing.T) {
                fmt.Fprintf(f, "tmpfs %s tmpfs %s 0 0\n", path.Dir(vol), opts)
        }
        f.Close()
-       PROC_MOUNTS = f.Name()
+       ProcMounts = f.Name()
 
        var resultVols volumeSet
        added := resultVols.Discover()
@@ -355,7 +355,7 @@ func TestDiscoverTmpfs(t *testing.T) {
 func TestDiscoverNone(t *testing.T) {
        defer teardown()
 
-       // Set up a bogus PROC_MOUNTS file with no Keep vols.
+       // Set up a bogus ProcMounts file with no Keep vols.
        f, err := ioutil.TempFile("", "keeptest")
        if err != nil {
                t.Fatal(err)
@@ -367,7 +367,7 @@ func TestDiscoverNone(t *testing.T) {
        fmt.Fprintln(f, "udev /dev devtmpfs opts 0 0")
        fmt.Fprintln(f, "devpts /dev/pts devpts opts 0 0")
        f.Close()
-       PROC_MOUNTS = f.Name()
+       ProcMounts = f.Name()
 
        var resultVols volumeSet
        added := resultVols.Discover()
@@ -431,7 +431,7 @@ func MakeTestVolumeManager(num_volumes int) VolumeManager {
 // teardown cleans up after each test.
 func teardown() {
        data_manager_token = ""
-       enforce_permissions = false
+       enforcePermissions = false
        PermissionSecret = nil
        KeepVM = nil
 }
index cdaec9232685dffe50b485bdcbdac22ce0486c74..e6a0f27f52df895d4b38a7f29ebd68ad97cbafdb 100644 (file)
@@ -36,7 +36,7 @@ type Volume interface {
        // access log if the block is not found on any other volumes
        // either).
        //
-       // If the data in the backing store is bigger than BLOCKSIZE,
+       // If the data in the backing store is bigger than BlockSize,
        // Get is permitted to return an error without reading any of
        // the data.
        Get(loc string) ([]byte, error)
@@ -52,7 +52,7 @@ type Volume interface {
        //
        // loc is as described in Get.
        //
-       // len(block) is guaranteed to be between 0 and BLOCKSIZE.
+       // len(block) is guaranteed to be between 0 and BlockSize.
        //
        // If a block is already stored under the same name (loc) with
        // different content, Put must either overwrite the existing
index 74bee52387c5f291f7edc8cc0c36e7ef5b48dd9e..12fcef8c4f2ced4087dc1b3c777fedf9401ec5c6 100644 (file)
@@ -79,7 +79,7 @@ func (v *UnixVolume) stat(path string) (os.FileInfo, error) {
        if err == nil {
                if stat.Size() < 0 {
                        err = os.ErrInvalid
-               } else if stat.Size() > BLOCKSIZE {
+               } else if stat.Size() > BlockSize {
                        err = TooLongError
                }
        }
@@ -343,7 +343,7 @@ func (v *UnixVolume) blockPath(loc string) string {
 }
 
 // IsFull returns true if the free space on the volume is less than
-// MIN_FREE_KILOBYTES.
+// MinFreeKilobytes.
 //
 func (v *UnixVolume) IsFull() (isFull bool) {
        fullSymlink := v.root + "/full"
@@ -359,7 +359,7 @@ func (v *UnixVolume) IsFull() (isFull bool) {
        }
 
        if avail, err := v.FreeDiskSpace(); err == nil {
-               isFull = avail < MIN_FREE_KILOBYTES
+               isFull = avail < MinFreeKilobytes
        } else {
                log.Printf("%s: FreeDiskSpace: %s\n", v, err)
                isFull = false