From 1c97dcb10a9836d39cc4f92d3142175b5133f329 Mon Sep 17 00:00:00 2001 From: Bala FA Date: Sat, 18 Mar 2017 23:58:41 +0530 Subject: [PATCH] Add UTCNow() function. (#3931) This patch adds UTCNow() function which returns current UTC time. This is equivalent of UTCNow() == time.Now().UTC() --- cmd/admin-handlers_test.go | 2 +- cmd/admin-rpc-client.go | 6 +++--- cmd/admin-rpc-server.go | 4 ++-- cmd/admin-rpc-server_test.go | 11 +++++------ cmd/api-headers.go | 4 ++-- cmd/api-headers_test.go | 5 ++--- cmd/auth-rpc-client.go | 4 ++-- cmd/azure.go | 6 +++--- cmd/benchmark-utils_test.go | 3 +-- cmd/browser-peer-rpc_test.go | 7 +++---- cmd/bucket-notification-handlers.go | 4 ++-- cmd/erasure-readfile_test.go | 5 ++--- cmd/event-notifier.go | 5 ++--- cmd/event-notifier_test.go | 2 +- cmd/fs-v1-multipart.go | 6 +++--- cmd/generic-handlers.go | 4 ++-- cmd/jwt.go | 2 +- cmd/leak-detect_test.go | 4 ++-- cmd/lock-instrument.go | 4 ++-- cmd/lock-instrument_test.go | 11 ++++------- cmd/lock-rpc-client_test.go | 3 +-- cmd/lock-rpc-server-common.go | 4 ++-- cmd/lock-rpc-server-common_test.go | 16 ++++++++-------- cmd/lock-rpc-server.go | 10 +++++----- cmd/lock-rpc-server_test.go | 3 +-- cmd/lockinfo-handlers.go | 4 ++-- cmd/object-api-common.go | 3 +-- cmd/post-policy_test.go | 14 +++++++------- cmd/postpolicyform.go | 4 ++-- cmd/retry.go | 2 +- cmd/rpc-common.go | 4 ++-- cmd/server-main.go | 2 +- cmd/server-mux_test.go | 4 ++-- cmd/server-startup-msg.go | 3 +-- cmd/server_test.go | 4 ++-- cmd/signature-v2.go | 5 ++--- cmd/signature-v2_test.go | 19 +++++++++++++++++-- cmd/signature-v4-parser_test.go | 20 ++++++++++---------- cmd/signature-v4-utils_test.go | 3 +-- cmd/signature-v4.go | 6 +++--- cmd/signature-v4_test.go | 4 ++-- cmd/storage-rpc-server_test.go | 3 +-- cmd/test-utils_test.go | 14 +++++++------- cmd/update-main_test.go | 4 ++-- cmd/utils.go | 8 +++++++- cmd/web-handlers.go | 4 ++-- cmd/xl-v1-common.go | 9 +++------ cmd/xl-v1-metadata_test.go | 4 ++-- cmd/xl-v1-multipart.go | 10 +++++----- cmd/xl-v1-multipart_test.go | 8 ++++---- cmd/xl-v1-object.go | 5 ++--- cmd/xl-v1-utils_test.go | 3 +-- 52 files changed, 154 insertions(+), 154 deletions(-) diff --git a/cmd/admin-handlers_test.go b/cmd/admin-handlers_test.go index 099129bf5..f649c52ee 100644 --- a/cmd/admin-handlers_test.go +++ b/cmd/admin-handlers_test.go @@ -155,7 +155,7 @@ func prepareAdminXLTestBed() (*adminXLTestBed, error) { } // Initialize boot time - globalBootTime = time.Now().UTC() + globalBootTime = UTCNow() // Set globalEndpoints for a single node XL setup. for _, xlDir := range xlDirs { diff --git a/cmd/admin-rpc-client.go b/cmd/admin-rpc-client.go index a1a482878..716fb79da 100644 --- a/cmd/admin-rpc-client.go +++ b/cmd/admin-rpc-client.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2014-2016 Minio, Inc. + * Minio Cloud Storage, (C) 2014, 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -117,7 +117,7 @@ func (lc localAdminClient) Uptime() (time.Duration, error) { return time.Duration(0), errServerNotInitialized } - return time.Now().UTC().Sub(globalBootTime), nil + return UTCNow().Sub(globalBootTime), nil } // Uptime - returns the uptime of the server to which the RPC call is made. @@ -380,7 +380,7 @@ func getPeerUptimes(peers adminPeers) (time.Duration, error) { // the setup is the uptime of the single minio server // instance. if !globalIsDistXL { - return time.Now().UTC().Sub(globalBootTime), nil + return UTCNow().Sub(globalBootTime), nil } uptimes := make(uptimeSlice, len(peers)) diff --git a/cmd/admin-rpc-server.go b/cmd/admin-rpc-server.go index 855044a64..5339cd7d0 100644 --- a/cmd/admin-rpc-server.go +++ b/cmd/admin-rpc-server.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -137,7 +137,7 @@ func (s *adminCmd) Uptime(args *AuthRPCArgs, reply *UptimeReply) error { // https://github.com/golang/go/issues/12914. This is expected // to be fixed by go1.9. *reply = UptimeReply{ - Uptime: time.Now().UTC().Sub(globalBootTime), + Uptime: UTCNow().Sub(globalBootTime), } return nil diff --git a/cmd/admin-rpc-server_test.go b/cmd/admin-rpc-server_test.go index f41c4e28d..c9736c567 100644 --- a/cmd/admin-rpc-server_test.go +++ b/cmd/admin-rpc-server_test.go @@ -20,7 +20,6 @@ import ( "encoding/json" "net/url" "testing" - "time" ) func testAdminCmd(cmd cmdType, t *testing.T) { @@ -40,7 +39,7 @@ func testAdminCmd(cmd cmdType, t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } reply := LoginRPCReply{} err = adminServer.Login(&args, &reply) @@ -99,7 +98,7 @@ func TestReInitDisks(t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } reply := LoginRPCReply{} err = adminServer.Login(&args, &reply) @@ -124,7 +123,7 @@ func TestReInitDisks(t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } fsReply := LoginRPCReply{} err = fsAdminServer.Login(&fsArgs, &fsReply) @@ -161,7 +160,7 @@ func TestGetConfig(t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } reply := LoginRPCReply{} err = adminServer.Login(&args, &reply) @@ -205,7 +204,7 @@ func TestWriteAndCommitConfig(t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } reply := LoginRPCReply{} err = adminServer.Login(&args, &reply) diff --git a/cmd/api-headers.go b/cmd/api-headers.go index 5f6cc730c..4b6c332b3 100644 --- a/cmd/api-headers.go +++ b/cmd/api-headers.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015,2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -34,7 +34,7 @@ func mustGetRequestID(t time.Time) string { // Write http common headers func setCommonHeaders(w http.ResponseWriter) { // Set unique request ID for each reply. - w.Header().Set(responseRequestIDKey, mustGetRequestID(time.Now().UTC())) + w.Header().Set(responseRequestIDKey, mustGetRequestID(UTCNow())) w.Header().Set("Server", globalServerUserAgent) w.Header().Set("Accept-Ranges", "bytes") } diff --git a/cmd/api-headers_test.go b/cmd/api-headers_test.go index 0d19f13dd..401608929 100644 --- a/cmd/api-headers_test.go +++ b/cmd/api-headers_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -18,12 +18,11 @@ package cmd import ( "testing" - "time" ) func TestNewRequestID(t *testing.T) { // Ensure that it returns an alphanumeric result of length 16. - var id = mustGetRequestID(time.Now().UTC()) + var id = mustGetRequestID(UTCNow()) if len(id) != 16 { t.Fail() diff --git a/cmd/auth-rpc-client.go b/cmd/auth-rpc-client.go index c8385badf..9b3c80fd1 100644 --- a/cmd/auth-rpc-client.go +++ b/cmd/auth-rpc-client.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -93,7 +93,7 @@ func (authClient *AuthRPCClient) Login() (err error) { Username: authClient.config.accessKey, Password: authClient.config.secretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } reply := LoginRPCReply{} diff --git a/cmd/azure.go b/cmd/azure.go index 5b3eebb2e..1217556bd 100644 --- a/cmd/azure.go +++ b/cmd/azure.go @@ -364,7 +364,7 @@ func (a AzureObjects) ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMa // NewMultipartUpload. return result, nil } - result.Uploads = []uploadMetadata{{prefix, prefix, time.Now().UTC(), "", nil}} + result.Uploads = []uploadMetadata{{prefix, prefix, UTCNow(), "", nil}} return result, nil } @@ -439,7 +439,7 @@ func (a AzureObjects) PutObjectPart(bucket, object, uploadID string, partID int, info.PartNumber = partID info.ETag = md5Hex - info.LastModified = time.Now().UTC() + info.LastModified = UTCNow() info.Size = size return info, nil } @@ -476,7 +476,7 @@ func (a AzureObjects) ListObjectParts(bucket, object, uploadID string, partNumbe } result.Parts = append(result.Parts, PartInfo{ partID, - time.Now().UTC(), + UTCNow(), md5Hex, part.Size, }) diff --git a/cmd/benchmark-utils_test.go b/cmd/benchmark-utils_test.go index 0bd8f3c3d..ca1c4dc41 100644 --- a/cmd/benchmark-utils_test.go +++ b/cmd/benchmark-utils_test.go @@ -23,7 +23,6 @@ import ( "math/rand" "strconv" "testing" - "time" humanize "github.com/dustin/go-humanize" ) @@ -245,7 +244,7 @@ func runGetObjectBenchmark(b *testing.B, obj ObjectLayer, objSize int) { func getRandomByte() []byte { const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" // seeding the random number generator. - rand.Seed(time.Now().UTC().UnixNano()) + rand.Seed(UTCNow().UnixNano()) var b byte // pick a character randomly. b = letterBytes[rand.Intn(len(letterBytes))] diff --git a/cmd/browser-peer-rpc_test.go b/cmd/browser-peer-rpc_test.go index 2bea40e9c..16e0aae30 100644 --- a/cmd/browser-peer-rpc_test.go +++ b/cmd/browser-peer-rpc_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -19,7 +19,6 @@ package cmd import ( "path" "testing" - "time" ) // API suite container common to both FS and XL. @@ -96,7 +95,7 @@ func (s *TestRPCBrowserPeerSuite) testBrowserPeerRPC(t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } rreply := &LoginRPCReply{} err = rclient.Call("BrowserPeer"+loginMethodName, rargs, rreply) @@ -111,7 +110,7 @@ func (s *TestRPCBrowserPeerSuite) testBrowserPeerRPC(t *testing.T) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } rreply = &LoginRPCReply{} err = rclient.Call("BrowserPeer"+loginMethodName, rargs, rreply) diff --git a/cmd/bucket-notification-handlers.go b/cmd/bucket-notification-handlers.go index 96c68cf97..afbe4f684 100644 --- a/cmd/bucket-notification-handlers.go +++ b/cmd/bucket-notification-handlers.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -285,7 +285,7 @@ func (api objectAPIHandlers) ListenBucketNotificationHandler(w http.ResponseWrit return } - accountID := fmt.Sprintf("%d", time.Now().UTC().UnixNano()) + accountID := fmt.Sprintf("%d", UTCNow().UnixNano()) accountARN := fmt.Sprintf( "%s:%s:%s:%s-%s", minioTopic, diff --git a/cmd/erasure-readfile_test.go b/cmd/erasure-readfile_test.go index 4fa3c43fa..83b4ea438 100644 --- a/cmd/erasure-readfile_test.go +++ b/cmd/erasure-readfile_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -20,7 +20,6 @@ import ( "bytes" "math/rand" "testing" - "time" "reflect" @@ -412,7 +411,7 @@ func TestErasureReadFileRandomOffsetLength(t *testing.T) { } // To generate random offset/length. - r := rand.New(rand.NewSource(time.Now().UTC().UnixNano())) + r := rand.New(rand.NewSource(UTCNow().UnixNano())) // create pool buffer which will be used by erasureReadFile for // reading from disks and erasure decoding. diff --git a/cmd/event-notifier.go b/cmd/event-notifier.go index 1cbfdc44b..0ecf54b2f 100644 --- a/cmd/event-notifier.go +++ b/cmd/event-notifier.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import ( "net/url" "path" "sync" - "time" "github.com/Sirupsen/logrus" ) @@ -95,7 +94,7 @@ func newNotificationEvent(event eventData) NotificationEvent { creds := serverConfig.GetCredential() // Time when Minio finished processing the request. - eventTime := time.Now().UTC() + eventTime := UTCNow() // API endpoint is captured here to be returned back // to the client for it to differentiate from which diff --git a/cmd/event-notifier_test.go b/cmd/event-notifier_test.go index 415350c24..b3fe5faa8 100644 --- a/cmd/event-notifier_test.go +++ b/cmd/event-notifier_test.go @@ -557,7 +557,7 @@ func TestAddRemoveBucketListenerConfig(t *testing.T) { } // Add a topicConfig to an empty notificationConfig. - accountID := fmt.Sprintf("%d", time.Now().UTC().UnixNano()) + accountID := fmt.Sprintf("%d", UTCNow().UnixNano()) accountARN := fmt.Sprintf( "arn:minio:sqs:%s:%s:listen-%s", serverConfig.GetRegion(), diff --git a/cmd/fs-v1-multipart.go b/cmd/fs-v1-multipart.go index 69ff09e1c..ee7010e8b 100644 --- a/cmd/fs-v1-multipart.go +++ b/cmd/fs-v1-multipart.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -48,7 +48,7 @@ func (fs fsObjects) isMultipartUpload(bucket, prefix string) bool { // Delete uploads.json file wrapper handling a tricky case on windows. func (fs fsObjects) deleteUploadsJSON(bucket, object, uploadID string) error { - timeID := fmt.Sprintf("%X", time.Now().UTC().UnixNano()) + timeID := fmt.Sprintf("%X", UTCNow().UnixNano()) tmpPath := pathJoin(fs.fsPath, minioMetaTmpBucket, fs.fsUUID, uploadID+"+"+timeID) multipartBucketPath := pathJoin(fs.fsPath, minioMetaMultipartBucket) @@ -380,7 +380,7 @@ func (fs fsObjects) newMultipartUpload(bucket string, object string, meta map[st fsMeta.Meta = meta uploadID = mustGetUUID() - initiated := time.Now().UTC() + initiated := UTCNow() // Add upload ID to uploads.json uploadsPath := pathJoin(bucket, object, uploadsJSONFile) diff --git a/cmd/generic-handlers.go b/cmd/generic-handlers.go index 1f69e5930..83cf0313c 100644 --- a/cmd/generic-handlers.go +++ b/cmd/generic-handlers.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -238,7 +238,7 @@ func (h timeValidityHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { } // Verify if the request date header is shifted by less than globalMaxSkewTime parameter in the past // or in the future, reject request otherwise. - curTime := time.Now().UTC() + curTime := UTCNow() if curTime.Sub(amzDate) > globalMaxSkewTime || amzDate.Sub(curTime) > globalMaxSkewTime { writeErrorResponse(w, ErrRequestTimeTooSkewed, r.URL) return diff --git a/cmd/jwt.go b/cmd/jwt.go index 430cada9f..b2bd75729 100644 --- a/cmd/jwt.go +++ b/cmd/jwt.go @@ -59,7 +59,7 @@ func authenticateJWT(accessKey, secretKey string, expiry time.Duration) (string, return "", errAuthentication } - utcNow := time.Now().UTC() + utcNow := UTCNow() token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.MapClaims{ "exp": utcNow.Add(expiry).Unix(), "iat": utcNow.Unix(), diff --git a/cmd/leak-detect_test.go b/cmd/leak-detect_test.go index 376a5c823..ca1aa42b8 100644 --- a/cmd/leak-detect_test.go +++ b/cmd/leak-detect_test.go @@ -54,7 +54,7 @@ func (initialSnapShot LeakDetect) DetectLeak(t TestErrHandler) { } // Loop, waiting for goroutines to shut down. // Wait up to 5 seconds, but finish as quickly as possible. - deadline := time.Now().UTC().Add(leakDetectDeadline * time.Second) + deadline := UTCNow().Add(leakDetectDeadline * time.Second) for { // get sack snapshot of relevant go routines. leaked := initialSnapShot.CompareCurrentSnapshot() @@ -63,7 +63,7 @@ func (initialSnapShot LeakDetect) DetectLeak(t TestErrHandler) { return } // wait a test again will deadline. - if time.Now().UTC().Before(deadline) { + if UTCNow().Before(deadline) { time.Sleep(leakDetectPauseTimeMs * time.Millisecond) continue } diff --git a/cmd/lock-instrument.go b/cmd/lock-instrument.go index d39fb17ad..ad54e2989 100644 --- a/cmd/lock-instrument.go +++ b/cmd/lock-instrument.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -157,7 +157,7 @@ func newDebugLockInfo(lockSource string, status statusType, readLock bool) debug lockSource: lockSource, lType: lType, status: status, - since: time.Now().UTC(), + since: UTCNow(), } } diff --git a/cmd/lock-instrument_test.go b/cmd/lock-instrument_test.go index 1b562b14b..1cdbd8691 100644 --- a/cmd/lock-instrument_test.go +++ b/cmd/lock-instrument_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,10 +16,7 @@ package cmd -import ( - "testing" - "time" -) +import "testing" type lockStateCase struct { volume string @@ -144,7 +141,7 @@ func getSystemLockState() (SystemLockState, error) { LockType: lockInfo.lType, Status: lockInfo.status, Since: lockInfo.since, - Duration: time.Now().UTC().Sub(lockInfo.since), + Duration: UTCNow().Sub(lockInfo.since), }) } lockState.LocksInfoPerObject = append(lockState.LocksInfoPerObject, volLockInfo) @@ -414,7 +411,7 @@ func TestNsLockMapStatusBlockedToRunning(t *testing.T) { globalNSMutex.debugLockMap[param].lockInfo[testCases[0].opsID] = debugLockInfo{ lockSource: "/home/vadmeste/work/go/src/github.com/minio/minio/xl-v1-object.go:683 +0x2a", status: "Running", // State set to "Running". Should fail with `LockInfoStateNotBlocked`. - since: time.Now().UTC(), + since: UTCNow(), } actualErr = globalNSMutex.statusBlockedToRunning(param, testCases[0].lockSource, diff --git a/cmd/lock-rpc-client_test.go b/cmd/lock-rpc-client_test.go index d8ecf1a4f..bd173c70a 100644 --- a/cmd/lock-rpc-client_test.go +++ b/cmd/lock-rpc-client_test.go @@ -19,7 +19,6 @@ package cmd import ( "fmt" "testing" - "time" "github.com/minio/dsync" ) @@ -29,7 +28,7 @@ func TestLockRPCClient(t *testing.T) { lkClient := newLockRPCClient(authConfig{ accessKey: "abcd", secretKey: "abcd123", - serverAddr: fmt.Sprintf("%X", time.Now().UTC().UnixNano()), + serverAddr: fmt.Sprintf("%X", UTCNow().UnixNano()), serviceEndpoint: pathJoin(lockRPCPath, "/test/1"), secureConn: false, serviceName: "Dsync", diff --git a/cmd/lock-rpc-server-common.go b/cmd/lock-rpc-server-common.go index 41856172c..a268c0b9c 100644 --- a/cmd/lock-rpc-server-common.go +++ b/cmd/lock-rpc-server-common.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -66,7 +66,7 @@ func getLongLivedLocks(m map[string][]lockRequesterInfo, interval time.Duration) // Check whether enough time has gone by since last check if time.Since(lriArray[idx].timeLastCheck) >= interval { rslt = append(rslt, nameLockRequesterInfoPair{name: name, lri: lriArray[idx]}) - lriArray[idx].timeLastCheck = time.Now().UTC() + lriArray[idx].timeLastCheck = UTCNow() } } } diff --git a/cmd/lock-rpc-server-common_test.go b/cmd/lock-rpc-server-common_test.go index eddc3ee8d..94617f768 100644 --- a/cmd/lock-rpc-server-common_test.go +++ b/cmd/lock-rpc-server-common_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -32,8 +32,8 @@ func TestLockRpcServerRemoveEntryIfExists(t *testing.T) { node: "host", rpcPath: "rpc-path", uid: "0123-4567", - timestamp: time.Now().UTC(), - timeLastCheck: time.Now().UTC(), + timestamp: UTCNow(), + timeLastCheck: UTCNow(), } nlrip := nameLockRequesterInfoPair{name: "name", lri: lri} @@ -69,16 +69,16 @@ func TestLockRpcServerRemoveEntry(t *testing.T) { node: "host", rpcPath: "rpc-path", uid: "0123-4567", - timestamp: time.Now().UTC(), - timeLastCheck: time.Now().UTC(), + timestamp: UTCNow(), + timeLastCheck: UTCNow(), } lockRequesterInfo2 := lockRequesterInfo{ writer: true, node: "host", rpcPath: "rpc-path", uid: "89ab-cdef", - timestamp: time.Now().UTC(), - timeLastCheck: time.Now().UTC(), + timestamp: UTCNow(), + timeLastCheck: UTCNow(), } locker.lockMap["name"] = []lockRequesterInfo{ @@ -116,7 +116,7 @@ func TestLockRpcServerRemoveEntry(t *testing.T) { // Tests function returning long lived locks. func TestLockRpcServerGetLongLivedLocks(t *testing.T) { - ut := time.Now().UTC() + ut := UTCNow() // Collection of test cases for verifying returning valid long lived locks. testCases := []struct { lockMap map[string][]lockRequesterInfo diff --git a/cmd/lock-rpc-server.go b/cmd/lock-rpc-server.go index ad86b035d..4709475cf 100644 --- a/cmd/lock-rpc-server.go +++ b/cmd/lock-rpc-server.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -145,8 +145,8 @@ func (l *lockServer) Lock(args *LockArgs, reply *bool) error { node: args.LockArgs.ServerAddr, rpcPath: args.LockArgs.ServiceEndpoint, uid: args.LockArgs.UID, - timestamp: time.Now().UTC(), - timeLastCheck: time.Now().UTC(), + timestamp: UTCNow(), + timeLastCheck: UTCNow(), }, } } @@ -186,8 +186,8 @@ func (l *lockServer) RLock(args *LockArgs, reply *bool) error { node: args.LockArgs.ServerAddr, rpcPath: args.LockArgs.ServiceEndpoint, uid: args.LockArgs.UID, - timestamp: time.Now().UTC(), - timeLastCheck: time.Now().UTC(), + timestamp: UTCNow(), + timeLastCheck: UTCNow(), } if lri, ok := l.lockMap[args.LockArgs.Resource]; ok { if *reply = !isWriteLock(lri); *reply { // Unless there is a write lock diff --git a/cmd/lock-rpc-server_test.go b/cmd/lock-rpc-server_test.go index 90661ca9b..006c8b28f 100644 --- a/cmd/lock-rpc-server_test.go +++ b/cmd/lock-rpc-server_test.go @@ -21,7 +21,6 @@ import ( "runtime" "sync" "testing" - "time" "github.com/minio/dsync" ) @@ -61,7 +60,7 @@ func createLockTestServer(t *testing.T) (string, *lockServer, string) { Username: creds.AccessKey, Password: creds.SecretKey, Version: Version, - RequestTime: time.Now().UTC(), + RequestTime: UTCNow(), } loginReply := LoginRPCReply{} err = locker.Login(&loginArgs, &loginReply) diff --git a/cmd/lockinfo-handlers.go b/cmd/lockinfo-handlers.go index aa3fb234d..ccc01b1e4 100644 --- a/cmd/lockinfo-handlers.go +++ b/cmd/lockinfo-handlers.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -71,7 +71,7 @@ func listLocksInfo(bucket, prefix string, duration time.Duration) []VolumeLockIn defer globalNSMutex.lockMapMutex.Unlock() // Fetch current time once instead of fetching system time for every lock. - timeNow := time.Now().UTC() + timeNow := UTCNow() volumeLocks := []VolumeLockInfo{} for param, debugLock := range globalNSMutex.debugLockMap { diff --git a/cmd/object-api-common.go b/cmd/object-api-common.go index b2fd37af6..ab66817a9 100644 --- a/cmd/object-api-common.go +++ b/cmd/object-api-common.go @@ -21,7 +21,6 @@ import ( "net/url" "runtime" "sync" - "time" humanize "github.com/dustin/go-humanize" ) @@ -71,7 +70,7 @@ func dirObjectInfo(bucket, object string, size int64, metadata map[string]string return ObjectInfo{ Bucket: bucket, Name: object, - ModTime: time.Now().UTC(), + ModTime: UTCNow(), ContentType: "application/octet-stream", IsDir: true, Size: size, diff --git a/cmd/post-policy_test.go b/cmd/post-policy_test.go index 29df94acc..97a7e483e 100644 --- a/cmd/post-policy_test.go +++ b/cmd/post-policy_test.go @@ -37,7 +37,7 @@ const ( ) func newPostPolicyBytesV4WithContentRange(credential, bucketName, objectKey string, expiration time.Time) []byte { - t := time.Now().UTC() + t := UTCNow() // Add the expiration date. expirationStr := fmt.Sprintf(`"expiration": "%s"`, expiration.Format(expirationDateFormat)) // Add the bucket condition, only accept buckets equal to the one passed. @@ -66,7 +66,7 @@ func newPostPolicyBytesV4WithContentRange(credential, bucketName, objectKey stri // newPostPolicyBytesV4 - creates a bare bones postpolicy string with key and bucket matches. func newPostPolicyBytesV4(credential, bucketName, objectKey string, expiration time.Time) []byte { - t := time.Now().UTC() + t := UTCNow() // Add the expiration date. expirationStr := fmt.Sprintf(`"expiration": "%s"`, expiration.Format(expirationDateFormat)) // Add the bucket condition, only accept buckets equal to the one passed. @@ -136,7 +136,7 @@ func testPostPolicyBucketHandler(obj ObjectLayer, instanceType string, t TestErr credentials := serverConfig.GetCredential() - curTime := time.Now().UTC() + curTime := UTCNow() curTimePlus5Min := curTime.Add(time.Minute * 5) // bucketnames[0]. @@ -455,7 +455,7 @@ func testPostPolicyBucketHandlerRedirect(obj ObjectLayer, instanceType string, t credentials := serverConfig.GetCredential() - curTime := time.Now().UTC() + curTime := UTCNow() curTimePlus5Min := curTime.Add(time.Minute * 5) err = obj.MakeBucket(bucketName) @@ -517,7 +517,7 @@ func postPresignSignatureV4(policyBase64 string, t time.Time, secretAccessKey, l func newPostRequestV2(endPoint, bucketName, objectName string, accessKey, secretKey string) (*http.Request, error) { // Expire the request five minutes from now. - expirationTime := time.Now().UTC().Add(time.Minute * 5) + expirationTime := UTCNow().Add(time.Minute * 5) // Create a new post policy. policy := newPostPolicyBytesV2(bucketName, objectName, expirationTime) // Only need the encoding. @@ -644,13 +644,13 @@ func newPostRequestV4Generic(endPoint, bucketName, objectName string, objData [] } func newPostRequestV4WithContentLength(endPoint, bucketName, objectName string, objData []byte, accessKey, secretKey string) (*http.Request, error) { - t := time.Now().UTC() + t := UTCNow() policy := buildGenericPolicy(t, accessKey, bucketName, objectName, true) return newPostRequestV4Generic(endPoint, bucketName, objectName, objData, accessKey, secretKey, t, policy, nil, false, false) } func newPostRequestV4(endPoint, bucketName, objectName string, objData []byte, accessKey, secretKey string) (*http.Request, error) { - t := time.Now().UTC() + t := UTCNow() policy := buildGenericPolicy(t, accessKey, bucketName, objectName, false) return newPostRequestV4Generic(endPoint, bucketName, objectName, objData, accessKey, secretKey, t, policy, nil, false, false) } diff --git a/cmd/postpolicyform.go b/cmd/postpolicyform.go index 6c90a294e..ed50ed007 100644 --- a/cmd/postpolicyform.go +++ b/cmd/postpolicyform.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -221,7 +221,7 @@ func checkPolicyCond(op string, input1, input2 string) bool { // (http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html) func checkPostPolicy(formValues http.Header, postPolicyForm PostPolicyForm) APIErrorCode { // Check if policy document expiry date is still not reached - if !postPolicyForm.Expiration.After(time.Now().UTC()) { + if !postPolicyForm.Expiration.After(UTCNow()) { return ErrPolicyAlreadyExpired } diff --git a/cmd/retry.go b/cmd/retry.go index 1624b0e2d..1c1a7cb7f 100644 --- a/cmd/retry.go +++ b/cmd/retry.go @@ -54,7 +54,7 @@ const NoJitter = 0.0 // Global random source for fetching random values. var globalRandomSource = rand.New(&lockedRandSource{ - src: rand.NewSource(time.Now().UTC().UnixNano()), + src: rand.NewSource(UTCNow().UnixNano()), }) // newRetryTimerJitter creates a timer with exponentially increasing delays diff --git a/cmd/rpc-common.go b/cmd/rpc-common.go index 876f335d6..9761787e3 100644 --- a/cmd/rpc-common.go +++ b/cmd/rpc-common.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -28,7 +28,7 @@ const rpcSkewTimeAllowed = 3 * time.Second func isRequestTimeAllowed(requestTime time.Time) bool { // Check whether request time is within acceptable skew time. - utcNow := time.Now().UTC() + utcNow := UTCNow() return !(requestTime.Sub(utcNow) > rpcSkewTimeAllowed || utcNow.Sub(requestTime) > rpcSkewTimeAllowed) } diff --git a/cmd/server-main.go b/cmd/server-main.go index a8293cc0f..1aaa066f9 100644 --- a/cmd/server-main.go +++ b/cmd/server-main.go @@ -596,7 +596,7 @@ func serverMain(c *cli.Context) { } // Set uptime time after object layer has initialized. - globalBootTime = time.Now().UTC() + globalBootTime = UTCNow() // Waits on the server. <-globalServiceDoneCh diff --git a/cmd/server-mux_test.go b/cmd/server-mux_test.go index 81985c174..22891386b 100644 --- a/cmd/server-mux_test.go +++ b/cmd/server-mux_test.go @@ -438,8 +438,8 @@ func generateTestCert(host string) error { Subject: pkix.Name{ Organization: []string{"Minio Test Cert"}, }, - NotBefore: time.Now().UTC(), - NotAfter: time.Now().UTC().Add(time.Minute * 1), + NotBefore: UTCNow(), + NotAfter: UTCNow().Add(time.Minute * 1), KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, diff --git a/cmd/server-startup-msg.go b/cmd/server-startup-msg.go index a51ca7ceb..eacef8e2e 100644 --- a/cmd/server-startup-msg.go +++ b/cmd/server-startup-msg.go @@ -21,7 +21,6 @@ import ( "fmt" "runtime" "strings" - "time" humanize "github.com/dustin/go-humanize" "github.com/minio/mc/pkg/console" @@ -161,7 +160,7 @@ func getCertificateChainMsg(certs []*x509.Certificate) string { var expiringCerts int for i := totalCerts - 1; i >= 0; i-- { cert := certs[i] - if cert.NotAfter.Before(time.Now().UTC().Add(globalMinioCertExpireWarnDays)) { + if cert.NotAfter.Before(UTCNow().Add(globalMinioCertExpireWarnDays)) { expiringCerts++ msg += fmt.Sprintf(colorBold("#%d %s will expire on %s\n"), expiringCerts, cert.Subject.CommonName, cert.NotAfter) } diff --git a/cmd/server_test.go b/cmd/server_test.go index 3dffd14b2..44a4a4a13 100644 --- a/cmd/server_test.go +++ b/cmd/server_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -1812,7 +1812,7 @@ func (s *TestSuiteCommon) TestGetPartialObjectMisAligned(c *C) { 1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890, 1234567890,1234567890,1234567890,123` - rand.Seed(time.Now().UTC().UnixNano()) + rand.Seed(UTCNow().UnixNano()) // Create a misalgined data. for i := 0; i < 13*rand.Intn(1<<16); i++ { buffer.WriteString(fmt.Sprintf("[%05d] %s\n", i, line[:rand.Intn(1<<8)])) diff --git a/cmd/signature-v2.go b/cmd/signature-v2.go index e1eecbc90..64dbc7181 100644 --- a/cmd/signature-v2.go +++ b/cmd/signature-v2.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,7 +26,6 @@ import ( "sort" "strconv" "strings" - "time" ) // Signature and API related constants. @@ -136,7 +135,7 @@ func doesPresignV2SignatureMatch(r *http.Request) APIErrorCode { } // Check if the presigned URL has expired. - if expiresInt < time.Now().UTC().Unix() { + if expiresInt < UTCNow().Unix() { return ErrExpiredPresignRequest } diff --git a/cmd/signature-v2_test.go b/cmd/signature-v2_test.go index 3a2b778aa..4622c9eb8 100644 --- a/cmd/signature-v2_test.go +++ b/cmd/signature-v2_test.go @@ -1,3 +1,19 @@ +/* + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ + package cmd import ( @@ -6,7 +22,6 @@ import ( "net/url" "sort" "testing" - "time" ) // Tests for 'func TestResourceListSorting(t *testing.T)'. @@ -30,7 +45,7 @@ func TestDoesPresignedV2SignatureMatch(t *testing.T) { } defer removeAll(root) - now := time.Now().UTC() + now := UTCNow() testCases := []struct { queryParams map[string]string diff --git a/cmd/signature-v4-parser_test.go b/cmd/signature-v4-parser_test.go index 3639c093d..6a59a4265 100644 --- a/cmd/signature-v4-parser_test.go +++ b/cmd/signature-v4-parser_test.go @@ -87,7 +87,7 @@ func validateCredentialfields(t *testing.T, testNum int, expectedCredentials cre // },"/") func TestParseCredentialHeader(t *testing.T) { - sampleTimeStr := time.Now().UTC().Format(yyyymmdd) + sampleTimeStr := UTCNow().Format(yyyymmdd) testCases := []struct { inputCredentialStr string @@ -120,7 +120,7 @@ func TestParseCredentialHeader(t *testing.T) { { inputCredentialStr: generateCredentialStr( "^#@.", - time.Now().UTC().Format(yyyymmdd), + UTCNow().Format(yyyymmdd), "ABCD", "ABCD", "ABCD"), @@ -133,7 +133,7 @@ func TestParseCredentialHeader(t *testing.T) { { inputCredentialStr: generateCredentialStr( "Z7IXGOO6BZ0REAN1Q26I", - time.Now().UTC().String(), + UTCNow().String(), "ABCD", "ABCD", "ABCD"), @@ -146,7 +146,7 @@ func TestParseCredentialHeader(t *testing.T) { { inputCredentialStr: generateCredentialStr( "Z7IXGOO6BZ0REAN1Q26I", - time.Now().UTC().Format(yyyymmdd), + UTCNow().Format(yyyymmdd), "", "ABCD", "ABCD"), @@ -159,7 +159,7 @@ func TestParseCredentialHeader(t *testing.T) { { inputCredentialStr: generateCredentialStr( "Z7IXGOO6BZ0REAN1Q26I", - time.Now().UTC().Format(yyyymmdd), + UTCNow().Format(yyyymmdd), "us-west-1", "ABCD", "ABCD"), @@ -172,7 +172,7 @@ func TestParseCredentialHeader(t *testing.T) { { inputCredentialStr: generateCredentialStr( "Z7IXGOO6BZ0REAN1Q26I", - time.Now().UTC().Format(yyyymmdd), + UTCNow().Format(yyyymmdd), "us-west-1", "s3", "ABCD"), @@ -313,7 +313,7 @@ func TestParseSignedHeaders(t *testing.T) { // TestParseSignV4 - Tests Parsing of v4 signature form the authorization string. func TestParseSignV4(t *testing.T) { - sampleTimeStr := time.Now().UTC().Format(yyyymmdd) + sampleTimeStr := UTCNow().Format(yyyymmdd) testCases := []struct { inputV4AuthStr string expectedAuthField signValues @@ -572,9 +572,9 @@ func TestParsePreSignV4(t *testing.T) { return strconv.Itoa(expires) } // used in expected preSignValues, preSignValues.Date is of type time.Time . - queryTime := time.Now().UTC() + queryTime := UTCNow() - sampleTimeStr := time.Now().UTC().Format(yyyymmdd) + sampleTimeStr := UTCNow().Format(yyyymmdd) testCases := []struct { inputQueryKeyVals []string @@ -668,7 +668,7 @@ func TestParsePreSignV4(t *testing.T) { "s3", "aws4_request"), // valid "X-Amz-Date" query. - "X-Amz-Date", time.Now().UTC().Format(iso8601Format), + "X-Amz-Date", UTCNow().Format(iso8601Format), "X-Amz-Expires", "MalformedExpiry", "X-Amz-SignedHeaders", "", "X-Amz-Signature", "", diff --git a/cmd/signature-v4-utils_test.go b/cmd/signature-v4-utils_test.go index 343c0ec3f..a844a63a9 100644 --- a/cmd/signature-v4-utils_test.go +++ b/cmd/signature-v4-utils_test.go @@ -19,7 +19,6 @@ package cmd import ( "net/http" "testing" - "time" ) // TestSkipContentSha256Cksum - Test validate the logic which decides whether @@ -140,7 +139,7 @@ func TestExtractSignedHeaders(t *testing.T) { // expected header values. expectedHost := "play.minio.io:9000" expectedContentSha256 := "1234abcd" - expectedTime := time.Now().UTC().Format(iso8601Format) + expectedTime := UTCNow().Format(iso8601Format) // Creating input http header. inputHeader := make(http.Header) diff --git a/cmd/signature-v4.go b/cmd/signature-v4.go index d32d22435..7abc98829 100644 --- a/cmd/signature-v4.go +++ b/cmd/signature-v4.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -249,11 +249,11 @@ func doesPresignedSignatureMatch(hashedPayload string, r *http.Request, region s // If the host which signed the request is slightly ahead in time (by less than globalMaxSkewTime) the // request should still be allowed. - if pSignValues.Date.After(time.Now().UTC().Add(globalMaxSkewTime)) { + if pSignValues.Date.After(UTCNow().Add(globalMaxSkewTime)) { return ErrRequestNotReadyYet } - if time.Now().UTC().Sub(pSignValues.Date) > time.Duration(pSignValues.Expires) { + if UTCNow().Sub(pSignValues.Date) > time.Duration(pSignValues.Expires) { return ErrExpiredPresignRequest } diff --git a/cmd/signature-v4_test.go b/cmd/signature-v4_test.go index 41422671d..7d5d794b2 100644 --- a/cmd/signature-v4_test.go +++ b/cmd/signature-v4_test.go @@ -35,7 +35,7 @@ func niceError(code APIErrorCode) string { func TestDoesPolicySignatureMatch(t *testing.T) { credentialTemplate := "%s/%s/%s/s3/aws4_request" - now := time.Now().UTC() + now := UTCNow() accessKey := serverConfig.GetCredential().AccessKey testCases := []struct { @@ -106,7 +106,7 @@ func TestDoesPresignedSignatureMatch(t *testing.T) { // sha256 hash of "payload" payloadSHA256 := "239f59ed55e737c77147cf55ad0c1b030b6d7ee748a7426952f9b852d5a935e5" - now := time.Now().UTC() + now := UTCNow() credentialTemplate := "%s/%s/%s/s3/aws4_request" region := serverConfig.GetRegion() diff --git a/cmd/storage-rpc-server_test.go b/cmd/storage-rpc-server_test.go index 9b5e001fa..2006f41c9 100644 --- a/cmd/storage-rpc-server_test.go +++ b/cmd/storage-rpc-server_test.go @@ -19,7 +19,6 @@ package cmd import ( "net/url" "testing" - "time" "github.com/minio/minio/pkg/disk" ) @@ -63,7 +62,7 @@ func createTestStorageServer(t *testing.T) *testStorageRPCServer { stServer := &storageServer{ storage: storageDisks[0], path: "/disk1", - timestamp: time.Now().UTC(), + timestamp: UTCNow(), } return &testStorageRPCServer{ token: token, diff --git a/cmd/test-utils_test.go b/cmd/test-utils_test.go index efaa6dd7d..ba630194e 100644 --- a/cmd/test-utils_test.go +++ b/cmd/test-utils_test.go @@ -816,7 +816,7 @@ func newTestStreamingSignedBadChunkDateRequest(method, urlStr string, contentLen return nil, err } - currTime := time.Now().UTC() + currTime := UTCNow() signature, err := signStreamingRequest(req, accessKey, secretKey, currTime) if err != nil { return nil, err @@ -835,7 +835,7 @@ func newTestStreamingSignedRequest(method, urlStr string, contentLength, chunkSi return nil, err } - currTime := time.Now().UTC() + currTime := UTCNow() signature, err := signStreamingRequest(req, accessKey, secretKey, currTime) if err != nil { return nil, err @@ -887,7 +887,7 @@ func preSignV4(req *http.Request, accessKeyID, secretAccessKey string, expires i } region := serverConfig.GetRegion() - date := time.Now().UTC() + date := UTCNow() scope := getScope(date, region) credential := fmt.Sprintf("%s/%s", accessKeyID, scope) @@ -926,7 +926,7 @@ func preSignV2(req *http.Request, accessKeyID, secretAccessKey string, expires i return errors.New("Presign cannot be generated without access and secret keys") } - d := time.Now().UTC() + d := UTCNow() // Find epoch expires when the request will expire. epochExpires := d.Unix() + expires @@ -975,7 +975,7 @@ func preSignV2(req *http.Request, accessKeyID, secretAccessKey string, expires i // Sign given request using Signature V2. func signRequestV2(req *http.Request, accessKey, secretKey string) error { // Initial time. - d := time.Now().UTC() + d := UTCNow() // Add date if not present. if date := req.Header.Get("Date"); date == "" { @@ -1018,7 +1018,7 @@ func signRequestV4(req *http.Request, accessKey, secretKey string) error { return fmt.Errorf("Invalid hashed payload") } - currTime := time.Now().UTC() + currTime := UTCNow() // Set x-amz-date. req.Header.Set("x-amz-date", currTime.Format(iso8601Format)) @@ -1297,7 +1297,7 @@ func getTestWebRPCResponse(resp *httptest.ResponseRecorder, data interface{}) er return nil } -var src = rand.NewSource(time.Now().UTC().UnixNano()) +var src = rand.NewSource(UTCNow().UnixNano()) // Function to generate random string for bucket/object names. func randString(n int) string { diff --git a/cmd/update-main_test.go b/cmd/update-main_test.go index 0a3a746ea..f1111ca91 100644 --- a/cmd/update-main_test.go +++ b/cmd/update-main_test.go @@ -31,7 +31,7 @@ import ( ) func TestGetCurrentReleaseTime(t *testing.T) { - minioVersion1 := time.Now().UTC().Format(time.RFC3339) + minioVersion1 := UTCNow().Format(time.RFC3339) releaseTime1, _ := time.Parse(time.RFC3339, minioVersion1) minioVersion2 := "DEVELOPMENT.GOGET" @@ -223,7 +223,7 @@ func TestIsSourceBuild(t *testing.T) { minioVersion string expectedResult bool }{ - {time.Now().UTC().Format(time.RFC3339), false}, + {UTCNow().Format(time.RFC3339), false}, {"DEVELOPMENT.GOGET", true}, {"junk", true}, {"3.2.4", true}, diff --git a/cmd/utils.go b/cmd/utils.go index 744e7bd08..a252c1c80 100644 --- a/cmd/utils.go +++ b/cmd/utils.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -26,6 +26,7 @@ import ( "net/url" "os" "strings" + "time" "encoding/json" @@ -275,3 +276,8 @@ func checkURL(address string) (*url.URL, error) { } return u, nil } + +// UTCNow - returns current UTC time. +func UTCNow() time.Time { + return time.Now().UTC() +} diff --git a/cmd/web-handlers.go b/cmd/web-handlers.go index 4c7bc8754..685136ac4 100644 --- a/cmd/web-handlers.go +++ b/cmd/web-handlers.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -850,7 +850,7 @@ func presignedGet(host, bucket, object string, expiry int64) string { accessKey := cred.AccessKey secretKey := cred.SecretKey - date := time.Now().UTC() + date := UTCNow() dateStr := date.Format(iso8601Format) credential := fmt.Sprintf("%s/%s", accessKey, getScope(date, region)) diff --git a/cmd/xl-v1-common.go b/cmd/xl-v1-common.go index 38a3491dd..a3ab28ee6 100644 --- a/cmd/xl-v1-common.go +++ b/cmd/xl-v1-common.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -16,15 +16,12 @@ package cmd -import ( - "path" - "time" -) +import "path" // getLoadBalancedDisks - fetches load balanced (sufficiently randomized) disk slice. func (xl xlObjects) getLoadBalancedDisks() (disks []StorageAPI) { // Based on the random shuffling return back randomized disks. - for _, i := range hashOrder(time.Now().UTC().String(), len(xl.storageDisks)) { + for _, i := range hashOrder(UTCNow().String(), len(xl.storageDisks)) { disks = append(disks, xl.storageDisks[i-1]) } return disks diff --git a/cmd/xl-v1-metadata_test.go b/cmd/xl-v1-metadata_test.go index fb92ebc2a..d09822a57 100644 --- a/cmd/xl-v1-metadata_test.go +++ b/cmd/xl-v1-metadata_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2015, 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -169,7 +169,7 @@ func isXLMetaSimilar(m, n xlMetaV1) bool { func TestPickValidXLMeta(t *testing.T) { obj := "object" x1 := newXLMetaV1(obj, 4, 4) - now := time.Now().UTC() + now := UTCNow() x1.Stat.ModTime = now invalidX1 := x1 invalidX1.Version = "invalid-version" diff --git a/cmd/xl-v1-multipart.go b/cmd/xl-v1-multipart.go index a6816dbe4..0af02bac7 100644 --- a/cmd/xl-v1-multipart.go +++ b/cmd/xl-v1-multipart.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -478,7 +478,7 @@ func (xl xlObjects) newMultipartUpload(bucket string, object string, meta map[st } meta["content-type"] = contentType } - xlMeta.Stat.ModTime = time.Now().UTC() + xlMeta.Stat.ModTime = UTCNow() xlMeta.Meta = meta // This lock needs to be held for any changes to the directory @@ -507,7 +507,7 @@ func (xl xlObjects) newMultipartUpload(bucket string, object string, meta map[st return "", toObjectErr(rErr, minioMetaMultipartBucket, uploadIDPath) } - initiated := time.Now().UTC() + initiated := UTCNow() // Create or update 'uploads.json' if err = xl.addUploadID(bucket, object, uploadID, initiated); err != nil { return "", err @@ -725,7 +725,7 @@ func (xl xlObjects) PutObjectPart(bucket, object, uploadID string, partID int, s } // Once part is successfully committed, proceed with updating XL metadata. - xlMeta.Stat.ModTime = time.Now().UTC() + xlMeta.Stat.ModTime = UTCNow() // Add the current part. xlMeta.AddObjectPart(partID, partSuffix, newMD5Hex, size) @@ -971,7 +971,7 @@ func (xl xlObjects) CompleteMultipartUpload(bucket string, object string, upload // Save the final object size and modtime. xlMeta.Stat.Size = objectSize - xlMeta.Stat.ModTime = time.Now().UTC() + xlMeta.Stat.ModTime = UTCNow() // Save successfully calculated md5sum. xlMeta.Meta["md5Sum"] = s3MD5 diff --git a/cmd/xl-v1-multipart_test.go b/cmd/xl-v1-multipart_test.go index 5d31eb1b2..71d5dd03b 100644 --- a/cmd/xl-v1-multipart_test.go +++ b/cmd/xl-v1-multipart_test.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2014-2016, 2017 Minio, Inc. + * Minio Cloud Storage, (C) 2014, 2015, 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -49,8 +49,8 @@ func TestUpdateUploadJSON(t *testing.T) { isRemove bool errVal error }{ - {"111abc", time.Now().UTC(), false, nil}, - {"222abc", time.Now().UTC(), false, nil}, + {"111abc", UTCNow(), false, nil}, + {"222abc", UTCNow(), false, nil}, {"111abc", time.Time{}, true, nil}, } @@ -68,7 +68,7 @@ func TestUpdateUploadJSON(t *testing.T) { xl.storageDisks[i] = newNaughtyDisk(xl.storageDisks[i].(*retryStorage), nil, errFaultyDisk) } - testErrVal := xl.updateUploadJSON(bucket, object, "222abc", time.Now().UTC(), false) + testErrVal := xl.updateUploadJSON(bucket, object, "222abc", UTCNow(), false) if testErrVal == nil || testErrVal.Error() != errXLWriteQuorum.Error() { t.Errorf("Expected write quorum error, but got: %v", testErrVal) } diff --git a/cmd/xl-v1-object.go b/cmd/xl-v1-object.go index f7ecf76c9..ce9d8ba29 100644 --- a/cmd/xl-v1-object.go +++ b/cmd/xl-v1-object.go @@ -1,5 +1,5 @@ /* - * Minio Cloud Storage, (C) 2016 Minio, Inc. + * Minio Cloud Storage, (C) 2016, 2017 Minio, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. @@ -25,7 +25,6 @@ import ( "strconv" "strings" "sync" - "time" "github.com/minio/minio/pkg/bpool" "github.com/minio/minio/pkg/mimedb" @@ -651,7 +650,7 @@ func (xl xlObjects) PutObject(bucket string, object string, size int64, data io. } // Save additional erasureMetadata. - modTime := time.Now().UTC() + modTime := UTCNow() newMD5Hex := hex.EncodeToString(md5Writer.Sum(nil)) // Update the md5sum if not set with the newly calculated one. diff --git a/cmd/xl-v1-utils_test.go b/cmd/xl-v1-utils_test.go index 80901b703..e167f226d 100644 --- a/cmd/xl-v1-utils_test.go +++ b/cmd/xl-v1-utils_test.go @@ -21,7 +21,6 @@ import ( "reflect" "strconv" "testing" - "time" humanize "github.com/dustin/go-humanize" ) @@ -146,7 +145,7 @@ func newTestXLMetaV1() xlMetaV1 { } xlMeta.Stat = statInfo{ Size: int64(20), - ModTime: time.Now().UTC(), + ModTime: UTCNow(), } // Set meta data. xlMeta.Meta = make(map[string]string)