Add UTCNow() function. (#3931)

This patch adds UTCNow() function which returns current UTC time.

This is equivalent of UTCNow() == time.Now().UTC()
This commit is contained in:
Bala FA 2017-03-18 23:58:41 +05:30 committed by Harshavardhana
parent 3a6111eff5
commit 1c97dcb10a
52 changed files with 154 additions and 154 deletions

View File

@ -155,7 +155,7 @@ func prepareAdminXLTestBed() (*adminXLTestBed, error) {
} }
// Initialize boot time // Initialize boot time
globalBootTime = time.Now().UTC() globalBootTime = UTCNow()
// Set globalEndpoints for a single node XL setup. // Set globalEndpoints for a single node XL setup.
for _, xlDir := range xlDirs { for _, xlDir := range xlDirs {

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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.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. // 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 // the setup is the uptime of the single minio server
// instance. // instance.
if !globalIsDistXL { if !globalIsDistXL {
return time.Now().UTC().Sub(globalBootTime), nil return UTCNow().Sub(globalBootTime), nil
} }
uptimes := make(uptimeSlice, len(peers)) uptimes := make(uptimeSlice, len(peers))

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 // https://github.com/golang/go/issues/12914. This is expected
// to be fixed by go1.9. // to be fixed by go1.9.
*reply = UptimeReply{ *reply = UptimeReply{
Uptime: time.Now().UTC().Sub(globalBootTime), Uptime: UTCNow().Sub(globalBootTime),
} }
return nil return nil

View File

@ -20,7 +20,6 @@ import (
"encoding/json" "encoding/json"
"net/url" "net/url"
"testing" "testing"
"time"
) )
func testAdminCmd(cmd cmdType, t *testing.T) { func testAdminCmd(cmd cmdType, t *testing.T) {
@ -40,7 +39,7 @@ func testAdminCmd(cmd cmdType, t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
reply := LoginRPCReply{} reply := LoginRPCReply{}
err = adminServer.Login(&args, &reply) err = adminServer.Login(&args, &reply)
@ -99,7 +98,7 @@ func TestReInitDisks(t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
reply := LoginRPCReply{} reply := LoginRPCReply{}
err = adminServer.Login(&args, &reply) err = adminServer.Login(&args, &reply)
@ -124,7 +123,7 @@ func TestReInitDisks(t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
fsReply := LoginRPCReply{} fsReply := LoginRPCReply{}
err = fsAdminServer.Login(&fsArgs, &fsReply) err = fsAdminServer.Login(&fsArgs, &fsReply)
@ -161,7 +160,7 @@ func TestGetConfig(t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
reply := LoginRPCReply{} reply := LoginRPCReply{}
err = adminServer.Login(&args, &reply) err = adminServer.Login(&args, &reply)
@ -205,7 +204,7 @@ func TestWriteAndCommitConfig(t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
reply := LoginRPCReply{} reply := LoginRPCReply{}
err = adminServer.Login(&args, &reply) err = adminServer.Login(&args, &reply)

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 // Write http common headers
func setCommonHeaders(w http.ResponseWriter) { func setCommonHeaders(w http.ResponseWriter) {
// Set unique request ID for each reply. // 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("Server", globalServerUserAgent)
w.Header().Set("Accept-Ranges", "bytes") w.Header().Set("Accept-Ranges", "bytes")
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -18,12 +18,11 @@ package cmd
import ( import (
"testing" "testing"
"time"
) )
func TestNewRequestID(t *testing.T) { func TestNewRequestID(t *testing.T) {
// Ensure that it returns an alphanumeric result of length 16. // Ensure that it returns an alphanumeric result of length 16.
var id = mustGetRequestID(time.Now().UTC()) var id = mustGetRequestID(UTCNow())
if len(id) != 16 { if len(id) != 16 {
t.Fail() t.Fail()

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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, Username: authClient.config.accessKey,
Password: authClient.config.secretKey, Password: authClient.config.secretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
reply := LoginRPCReply{} reply := LoginRPCReply{}

View File

@ -364,7 +364,7 @@ func (a AzureObjects) ListMultipartUploads(bucket, prefix, keyMarker, uploadIDMa
// NewMultipartUpload. // NewMultipartUpload.
return result, nil return result, nil
} }
result.Uploads = []uploadMetadata{{prefix, prefix, time.Now().UTC(), "", nil}} result.Uploads = []uploadMetadata{{prefix, prefix, UTCNow(), "", nil}}
return result, nil return result, nil
} }
@ -439,7 +439,7 @@ func (a AzureObjects) PutObjectPart(bucket, object, uploadID string, partID int,
info.PartNumber = partID info.PartNumber = partID
info.ETag = md5Hex info.ETag = md5Hex
info.LastModified = time.Now().UTC() info.LastModified = UTCNow()
info.Size = size info.Size = size
return info, nil return info, nil
} }
@ -476,7 +476,7 @@ func (a AzureObjects) ListObjectParts(bucket, object, uploadID string, partNumbe
} }
result.Parts = append(result.Parts, PartInfo{ result.Parts = append(result.Parts, PartInfo{
partID, partID,
time.Now().UTC(), UTCNow(),
md5Hex, md5Hex,
part.Size, part.Size,
}) })

View File

@ -23,7 +23,6 @@ import (
"math/rand" "math/rand"
"strconv" "strconv"
"testing" "testing"
"time"
humanize "github.com/dustin/go-humanize" humanize "github.com/dustin/go-humanize"
) )
@ -245,7 +244,7 @@ func runGetObjectBenchmark(b *testing.B, obj ObjectLayer, objSize int) {
func getRandomByte() []byte { func getRandomByte() []byte {
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ" const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
// seeding the random number generator. // seeding the random number generator.
rand.Seed(time.Now().UTC().UnixNano()) rand.Seed(UTCNow().UnixNano())
var b byte var b byte
// pick a character randomly. // pick a character randomly.
b = letterBytes[rand.Intn(len(letterBytes))] b = letterBytes[rand.Intn(len(letterBytes))]

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -19,7 +19,6 @@ package cmd
import ( import (
"path" "path"
"testing" "testing"
"time"
) )
// API suite container common to both FS and XL. // API suite container common to both FS and XL.
@ -96,7 +95,7 @@ func (s *TestRPCBrowserPeerSuite) testBrowserPeerRPC(t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
rreply := &LoginRPCReply{} rreply := &LoginRPCReply{}
err = rclient.Call("BrowserPeer"+loginMethodName, rargs, rreply) err = rclient.Call("BrowserPeer"+loginMethodName, rargs, rreply)
@ -111,7 +110,7 @@ func (s *TestRPCBrowserPeerSuite) testBrowserPeerRPC(t *testing.T) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
rreply = &LoginRPCReply{} rreply = &LoginRPCReply{}
err = rclient.Call("BrowserPeer"+loginMethodName, rargs, rreply) err = rclient.Call("BrowserPeer"+loginMethodName, rargs, rreply)

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 return
} }
accountID := fmt.Sprintf("%d", time.Now().UTC().UnixNano()) accountID := fmt.Sprintf("%d", UTCNow().UnixNano())
accountARN := fmt.Sprintf( accountARN := fmt.Sprintf(
"%s:%s:%s:%s-%s", "%s:%s:%s:%s-%s",
minioTopic, minioTopic,

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -20,7 +20,6 @@ import (
"bytes" "bytes"
"math/rand" "math/rand"
"testing" "testing"
"time"
"reflect" "reflect"
@ -412,7 +411,7 @@ func TestErasureReadFileRandomOffsetLength(t *testing.T) {
} }
// To generate random offset/length. // 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 // create pool buffer which will be used by erasureReadFile for
// reading from disks and erasure decoding. // reading from disks and erasure decoding.

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -25,7 +25,6 @@ import (
"net/url" "net/url"
"path" "path"
"sync" "sync"
"time"
"github.com/Sirupsen/logrus" "github.com/Sirupsen/logrus"
) )
@ -95,7 +94,7 @@ func newNotificationEvent(event eventData) NotificationEvent {
creds := serverConfig.GetCredential() creds := serverConfig.GetCredential()
// Time when Minio finished processing the request. // Time when Minio finished processing the request.
eventTime := time.Now().UTC() eventTime := UTCNow()
// API endpoint is captured here to be returned back // API endpoint is captured here to be returned back
// to the client for it to differentiate from which // to the client for it to differentiate from which

View File

@ -557,7 +557,7 @@ func TestAddRemoveBucketListenerConfig(t *testing.T) {
} }
// Add a topicConfig to an empty notificationConfig. // Add a topicConfig to an empty notificationConfig.
accountID := fmt.Sprintf("%d", time.Now().UTC().UnixNano()) accountID := fmt.Sprintf("%d", UTCNow().UnixNano())
accountARN := fmt.Sprintf( accountARN := fmt.Sprintf(
"arn:minio:sqs:%s:%s:listen-%s", "arn:minio:sqs:%s:%s:listen-%s",
serverConfig.GetRegion(), serverConfig.GetRegion(),

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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. // Delete uploads.json file wrapper handling a tricky case on windows.
func (fs fsObjects) deleteUploadsJSON(bucket, object, uploadID string) error { 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) tmpPath := pathJoin(fs.fsPath, minioMetaTmpBucket, fs.fsUUID, uploadID+"+"+timeID)
multipartBucketPath := pathJoin(fs.fsPath, minioMetaMultipartBucket) multipartBucketPath := pathJoin(fs.fsPath, minioMetaMultipartBucket)
@ -380,7 +380,7 @@ func (fs fsObjects) newMultipartUpload(bucket string, object string, meta map[st
fsMeta.Meta = meta fsMeta.Meta = meta
uploadID = mustGetUUID() uploadID = mustGetUUID()
initiated := time.Now().UTC() initiated := UTCNow()
// Add upload ID to uploads.json // Add upload ID to uploads.json
uploadsPath := pathJoin(bucket, object, uploadsJSONFile) uploadsPath := pathJoin(bucket, object, uploadsJSONFile)

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 // Verify if the request date header is shifted by less than globalMaxSkewTime parameter in the past
// or in the future, reject request otherwise. // or in the future, reject request otherwise.
curTime := time.Now().UTC() curTime := UTCNow()
if curTime.Sub(amzDate) > globalMaxSkewTime || amzDate.Sub(curTime) > globalMaxSkewTime { if curTime.Sub(amzDate) > globalMaxSkewTime || amzDate.Sub(curTime) > globalMaxSkewTime {
writeErrorResponse(w, ErrRequestTimeTooSkewed, r.URL) writeErrorResponse(w, ErrRequestTimeTooSkewed, r.URL)
return return

View File

@ -59,7 +59,7 @@ func authenticateJWT(accessKey, secretKey string, expiry time.Duration) (string,
return "", errAuthentication return "", errAuthentication
} }
utcNow := time.Now().UTC() utcNow := UTCNow()
token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.MapClaims{ token := jwtgo.NewWithClaims(jwtgo.SigningMethodHS512, jwtgo.MapClaims{
"exp": utcNow.Add(expiry).Unix(), "exp": utcNow.Add(expiry).Unix(),
"iat": utcNow.Unix(), "iat": utcNow.Unix(),

View File

@ -54,7 +54,7 @@ func (initialSnapShot LeakDetect) DetectLeak(t TestErrHandler) {
} }
// Loop, waiting for goroutines to shut down. // Loop, waiting for goroutines to shut down.
// Wait up to 5 seconds, but finish as quickly as possible. // 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 { for {
// get sack snapshot of relevant go routines. // get sack snapshot of relevant go routines.
leaked := initialSnapShot.CompareCurrentSnapshot() leaked := initialSnapShot.CompareCurrentSnapshot()
@ -63,7 +63,7 @@ func (initialSnapShot LeakDetect) DetectLeak(t TestErrHandler) {
return return
} }
// wait a test again will deadline. // wait a test again will deadline.
if time.Now().UTC().Before(deadline) { if UTCNow().Before(deadline) {
time.Sleep(leakDetectPauseTimeMs * time.Millisecond) time.Sleep(leakDetectPauseTimeMs * time.Millisecond)
continue continue
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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, lockSource: lockSource,
lType: lType, lType: lType,
status: status, status: status,
since: time.Now().UTC(), since: UTCNow(),
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,10 +16,7 @@
package cmd package cmd
import ( import "testing"
"testing"
"time"
)
type lockStateCase struct { type lockStateCase struct {
volume string volume string
@ -144,7 +141,7 @@ func getSystemLockState() (SystemLockState, error) {
LockType: lockInfo.lType, LockType: lockInfo.lType,
Status: lockInfo.status, Status: lockInfo.status,
Since: lockInfo.since, Since: lockInfo.since,
Duration: time.Now().UTC().Sub(lockInfo.since), Duration: UTCNow().Sub(lockInfo.since),
}) })
} }
lockState.LocksInfoPerObject = append(lockState.LocksInfoPerObject, volLockInfo) lockState.LocksInfoPerObject = append(lockState.LocksInfoPerObject, volLockInfo)
@ -414,7 +411,7 @@ func TestNsLockMapStatusBlockedToRunning(t *testing.T) {
globalNSMutex.debugLockMap[param].lockInfo[testCases[0].opsID] = debugLockInfo{ globalNSMutex.debugLockMap[param].lockInfo[testCases[0].opsID] = debugLockInfo{
lockSource: "/home/vadmeste/work/go/src/github.com/minio/minio/xl-v1-object.go:683 +0x2a", 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`. status: "Running", // State set to "Running". Should fail with `LockInfoStateNotBlocked`.
since: time.Now().UTC(), since: UTCNow(),
} }
actualErr = globalNSMutex.statusBlockedToRunning(param, testCases[0].lockSource, actualErr = globalNSMutex.statusBlockedToRunning(param, testCases[0].lockSource,

View File

@ -19,7 +19,6 @@ package cmd
import ( import (
"fmt" "fmt"
"testing" "testing"
"time"
"github.com/minio/dsync" "github.com/minio/dsync"
) )
@ -29,7 +28,7 @@ func TestLockRPCClient(t *testing.T) {
lkClient := newLockRPCClient(authConfig{ lkClient := newLockRPCClient(authConfig{
accessKey: "abcd", accessKey: "abcd",
secretKey: "abcd123", secretKey: "abcd123",
serverAddr: fmt.Sprintf("%X", time.Now().UTC().UnixNano()), serverAddr: fmt.Sprintf("%X", UTCNow().UnixNano()),
serviceEndpoint: pathJoin(lockRPCPath, "/test/1"), serviceEndpoint: pathJoin(lockRPCPath, "/test/1"),
secureConn: false, secureConn: false,
serviceName: "Dsync", serviceName: "Dsync",

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 // Check whether enough time has gone by since last check
if time.Since(lriArray[idx].timeLastCheck) >= interval { if time.Since(lriArray[idx].timeLastCheck) >= interval {
rslt = append(rslt, nameLockRequesterInfoPair{name: name, lri: lriArray[idx]}) rslt = append(rslt, nameLockRequesterInfoPair{name: name, lri: lriArray[idx]})
lriArray[idx].timeLastCheck = time.Now().UTC() lriArray[idx].timeLastCheck = UTCNow()
} }
} }
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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", node: "host",
rpcPath: "rpc-path", rpcPath: "rpc-path",
uid: "0123-4567", uid: "0123-4567",
timestamp: time.Now().UTC(), timestamp: UTCNow(),
timeLastCheck: time.Now().UTC(), timeLastCheck: UTCNow(),
} }
nlrip := nameLockRequesterInfoPair{name: "name", lri: lri} nlrip := nameLockRequesterInfoPair{name: "name", lri: lri}
@ -69,16 +69,16 @@ func TestLockRpcServerRemoveEntry(t *testing.T) {
node: "host", node: "host",
rpcPath: "rpc-path", rpcPath: "rpc-path",
uid: "0123-4567", uid: "0123-4567",
timestamp: time.Now().UTC(), timestamp: UTCNow(),
timeLastCheck: time.Now().UTC(), timeLastCheck: UTCNow(),
} }
lockRequesterInfo2 := lockRequesterInfo{ lockRequesterInfo2 := lockRequesterInfo{
writer: true, writer: true,
node: "host", node: "host",
rpcPath: "rpc-path", rpcPath: "rpc-path",
uid: "89ab-cdef", uid: "89ab-cdef",
timestamp: time.Now().UTC(), timestamp: UTCNow(),
timeLastCheck: time.Now().UTC(), timeLastCheck: UTCNow(),
} }
locker.lockMap["name"] = []lockRequesterInfo{ locker.lockMap["name"] = []lockRequesterInfo{
@ -116,7 +116,7 @@ func TestLockRpcServerRemoveEntry(t *testing.T) {
// Tests function returning long lived locks. // Tests function returning long lived locks.
func TestLockRpcServerGetLongLivedLocks(t *testing.T) { func TestLockRpcServerGetLongLivedLocks(t *testing.T) {
ut := time.Now().UTC() ut := UTCNow()
// Collection of test cases for verifying returning valid long lived locks. // Collection of test cases for verifying returning valid long lived locks.
testCases := []struct { testCases := []struct {
lockMap map[string][]lockRequesterInfo lockMap map[string][]lockRequesterInfo

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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, node: args.LockArgs.ServerAddr,
rpcPath: args.LockArgs.ServiceEndpoint, rpcPath: args.LockArgs.ServiceEndpoint,
uid: args.LockArgs.UID, uid: args.LockArgs.UID,
timestamp: time.Now().UTC(), timestamp: UTCNow(),
timeLastCheck: time.Now().UTC(), timeLastCheck: UTCNow(),
}, },
} }
} }
@ -186,8 +186,8 @@ func (l *lockServer) RLock(args *LockArgs, reply *bool) error {
node: args.LockArgs.ServerAddr, node: args.LockArgs.ServerAddr,
rpcPath: args.LockArgs.ServiceEndpoint, rpcPath: args.LockArgs.ServiceEndpoint,
uid: args.LockArgs.UID, uid: args.LockArgs.UID,
timestamp: time.Now().UTC(), timestamp: UTCNow(),
timeLastCheck: time.Now().UTC(), timeLastCheck: UTCNow(),
} }
if lri, ok := l.lockMap[args.LockArgs.Resource]; ok { if lri, ok := l.lockMap[args.LockArgs.Resource]; ok {
if *reply = !isWriteLock(lri); *reply { // Unless there is a write lock if *reply = !isWriteLock(lri); *reply { // Unless there is a write lock

View File

@ -21,7 +21,6 @@ import (
"runtime" "runtime"
"sync" "sync"
"testing" "testing"
"time"
"github.com/minio/dsync" "github.com/minio/dsync"
) )
@ -61,7 +60,7 @@ func createLockTestServer(t *testing.T) (string, *lockServer, string) {
Username: creds.AccessKey, Username: creds.AccessKey,
Password: creds.SecretKey, Password: creds.SecretKey,
Version: Version, Version: Version,
RequestTime: time.Now().UTC(), RequestTime: UTCNow(),
} }
loginReply := LoginRPCReply{} loginReply := LoginRPCReply{}
err = locker.Login(&loginArgs, &loginReply) err = locker.Login(&loginArgs, &loginReply)

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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() defer globalNSMutex.lockMapMutex.Unlock()
// Fetch current time once instead of fetching system time for every lock. // Fetch current time once instead of fetching system time for every lock.
timeNow := time.Now().UTC() timeNow := UTCNow()
volumeLocks := []VolumeLockInfo{} volumeLocks := []VolumeLockInfo{}
for param, debugLock := range globalNSMutex.debugLockMap { for param, debugLock := range globalNSMutex.debugLockMap {

View File

@ -21,7 +21,6 @@ import (
"net/url" "net/url"
"runtime" "runtime"
"sync" "sync"
"time"
humanize "github.com/dustin/go-humanize" humanize "github.com/dustin/go-humanize"
) )
@ -71,7 +70,7 @@ func dirObjectInfo(bucket, object string, size int64, metadata map[string]string
return ObjectInfo{ return ObjectInfo{
Bucket: bucket, Bucket: bucket,
Name: object, Name: object,
ModTime: time.Now().UTC(), ModTime: UTCNow(),
ContentType: "application/octet-stream", ContentType: "application/octet-stream",
IsDir: true, IsDir: true,
Size: size, Size: size,

View File

@ -37,7 +37,7 @@ const (
) )
func newPostPolicyBytesV4WithContentRange(credential, bucketName, objectKey string, expiration time.Time) []byte { func newPostPolicyBytesV4WithContentRange(credential, bucketName, objectKey string, expiration time.Time) []byte {
t := time.Now().UTC() t := UTCNow()
// Add the expiration date. // Add the expiration date.
expirationStr := fmt.Sprintf(`"expiration": "%s"`, expiration.Format(expirationDateFormat)) expirationStr := fmt.Sprintf(`"expiration": "%s"`, expiration.Format(expirationDateFormat))
// Add the bucket condition, only accept buckets equal to the one passed. // 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. // newPostPolicyBytesV4 - creates a bare bones postpolicy string with key and bucket matches.
func newPostPolicyBytesV4(credential, bucketName, objectKey string, expiration time.Time) []byte { func newPostPolicyBytesV4(credential, bucketName, objectKey string, expiration time.Time) []byte {
t := time.Now().UTC() t := UTCNow()
// Add the expiration date. // Add the expiration date.
expirationStr := fmt.Sprintf(`"expiration": "%s"`, expiration.Format(expirationDateFormat)) expirationStr := fmt.Sprintf(`"expiration": "%s"`, expiration.Format(expirationDateFormat))
// Add the bucket condition, only accept buckets equal to the one passed. // 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() credentials := serverConfig.GetCredential()
curTime := time.Now().UTC() curTime := UTCNow()
curTimePlus5Min := curTime.Add(time.Minute * 5) curTimePlus5Min := curTime.Add(time.Minute * 5)
// bucketnames[0]. // bucketnames[0].
@ -455,7 +455,7 @@ func testPostPolicyBucketHandlerRedirect(obj ObjectLayer, instanceType string, t
credentials := serverConfig.GetCredential() credentials := serverConfig.GetCredential()
curTime := time.Now().UTC() curTime := UTCNow()
curTimePlus5Min := curTime.Add(time.Minute * 5) curTimePlus5Min := curTime.Add(time.Minute * 5)
err = obj.MakeBucket(bucketName) 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) { func newPostRequestV2(endPoint, bucketName, objectName string, accessKey, secretKey string) (*http.Request, error) {
// Expire the request five minutes from now. // 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. // Create a new post policy.
policy := newPostPolicyBytesV2(bucketName, objectName, expirationTime) policy := newPostPolicyBytesV2(bucketName, objectName, expirationTime)
// Only need the encoding. // 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) { 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) policy := buildGenericPolicy(t, accessKey, bucketName, objectName, true)
return newPostRequestV4Generic(endPoint, bucketName, objectName, objData, accessKey, secretKey, t, policy, nil, false, false) 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) { 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) policy := buildGenericPolicy(t, accessKey, bucketName, objectName, false)
return newPostRequestV4Generic(endPoint, bucketName, objectName, objData, accessKey, secretKey, t, policy, nil, false, false) return newPostRequestV4Generic(endPoint, bucketName, objectName, objData, accessKey, secretKey, t, policy, nil, false, false)
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) // (http://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-HTTPPOSTConstructPolicy.html)
func checkPostPolicy(formValues http.Header, postPolicyForm PostPolicyForm) APIErrorCode { func checkPostPolicy(formValues http.Header, postPolicyForm PostPolicyForm) APIErrorCode {
// Check if policy document expiry date is still not reached // Check if policy document expiry date is still not reached
if !postPolicyForm.Expiration.After(time.Now().UTC()) { if !postPolicyForm.Expiration.After(UTCNow()) {
return ErrPolicyAlreadyExpired return ErrPolicyAlreadyExpired
} }

View File

@ -54,7 +54,7 @@ const NoJitter = 0.0
// Global random source for fetching random values. // Global random source for fetching random values.
var globalRandomSource = rand.New(&lockedRandSource{ 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 // newRetryTimerJitter creates a timer with exponentially increasing delays

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 { func isRequestTimeAllowed(requestTime time.Time) bool {
// Check whether request time is within acceptable skew time. // Check whether request time is within acceptable skew time.
utcNow := time.Now().UTC() utcNow := UTCNow()
return !(requestTime.Sub(utcNow) > rpcSkewTimeAllowed || return !(requestTime.Sub(utcNow) > rpcSkewTimeAllowed ||
utcNow.Sub(requestTime) > rpcSkewTimeAllowed) utcNow.Sub(requestTime) > rpcSkewTimeAllowed)
} }

View File

@ -596,7 +596,7 @@ func serverMain(c *cli.Context) {
} }
// Set uptime time after object layer has initialized. // Set uptime time after object layer has initialized.
globalBootTime = time.Now().UTC() globalBootTime = UTCNow()
// Waits on the server. // Waits on the server.
<-globalServiceDoneCh <-globalServiceDoneCh

View File

@ -438,8 +438,8 @@ func generateTestCert(host string) error {
Subject: pkix.Name{ Subject: pkix.Name{
Organization: []string{"Minio Test Cert"}, Organization: []string{"Minio Test Cert"},
}, },
NotBefore: time.Now().UTC(), NotBefore: UTCNow(),
NotAfter: time.Now().UTC().Add(time.Minute * 1), NotAfter: UTCNow().Add(time.Minute * 1),
KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature, KeyUsage: x509.KeyUsageKeyEncipherment | x509.KeyUsageDigitalSignature,
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth},

View File

@ -21,7 +21,6 @@ import (
"fmt" "fmt"
"runtime" "runtime"
"strings" "strings"
"time"
humanize "github.com/dustin/go-humanize" humanize "github.com/dustin/go-humanize"
"github.com/minio/mc/pkg/console" "github.com/minio/mc/pkg/console"
@ -161,7 +160,7 @@ func getCertificateChainMsg(certs []*x509.Certificate) string {
var expiringCerts int var expiringCerts int
for i := totalCerts - 1; i >= 0; i-- { for i := totalCerts - 1; i >= 0; i-- {
cert := certs[i] cert := certs[i]
if cert.NotAfter.Before(time.Now().UTC().Add(globalMinioCertExpireWarnDays)) { if cert.NotAfter.Before(UTCNow().Add(globalMinioCertExpireWarnDays)) {
expiringCerts++ expiringCerts++
msg += fmt.Sprintf(colorBold("#%d %s will expire on %s\n"), expiringCerts, cert.Subject.CommonName, cert.NotAfter) msg += fmt.Sprintf(colorBold("#%d %s will expire on %s\n"), expiringCerts, cert.Subject.CommonName, cert.NotAfter)
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,1234567890,
1234567890,1234567890,1234567890,123` 1234567890,1234567890,1234567890,123`
rand.Seed(time.Now().UTC().UnixNano()) rand.Seed(UTCNow().UnixNano())
// Create a misalgined data. // Create a misalgined data.
for i := 0; i < 13*rand.Intn(1<<16); i++ { for i := 0; i < 13*rand.Intn(1<<16); i++ {
buffer.WriteString(fmt.Sprintf("[%05d] %s\n", i, line[:rand.Intn(1<<8)])) buffer.WriteString(fmt.Sprintf("[%05d] %s\n", i, line[:rand.Intn(1<<8)]))

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -26,7 +26,6 @@ import (
"sort" "sort"
"strconv" "strconv"
"strings" "strings"
"time"
) )
// Signature and API related constants. // Signature and API related constants.
@ -136,7 +135,7 @@ func doesPresignV2SignatureMatch(r *http.Request) APIErrorCode {
} }
// Check if the presigned URL has expired. // Check if the presigned URL has expired.
if expiresInt < time.Now().UTC().Unix() { if expiresInt < UTCNow().Unix() {
return ErrExpiredPresignRequest return ErrExpiredPresignRequest
} }

View File

@ -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 package cmd
import ( import (
@ -6,7 +22,6 @@ import (
"net/url" "net/url"
"sort" "sort"
"testing" "testing"
"time"
) )
// Tests for 'func TestResourceListSorting(t *testing.T)'. // Tests for 'func TestResourceListSorting(t *testing.T)'.
@ -30,7 +45,7 @@ func TestDoesPresignedV2SignatureMatch(t *testing.T) {
} }
defer removeAll(root) defer removeAll(root)
now := time.Now().UTC() now := UTCNow()
testCases := []struct { testCases := []struct {
queryParams map[string]string queryParams map[string]string

View File

@ -87,7 +87,7 @@ func validateCredentialfields(t *testing.T, testNum int, expectedCredentials cre
// },"/") // },"/")
func TestParseCredentialHeader(t *testing.T) { func TestParseCredentialHeader(t *testing.T) {
sampleTimeStr := time.Now().UTC().Format(yyyymmdd) sampleTimeStr := UTCNow().Format(yyyymmdd)
testCases := []struct { testCases := []struct {
inputCredentialStr string inputCredentialStr string
@ -120,7 +120,7 @@ func TestParseCredentialHeader(t *testing.T) {
{ {
inputCredentialStr: generateCredentialStr( inputCredentialStr: generateCredentialStr(
"^#@.", "^#@.",
time.Now().UTC().Format(yyyymmdd), UTCNow().Format(yyyymmdd),
"ABCD", "ABCD",
"ABCD", "ABCD",
"ABCD"), "ABCD"),
@ -133,7 +133,7 @@ func TestParseCredentialHeader(t *testing.T) {
{ {
inputCredentialStr: generateCredentialStr( inputCredentialStr: generateCredentialStr(
"Z7IXGOO6BZ0REAN1Q26I", "Z7IXGOO6BZ0REAN1Q26I",
time.Now().UTC().String(), UTCNow().String(),
"ABCD", "ABCD",
"ABCD", "ABCD",
"ABCD"), "ABCD"),
@ -146,7 +146,7 @@ func TestParseCredentialHeader(t *testing.T) {
{ {
inputCredentialStr: generateCredentialStr( inputCredentialStr: generateCredentialStr(
"Z7IXGOO6BZ0REAN1Q26I", "Z7IXGOO6BZ0REAN1Q26I",
time.Now().UTC().Format(yyyymmdd), UTCNow().Format(yyyymmdd),
"", "",
"ABCD", "ABCD",
"ABCD"), "ABCD"),
@ -159,7 +159,7 @@ func TestParseCredentialHeader(t *testing.T) {
{ {
inputCredentialStr: generateCredentialStr( inputCredentialStr: generateCredentialStr(
"Z7IXGOO6BZ0REAN1Q26I", "Z7IXGOO6BZ0REAN1Q26I",
time.Now().UTC().Format(yyyymmdd), UTCNow().Format(yyyymmdd),
"us-west-1", "us-west-1",
"ABCD", "ABCD",
"ABCD"), "ABCD"),
@ -172,7 +172,7 @@ func TestParseCredentialHeader(t *testing.T) {
{ {
inputCredentialStr: generateCredentialStr( inputCredentialStr: generateCredentialStr(
"Z7IXGOO6BZ0REAN1Q26I", "Z7IXGOO6BZ0REAN1Q26I",
time.Now().UTC().Format(yyyymmdd), UTCNow().Format(yyyymmdd),
"us-west-1", "us-west-1",
"s3", "s3",
"ABCD"), "ABCD"),
@ -313,7 +313,7 @@ func TestParseSignedHeaders(t *testing.T) {
// TestParseSignV4 - Tests Parsing of v4 signature form the authorization string. // TestParseSignV4 - Tests Parsing of v4 signature form the authorization string.
func TestParseSignV4(t *testing.T) { func TestParseSignV4(t *testing.T) {
sampleTimeStr := time.Now().UTC().Format(yyyymmdd) sampleTimeStr := UTCNow().Format(yyyymmdd)
testCases := []struct { testCases := []struct {
inputV4AuthStr string inputV4AuthStr string
expectedAuthField signValues expectedAuthField signValues
@ -572,9 +572,9 @@ func TestParsePreSignV4(t *testing.T) {
return strconv.Itoa(expires) return strconv.Itoa(expires)
} }
// used in expected preSignValues, preSignValues.Date is of type time.Time . // 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 { testCases := []struct {
inputQueryKeyVals []string inputQueryKeyVals []string
@ -668,7 +668,7 @@ func TestParsePreSignV4(t *testing.T) {
"s3", "s3",
"aws4_request"), "aws4_request"),
// valid "X-Amz-Date" query. // 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-Expires", "MalformedExpiry",
"X-Amz-SignedHeaders", "", "X-Amz-SignedHeaders", "",
"X-Amz-Signature", "", "X-Amz-Signature", "",

View File

@ -19,7 +19,6 @@ package cmd
import ( import (
"net/http" "net/http"
"testing" "testing"
"time"
) )
// TestSkipContentSha256Cksum - Test validate the logic which decides whether // TestSkipContentSha256Cksum - Test validate the logic which decides whether
@ -140,7 +139,7 @@ func TestExtractSignedHeaders(t *testing.T) {
// expected header values. // expected header values.
expectedHost := "play.minio.io:9000" expectedHost := "play.minio.io:9000"
expectedContentSha256 := "1234abcd" expectedContentSha256 := "1234abcd"
expectedTime := time.Now().UTC().Format(iso8601Format) expectedTime := UTCNow().Format(iso8601Format)
// Creating input http header. // Creating input http header.
inputHeader := make(http.Header) inputHeader := make(http.Header)

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 // If the host which signed the request is slightly ahead in time (by less than globalMaxSkewTime) the
// request should still be allowed. // request should still be allowed.
if pSignValues.Date.After(time.Now().UTC().Add(globalMaxSkewTime)) { if pSignValues.Date.After(UTCNow().Add(globalMaxSkewTime)) {
return ErrRequestNotReadyYet return ErrRequestNotReadyYet
} }
if time.Now().UTC().Sub(pSignValues.Date) > time.Duration(pSignValues.Expires) { if UTCNow().Sub(pSignValues.Date) > time.Duration(pSignValues.Expires) {
return ErrExpiredPresignRequest return ErrExpiredPresignRequest
} }

View File

@ -35,7 +35,7 @@ func niceError(code APIErrorCode) string {
func TestDoesPolicySignatureMatch(t *testing.T) { func TestDoesPolicySignatureMatch(t *testing.T) {
credentialTemplate := "%s/%s/%s/s3/aws4_request" credentialTemplate := "%s/%s/%s/s3/aws4_request"
now := time.Now().UTC() now := UTCNow()
accessKey := serverConfig.GetCredential().AccessKey accessKey := serverConfig.GetCredential().AccessKey
testCases := []struct { testCases := []struct {
@ -106,7 +106,7 @@ func TestDoesPresignedSignatureMatch(t *testing.T) {
// sha256 hash of "payload" // sha256 hash of "payload"
payloadSHA256 := "239f59ed55e737c77147cf55ad0c1b030b6d7ee748a7426952f9b852d5a935e5" payloadSHA256 := "239f59ed55e737c77147cf55ad0c1b030b6d7ee748a7426952f9b852d5a935e5"
now := time.Now().UTC() now := UTCNow()
credentialTemplate := "%s/%s/%s/s3/aws4_request" credentialTemplate := "%s/%s/%s/s3/aws4_request"
region := serverConfig.GetRegion() region := serverConfig.GetRegion()

View File

@ -19,7 +19,6 @@ package cmd
import ( import (
"net/url" "net/url"
"testing" "testing"
"time"
"github.com/minio/minio/pkg/disk" "github.com/minio/minio/pkg/disk"
) )
@ -63,7 +62,7 @@ func createTestStorageServer(t *testing.T) *testStorageRPCServer {
stServer := &storageServer{ stServer := &storageServer{
storage: storageDisks[0], storage: storageDisks[0],
path: "/disk1", path: "/disk1",
timestamp: time.Now().UTC(), timestamp: UTCNow(),
} }
return &testStorageRPCServer{ return &testStorageRPCServer{
token: token, token: token,

View File

@ -816,7 +816,7 @@ func newTestStreamingSignedBadChunkDateRequest(method, urlStr string, contentLen
return nil, err return nil, err
} }
currTime := time.Now().UTC() currTime := UTCNow()
signature, err := signStreamingRequest(req, accessKey, secretKey, currTime) signature, err := signStreamingRequest(req, accessKey, secretKey, currTime)
if err != nil { if err != nil {
return nil, err return nil, err
@ -835,7 +835,7 @@ func newTestStreamingSignedRequest(method, urlStr string, contentLength, chunkSi
return nil, err return nil, err
} }
currTime := time.Now().UTC() currTime := UTCNow()
signature, err := signStreamingRequest(req, accessKey, secretKey, currTime) signature, err := signStreamingRequest(req, accessKey, secretKey, currTime)
if err != nil { if err != nil {
return nil, err return nil, err
@ -887,7 +887,7 @@ func preSignV4(req *http.Request, accessKeyID, secretAccessKey string, expires i
} }
region := serverConfig.GetRegion() region := serverConfig.GetRegion()
date := time.Now().UTC() date := UTCNow()
scope := getScope(date, region) scope := getScope(date, region)
credential := fmt.Sprintf("%s/%s", accessKeyID, scope) 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") 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. // Find epoch expires when the request will expire.
epochExpires := d.Unix() + expires epochExpires := d.Unix() + expires
@ -975,7 +975,7 @@ func preSignV2(req *http.Request, accessKeyID, secretAccessKey string, expires i
// Sign given request using Signature V2. // Sign given request using Signature V2.
func signRequestV2(req *http.Request, accessKey, secretKey string) error { func signRequestV2(req *http.Request, accessKey, secretKey string) error {
// Initial time. // Initial time.
d := time.Now().UTC() d := UTCNow()
// Add date if not present. // Add date if not present.
if date := req.Header.Get("Date"); date == "" { 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") return fmt.Errorf("Invalid hashed payload")
} }
currTime := time.Now().UTC() currTime := UTCNow()
// Set x-amz-date. // Set x-amz-date.
req.Header.Set("x-amz-date", currTime.Format(iso8601Format)) req.Header.Set("x-amz-date", currTime.Format(iso8601Format))
@ -1297,7 +1297,7 @@ func getTestWebRPCResponse(resp *httptest.ResponseRecorder, data interface{}) er
return nil 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. // Function to generate random string for bucket/object names.
func randString(n int) string { func randString(n int) string {

View File

@ -31,7 +31,7 @@ import (
) )
func TestGetCurrentReleaseTime(t *testing.T) { func TestGetCurrentReleaseTime(t *testing.T) {
minioVersion1 := time.Now().UTC().Format(time.RFC3339) minioVersion1 := UTCNow().Format(time.RFC3339)
releaseTime1, _ := time.Parse(time.RFC3339, minioVersion1) releaseTime1, _ := time.Parse(time.RFC3339, minioVersion1)
minioVersion2 := "DEVELOPMENT.GOGET" minioVersion2 := "DEVELOPMENT.GOGET"
@ -223,7 +223,7 @@ func TestIsSourceBuild(t *testing.T) {
minioVersion string minioVersion string
expectedResult bool expectedResult bool
}{ }{
{time.Now().UTC().Format(time.RFC3339), false}, {UTCNow().Format(time.RFC3339), false},
{"DEVELOPMENT.GOGET", true}, {"DEVELOPMENT.GOGET", true},
{"junk", true}, {"junk", true},
{"3.2.4", true}, {"3.2.4", true},

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -26,6 +26,7 @@ import (
"net/url" "net/url"
"os" "os"
"strings" "strings"
"time"
"encoding/json" "encoding/json"
@ -275,3 +276,8 @@ func checkURL(address string) (*url.URL, error) {
} }
return u, nil return u, nil
} }
// UTCNow - returns current UTC time.
func UTCNow() time.Time {
return time.Now().UTC()
}

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 accessKey := cred.AccessKey
secretKey := cred.SecretKey secretKey := cred.SecretKey
date := time.Now().UTC() date := UTCNow()
dateStr := date.Format(iso8601Format) dateStr := date.Format(iso8601Format)
credential := fmt.Sprintf("%s/%s", accessKey, getScope(date, region)) credential := fmt.Sprintf("%s/%s", accessKey, getScope(date, region))

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -16,15 +16,12 @@
package cmd package cmd
import ( import "path"
"path"
"time"
)
// getLoadBalancedDisks - fetches load balanced (sufficiently randomized) disk slice. // getLoadBalancedDisks - fetches load balanced (sufficiently randomized) disk slice.
func (xl xlObjects) getLoadBalancedDisks() (disks []StorageAPI) { func (xl xlObjects) getLoadBalancedDisks() (disks []StorageAPI) {
// Based on the random shuffling return back randomized disks. // 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]) disks = append(disks, xl.storageDisks[i-1])
} }
return disks return disks

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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) { func TestPickValidXLMeta(t *testing.T) {
obj := "object" obj := "object"
x1 := newXLMetaV1(obj, 4, 4) x1 := newXLMetaV1(obj, 4, 4)
now := time.Now().UTC() now := UTCNow()
x1.Stat.ModTime = now x1.Stat.ModTime = now
invalidX1 := x1 invalidX1 := x1
invalidX1.Version = "invalid-version" invalidX1.Version = "invalid-version"

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 meta["content-type"] = contentType
} }
xlMeta.Stat.ModTime = time.Now().UTC() xlMeta.Stat.ModTime = UTCNow()
xlMeta.Meta = meta xlMeta.Meta = meta
// This lock needs to be held for any changes to the directory // 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) return "", toObjectErr(rErr, minioMetaMultipartBucket, uploadIDPath)
} }
initiated := time.Now().UTC() initiated := UTCNow()
// Create or update 'uploads.json' // Create or update 'uploads.json'
if err = xl.addUploadID(bucket, object, uploadID, initiated); err != nil { if err = xl.addUploadID(bucket, object, uploadID, initiated); err != nil {
return "", err 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. // Once part is successfully committed, proceed with updating XL metadata.
xlMeta.Stat.ModTime = time.Now().UTC() xlMeta.Stat.ModTime = UTCNow()
// Add the current part. // Add the current part.
xlMeta.AddObjectPart(partID, partSuffix, newMD5Hex, size) 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. // Save the final object size and modtime.
xlMeta.Stat.Size = objectSize xlMeta.Stat.Size = objectSize
xlMeta.Stat.ModTime = time.Now().UTC() xlMeta.Stat.ModTime = UTCNow()
// Save successfully calculated md5sum. // Save successfully calculated md5sum.
xlMeta.Meta["md5Sum"] = s3MD5 xlMeta.Meta["md5Sum"] = s3MD5

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with 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 isRemove bool
errVal error errVal error
}{ }{
{"111abc", time.Now().UTC(), false, nil}, {"111abc", UTCNow(), false, nil},
{"222abc", time.Now().UTC(), false, nil}, {"222abc", UTCNow(), false, nil},
{"111abc", time.Time{}, true, 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) 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() { if testErrVal == nil || testErrVal.Error() != errXLWriteQuorum.Error() {
t.Errorf("Expected write quorum error, but got: %v", testErrVal) t.Errorf("Expected write quorum error, but got: %v", testErrVal)
} }

View File

@ -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"); * Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License. * you may not use this file except in compliance with the License.
@ -25,7 +25,6 @@ import (
"strconv" "strconv"
"strings" "strings"
"sync" "sync"
"time"
"github.com/minio/minio/pkg/bpool" "github.com/minio/minio/pkg/bpool"
"github.com/minio/minio/pkg/mimedb" "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. // Save additional erasureMetadata.
modTime := time.Now().UTC() modTime := UTCNow()
newMD5Hex := hex.EncodeToString(md5Writer.Sum(nil)) newMD5Hex := hex.EncodeToString(md5Writer.Sum(nil))
// Update the md5sum if not set with the newly calculated one. // Update the md5sum if not set with the newly calculated one.

View File

@ -21,7 +21,6 @@ import (
"reflect" "reflect"
"strconv" "strconv"
"testing" "testing"
"time"
humanize "github.com/dustin/go-humanize" humanize "github.com/dustin/go-humanize"
) )
@ -146,7 +145,7 @@ func newTestXLMetaV1() xlMetaV1 {
} }
xlMeta.Stat = statInfo{ xlMeta.Stat = statInfo{
Size: int64(20), Size: int64(20),
ModTime: time.Now().UTC(), ModTime: UTCNow(),
} }
// Set meta data. // Set meta data.
xlMeta.Meta = make(map[string]string) xlMeta.Meta = make(map[string]string)