minio/pkg/storage/drivers/memory/memory.go

383 lines
12 KiB
Go
Raw Normal View History

/*
* Minimalist Object Storage, (C) 2015 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 memory
import (
"bufio"
"bytes"
"io"
"sort"
"strings"
"sync"
"time"
"crypto/md5"
"encoding/hex"
"io/ioutil"
"github.com/golang/groupcache/lru"
"github.com/minio-io/minio/pkg/iodine"
"github.com/minio-io/minio/pkg/storage/drivers"
2015-04-22 20:50:26 -04:00
"github.com/minio-io/minio/pkg/utils/log"
)
// memoryDriver - local variables
type memoryDriver struct {
bucketMetadata map[string]storedBucket
objectMetadata map[string]storedObject
objects *lru.Cache
lock *sync.RWMutex
totalSize uint64
maxSize uint64
}
type storedBucket struct {
metadata drivers.BucketMetadata
// owner string // TODO
// id string // TODO
}
type storedObject struct {
metadata drivers.ObjectMetadata
}
// Start memory object server
func Start(maxSize uint64) (chan<- string, <-chan error, drivers.Driver) {
ctrlChannel := make(chan string)
errorChannel := make(chan error)
2015-04-22 20:50:26 -04:00
var memory *memoryDriver
memory = new(memoryDriver)
memory.bucketMetadata = make(map[string]storedBucket)
memory.objectMetadata = make(map[string]storedObject)
2015-04-22 20:50:26 -04:00
memory.objects = lru.New(0)
memory.lock = new(sync.RWMutex)
2015-04-22 20:50:26 -04:00
switch {
case maxSize == 0:
memory.maxSize = 9223372036854775807
case maxSize > 0:
memory.maxSize = maxSize
default:
log.Println("Error")
}
memory.objects.OnEvicted = memory.evictObject
go start(ctrlChannel, errorChannel)
return ctrlChannel, errorChannel, memory
}
func start(ctrlChannel <-chan string, errorChannel chan<- error) {
close(errorChannel)
}
// GetObject - GET object from memory buffer
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) GetObject(w io.Writer, bucket string, object string) (int64, error) {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
defer memory.lock.RUnlock()
if !drivers.IsValidBucket(bucket) {
return 0, iodine.New(drivers.BucketNameInvalid{Bucket: bucket}, nil)
}
if !drivers.IsValidObject(object) {
return 0, iodine.New(drivers.ObjectNameInvalid{Object: object}, nil)
}
if _, ok := memory.bucketMetadata[bucket]; ok == false {
return 0, iodine.New(drivers.BucketNotFound{Bucket: bucket}, nil)
}
// get object
objectKey := bucket + "/" + object
if _, ok := memory.objectMetadata[objectKey]; ok {
if data, ok := memory.objects.Get(objectKey); ok {
dataSlice := data.([]byte)
objectBuffer := bytes.NewBuffer(dataSlice)
written, err := io.Copy(w, objectBuffer)
return written, iodine.New(err, nil)
}
}
return 0, iodine.New(drivers.ObjectNotFound{Bucket: bucket, Object: object}, nil)
}
// GetPartialObject - GET object from memory buffer range
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) GetPartialObject(w io.Writer, bucket, object string, start, length int64) (int64, error) {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
defer memory.lock.RUnlock()
var sourceBuffer bytes.Buffer
if !drivers.IsValidBucket(bucket) {
return 0, iodine.New(drivers.BucketNameInvalid{Bucket: bucket}, nil)
}
if !drivers.IsValidObject(object) {
return 0, iodine.New(drivers.ObjectNameInvalid{Object: object}, nil)
}
if _, err := memory.GetObject(&sourceBuffer, bucket, object); err != nil {
return 0, iodine.New(err, nil)
}
if _, err := io.CopyN(ioutil.Discard, &sourceBuffer, start); err != nil {
return 0, iodine.New(err, nil)
}
return io.CopyN(w, &sourceBuffer, length)
}
// GetBucketMetadata -
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) GetBucketMetadata(bucket string) (drivers.BucketMetadata, error) {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
defer memory.lock.RUnlock()
if !drivers.IsValidBucket(bucket) {
return drivers.BucketMetadata{}, iodine.New(drivers.BucketNameInvalid{Bucket: bucket}, nil)
}
if _, ok := memory.bucketMetadata[bucket]; ok == false {
return drivers.BucketMetadata{}, iodine.New(drivers.BucketNotFound{Bucket: bucket}, nil)
}
return memory.bucketMetadata[bucket].metadata, nil
}
// CreateObject - PUT object to memory buffer
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) CreateObject(bucket, key, contentType, md5sum string, data io.Reader) error {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
if !drivers.IsValidBucket(bucket) {
memory.lock.RUnlock()
return iodine.New(drivers.BucketNameInvalid{Bucket: bucket}, nil)
}
if !drivers.IsValidObject(key) {
memory.lock.RUnlock()
return iodine.New(drivers.ObjectNameInvalid{Object: key}, nil)
}
if _, ok := memory.bucketMetadata[bucket]; ok == false {
2015-04-15 14:48:56 -04:00
memory.lock.RUnlock()
return iodine.New(drivers.BucketNotFound{Bucket: bucket}, nil)
}
objectKey := bucket + "/" + key
if _, ok := memory.objectMetadata[objectKey]; ok == true {
2015-04-15 14:48:56 -04:00
memory.lock.RUnlock()
return iodine.New(drivers.ObjectExists{Bucket: bucket, Object: key}, nil)
}
2015-04-15 14:48:56 -04:00
memory.lock.RUnlock()
if contentType == "" {
contentType = "application/octet-stream"
}
contentType = strings.TrimSpace(contentType)
var bytesBuffer bytes.Buffer
var newObject = storedObject{}
var dataSlice []byte
if _, ok := io.Copy(&bytesBuffer, data); ok == nil {
size := bytesBuffer.Len()
md5SumBytes := md5.Sum(bytesBuffer.Bytes())
md5Sum := hex.EncodeToString(md5SumBytes[:])
newObject.metadata = drivers.ObjectMetadata{
Bucket: bucket,
Key: key,
ContentType: contentType,
Created: time.Now(),
Md5: md5Sum,
Size: int64(size),
}
dataSlice = bytesBuffer.Bytes()
}
2015-04-15 14:48:56 -04:00
memory.lock.Lock()
if _, ok := memory.objectMetadata[objectKey]; ok == true {
2015-04-15 14:48:56 -04:00
memory.lock.Unlock()
return iodine.New(drivers.ObjectExists{Bucket: bucket, Object: key}, nil)
2015-04-15 14:48:56 -04:00
}
memory.objectMetadata[objectKey] = newObject
memory.objects.Add(objectKey, dataSlice)
memory.totalSize = memory.totalSize + uint64(newObject.metadata.Size)
2015-04-22 20:50:26 -04:00
for memory.totalSize > memory.maxSize {
memory.objects.RemoveOldest()
}
2015-04-15 14:48:56 -04:00
memory.lock.Unlock()
return nil
}
// CreateBucket - create bucket in memory
2015-04-22 21:19:53 -04:00
func (memory *memoryDriver) CreateBucket(bucketName, acl string) error {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
if !drivers.IsValidBucket(bucketName) {
2015-04-15 14:48:56 -04:00
memory.lock.RUnlock()
return iodine.New(drivers.BucketNameInvalid{Bucket: bucketName}, nil)
}
2015-04-22 21:19:53 -04:00
if !drivers.IsValidBucketACL(acl) {
memory.lock.RUnlock()
return iodine.New(drivers.InvalidACL{ACL: acl}, nil)
2015-04-22 21:19:53 -04:00
}
if _, ok := memory.bucketMetadata[bucketName]; ok == true {
2015-04-15 14:48:56 -04:00
memory.lock.RUnlock()
return iodine.New(drivers.BucketExists{Bucket: bucketName}, nil)
}
2015-04-15 14:48:56 -04:00
memory.lock.RUnlock()
var newBucket = storedBucket{}
newBucket.metadata = drivers.BucketMetadata{}
newBucket.metadata.Name = bucketName
newBucket.metadata.Created = time.Now()
2015-04-22 21:19:53 -04:00
newBucket.metadata.ACL = drivers.BucketACL(acl)
2015-04-15 14:48:56 -04:00
memory.lock.Lock()
defer memory.lock.Unlock()
memory.bucketMetadata[bucketName] = newBucket
return nil
}
func delimiter(object, delimiter string) string {
readBuffer := bytes.NewBufferString(object)
reader := bufio.NewReader(readBuffer)
stringReader := strings.NewReader(delimiter)
delimited, _ := stringReader.ReadByte()
delimitedStr, _ := reader.ReadString(delimited)
return delimitedStr
}
func appendUniq(slice []string, i string) []string {
for _, ele := range slice {
if ele == i {
return slice
}
}
return append(slice, i)
}
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) filterDelimiterPrefix(keys []string, key, delimitedName string, resources drivers.BucketResourcesMetadata) (drivers.BucketResourcesMetadata, []string) {
switch true {
case key == resources.Prefix:
keys = appendUniq(keys, key)
2015-04-22 21:19:53 -04:00
// DelimitedName - requires resources.Prefix as it was trimmed off earlier in the flow
case key == resources.Prefix+delimitedName:
keys = appendUniq(keys, key)
case delimitedName != "":
resources.CommonPrefixes = appendUniq(resources.CommonPrefixes, resources.Prefix+delimitedName)
}
return resources, keys
}
func (memory *memoryDriver) listObjectsInternal(keys []string, key string, resources drivers.BucketResourcesMetadata) ([]string, drivers.BucketResourcesMetadata) {
switch true {
// Prefix absent, delimit object key based on delimiter
case resources.IsDelimiterSet():
delimitedName := delimiter(key, resources.Delimiter)
switch true {
case delimitedName == "" || delimitedName == key:
keys = appendUniq(keys, key)
case delimitedName != "":
resources.CommonPrefixes = appendUniq(resources.CommonPrefixes, delimitedName)
}
// Prefix present, delimit object key with prefix key based on delimiter
case resources.IsDelimiterPrefixSet():
if strings.HasPrefix(key, resources.Prefix) {
trimmedName := strings.TrimPrefix(key, resources.Prefix)
delimitedName := delimiter(trimmedName, resources.Delimiter)
resources, keys = memory.filterDelimiterPrefix(keys, key, delimitedName, resources)
}
// Prefix present, nothing to delimit
case resources.IsPrefixSet():
keys = appendUniq(keys, key)
// Prefix and delimiter absent
case resources.IsDefault():
keys = appendUniq(keys, key)
}
return keys, resources
}
// ListObjects - list objects from memory
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) ListObjects(bucket string, resources drivers.BucketResourcesMetadata) ([]drivers.ObjectMetadata, drivers.BucketResourcesMetadata, error) {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
defer memory.lock.RUnlock()
if !drivers.IsValidBucket(bucket) {
return nil, drivers.BucketResourcesMetadata{IsTruncated: false}, iodine.New(drivers.BucketNameInvalid{Bucket: bucket}, nil)
}
if !drivers.IsValidObject(resources.Prefix) {
return nil, drivers.BucketResourcesMetadata{IsTruncated: false}, iodine.New(drivers.ObjectNameInvalid{Object: resources.Prefix}, nil)
}
if _, ok := memory.bucketMetadata[bucket]; ok == false {
return nil, drivers.BucketResourcesMetadata{IsTruncated: false}, iodine.New(drivers.BucketNotFound{Bucket: bucket}, nil)
}
var results []drivers.ObjectMetadata
var keys []string
for key := range memory.objectMetadata {
if strings.HasPrefix(key, bucket+"/") {
key = key[len(bucket)+1:]
keys, resources = memory.listObjectsInternal(keys, key, resources)
}
}
sort.Strings(keys)
for _, key := range keys {
if len(results) == resources.Maxkeys {
return results, drivers.BucketResourcesMetadata{IsTruncated: true}, nil
}
object := memory.objectMetadata[bucket+"/"+key]
if bucket == object.metadata.Bucket {
results = append(results, object.metadata)
}
}
return results, resources, nil
}
// ByBucketName is a type for sorting bucket metadata by bucket name
type ByBucketName []drivers.BucketMetadata
// Len of bucket name
func (b ByBucketName) Len() int { return len(b) }
// Swap bucket i, j
func (b ByBucketName) Swap(i, j int) { b[i], b[j] = b[j], b[i] }
// Less
func (b ByBucketName) Less(i, j int) bool { return b[i].Name < b[j].Name }
// ListBuckets - List buckets from memory
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) ListBuckets() ([]drivers.BucketMetadata, error) {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
defer memory.lock.RUnlock()
var results []drivers.BucketMetadata
for _, bucket := range memory.bucketMetadata {
results = append(results, bucket.metadata)
}
sort.Sort(ByBucketName(results))
return results, nil
}
// GetObjectMetadata - get object metadata from memory
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) GetObjectMetadata(bucket, key, prefix string) (drivers.ObjectMetadata, error) {
2015-04-15 14:48:56 -04:00
memory.lock.RLock()
defer memory.lock.RUnlock()
// check if bucket exists
if !drivers.IsValidBucket(bucket) {
return drivers.ObjectMetadata{}, iodine.New(drivers.BucketNameInvalid{Bucket: bucket}, nil)
}
if !drivers.IsValidObject(key) || !drivers.IsValidObject(prefix) {
return drivers.ObjectMetadata{}, iodine.New(drivers.ObjectNameInvalid{Object: key}, nil)
}
if _, ok := memory.bucketMetadata[bucket]; ok == false {
return drivers.ObjectMetadata{}, iodine.New(drivers.BucketNotFound{Bucket: bucket}, nil)
}
objectKey := bucket + "/" + key
if object, ok := memory.objectMetadata[objectKey]; ok == true {
return object.metadata, nil
}
return drivers.ObjectMetadata{}, iodine.New(drivers.ObjectNotFound{Bucket: bucket, Object: key}, nil)
}
2015-04-22 20:50:26 -04:00
func (memory *memoryDriver) evictObject(key lru.Key, value interface{}) {
k := key.(string)
memory.totalSize = memory.totalSize - uint64(memory.objectMetadata[k].metadata.Size)
2015-04-22 20:50:26 -04:00
log.Println("evicting:", k)
delete(memory.objectMetadata, k)
}