contentType: use contentDB package from server.

This commit is contained in:
Harshavardhana
2015-12-04 16:28:26 -08:00
parent 3f91446e6e
commit 36e7e42637
13 changed files with 519 additions and 65 deletions
+2 -1
View File
@@ -62,7 +62,8 @@ func putTarget(targetURL string, reader io.ReadSeeker, size int64) *probe.Error
if err != nil {
return err.Trace(targetURL)
}
err = targetClnt.Put(reader, size)
contentType := guessURLContentType(targetURL)
err = targetClnt.Put(reader, size, contentType)
if err != nil {
return err.Trace(targetURL)
}
+2
View File
@@ -25,6 +25,7 @@ import (
"github.com/minio/cli"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/contentdb"
"github.com/minio/pb"
"github.com/olekukonko/ts"
)
@@ -176,6 +177,7 @@ func main() {
probe.SetAppInfo("Release-Tag", mcReleaseTag)
probe.SetAppInfo("Commit", mcShortCommitID)
contentdb.Init() // Load contentdb into memory.
app := registerApp()
app.Before = registerBefore
+1 -1
View File
@@ -37,7 +37,7 @@ type Client interface {
// I/O operations
Get(offset, length int64) (body io.ReadSeeker, err *probe.Error)
Put(data io.ReadSeeker, size int64) *probe.Error
Put(data io.ReadSeeker, size int64, contentType string) *probe.Error
// I/O operations with expiration
ShareDownload(expires time.Duration) (string, *probe.Error)
+5 -3
View File
@@ -57,7 +57,10 @@ func (f *fsClient) GetURL() client.URL {
/// Object operations.
// Put - create a new file.
func (f *fsClient) Put(data io.ReadSeeker, size int64) *probe.Error {
func (f *fsClient) Put(data io.ReadSeeker, size int64, contentType string) *probe.Error {
// ContentType is not handled on purpose.
// For filesystem this is a redundant information.
// Extract dir name.
objectDir, _ := filepath.Split(f.PathURL.Path)
objectPath := f.PathURL.Path
@@ -82,7 +85,6 @@ func (f *fsClient) Put(data io.ReadSeeker, size int64) *probe.Error {
// Write to a temporary file "object.part.mc" before commiting.
objectPartPath := objectPath + partSuffix
if objectDir != "" {
// Create any missing top level directories.
if e := os.MkdirAll(objectDir, 0700); e != nil {
@@ -641,7 +643,7 @@ func (f *fsClient) MakeBucket() *probe.Error {
}
// GetBucketACL - get bucket access.
func (f *fsClient) GetBucketAccess() (acl string, error *probe.Error) {
func (f *fsClient) GetBucketAccess() (acl string, err *probe.Error) {
return "", probe.NewError(client.APINotImplemented{API: "GetBucketAccess", APIType: "filesystem"})
}
+7 -7
View File
@@ -46,14 +46,14 @@ func (s *MySuite) TestList(c *C) {
data := "hello"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
objectPath = filepath.Join(root, "object2")
fsc, err = fs.New(objectPath)
c.Assert(err, IsNil)
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
fsc, err = fs.New(root)
@@ -75,7 +75,7 @@ func (s *MySuite) TestList(c *C) {
fsc, err = fs.New(objectPath)
c.Assert(err, IsNil)
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
fsc, err = fs.New(root)
@@ -179,7 +179,7 @@ func (s *MySuite) TestPut(c *C) {
c.Assert(err, IsNil)
data := "hello"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
}
@@ -194,7 +194,7 @@ func (s *MySuite) TestGet(c *C) {
data := "hello"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
reader, err := fsc.Get(0, 0)
@@ -217,7 +217,7 @@ func (s *MySuite) TestGetRange(c *C) {
data := "hello world"
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
reader, err := fsc.Get(0, 5)
@@ -240,7 +240,7 @@ func (s *MySuite) TestStatObject(c *C) {
data := "hello"
dataLen := len(data)
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)))
err = fsc.Put(bytes.NewReader([]byte(data)), int64(len(data)), "application/octet-stream")
c.Assert(err, IsNil)
content, err := fsc.Stat()
+55 -52
View File
@@ -66,9 +66,9 @@ func New(config *client.Config) (client.Client, *probe.Error) {
}(),
}
s3Conf.SetUserAgent(config.AppName, config.AppVersion, config.AppComments...)
api, err := minio.New(s3Conf)
if err != nil {
return nil, probe.NewError(err)
api, e := minio.New(s3Conf)
if e != nil {
return nil, probe.NewError(e)
}
s3Clnt := &s3Client{
mu: new(sync.Mutex),
@@ -87,15 +87,15 @@ func (c *s3Client) GetURL() client.URL {
// Get - get object.
func (c *s3Client) Get(offset, length int64) (io.ReadSeeker, *probe.Error) {
bucket, object := c.url2BucketAndObject()
reader, err := c.api.GetPartialObject(bucket, object, offset, length)
if err != nil {
errResponse := minio.ToErrorResponse(err)
reader, e := c.api.GetPartialObject(bucket, object, offset, length)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse != nil {
if errResponse.Code == "AccessDenied" {
return nil, probe.NewError(client.PathInsufficientPermission{Path: c.hostURL.String()})
}
}
return nil, probe.NewError(err)
return nil, probe.NewError(e)
}
return reader, nil
}
@@ -107,21 +107,21 @@ func (c *s3Client) Remove(incomplete bool) *probe.Error {
errCh := c.api.RemoveIncompleteUpload(bucket, object)
return probe.NewError(<-errCh)
}
var err error
var e error
if object == "" {
err = c.api.RemoveBucket(bucket)
e = c.api.RemoveBucket(bucket)
} else {
err = c.api.RemoveObject(bucket, object)
e = c.api.RemoveObject(bucket, object)
}
return probe.NewError(err)
return probe.NewError(e)
}
// ShareDownload - get a usable presigned object url to share.
func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
presignedURL, err := c.api.PresignedGetObject(bucket, object, expires)
if err != nil {
return "", probe.NewError(err)
presignedURL, e := c.api.PresignedGetObject(bucket, object, expires)
if e != nil {
return "", probe.NewError(e)
}
return presignedURL, nil
}
@@ -130,39 +130,42 @@ func (c *s3Client) ShareDownload(expires time.Duration) (string, *probe.Error) {
func (c *s3Client) ShareUpload(isRecursive bool, expires time.Duration, contentType string) (map[string]string, *probe.Error) {
bucket, object := c.url2BucketAndObject()
p := minio.NewPostPolicy()
if err := p.SetExpires(time.Now().UTC().Add(expires)); err != nil {
return nil, probe.NewError(err)
if e := p.SetExpires(time.Now().UTC().Add(expires)); e != nil {
return nil, probe.NewError(e)
}
if strings.TrimSpace(contentType) != "" || contentType != "" {
// No need to verify for error here, since we have stripped out spaces.
p.SetContentType(contentType)
}
if err := p.SetBucket(bucket); err != nil {
return nil, probe.NewError(err)
if e := p.SetBucket(bucket); e != nil {
return nil, probe.NewError(e)
}
if isRecursive {
if err := p.SetKeyStartsWith(object); err != nil {
return nil, probe.NewError(err)
if e := p.SetKeyStartsWith(object); e != nil {
return nil, probe.NewError(e)
}
} else {
if err := p.SetKey(object); err != nil {
return nil, probe.NewError(err)
if e := p.SetKey(object); e != nil {
return nil, probe.NewError(e)
}
}
m, err := c.api.PresignedPostPolicy(p)
return m, probe.NewError(err)
m, e := c.api.PresignedPostPolicy(p)
return m, probe.NewError(e)
}
// Put - put object.
func (c *s3Client) Put(data io.ReadSeeker, size int64) *probe.Error {
func (c *s3Client) Put(data io.ReadSeeker, size int64, contentType string) *probe.Error {
// md5 is purposefully ignored since AmazonS3 does not return proper md5sum
// for a multipart upload and there is no need to cross verify,
// invidual parts are properly verified fully in transit and also upon completion
// of the multipart request.
bucket, object := c.url2BucketAndObject()
err := c.api.PutObject(bucket, object, data, size, "application/octet-stream")
if err != nil {
errResponse := minio.ToErrorResponse(err)
if contentType == "" {
contentType = "application/octet-stream"
}
e := c.api.PutObject(bucket, object, data, size, contentType)
if e != nil {
errResponse := minio.ToErrorResponse(e)
if errResponse != nil {
if errResponse.Code == "AccessDenied" {
return probe.NewError(client.PathInsufficientPermission{
@@ -178,7 +181,7 @@ func (c *s3Client) Put(data io.ReadSeeker, size int64) *probe.Error {
return probe.NewError(client.ObjectMissing{})
}
}
return probe.NewError(err)
return probe.NewError(e)
}
return nil
}
@@ -197,15 +200,15 @@ func (c *s3Client) MakeBucket() *probe.Error {
return probe.NewError(errors.New("Bucket name can contain alphabet, '-' and numbers, but first character should be an alphabet"))
}
err := c.api.MakeBucket(bucket, minio.BucketACL("private"))
if err != nil {
return probe.NewError(err)
e := c.api.MakeBucket(bucket, minio.BucketACL("private"))
if e != nil {
return probe.NewError(e)
}
return nil
}
// GetBucketAccess get acl on a bucket.
func (c *s3Client) GetBucketAccess() (acl string, error *probe.Error) {
func (c *s3Client) GetBucketAccess() (acl string, err *probe.Error) {
bucket, object := c.url2BucketAndObject()
if object != "" {
return "", probe.NewError(client.InvalidBucketName{Bucket: filepath.Join(bucket, object)})
@@ -213,9 +216,9 @@ func (c *s3Client) GetBucketAccess() (acl string, error *probe.Error) {
if bucket == "" {
return "", probe.NewError(client.BucketNameEmpty{})
}
bucketACL, err := c.api.GetBucketACL(bucket)
if err != nil {
return "", probe.NewError(err)
bucketACL, e := c.api.GetBucketACL(bucket)
if e != nil {
return "", probe.NewError(e)
}
return bucketACL.String(), nil
}
@@ -229,9 +232,9 @@ func (c *s3Client) SetBucketAccess(acl string) *probe.Error {
if bucket == "" {
return probe.NewError(client.BucketNameEmpty{})
}
err := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
if err != nil {
return probe.NewError(err)
e := c.api.SetBucketACL(bucket, minio.BucketACL(acl))
if e != nil {
return probe.NewError(e)
}
return nil
}
@@ -242,7 +245,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
objectMetadata := new(client.Content)
bucket, object := c.url2BucketAndObject()
switch {
// valid case for '-r s3/'
// valid case for 'ls -r s3/'
case bucket == "" && object == "":
for bucket := range c.api.ListBuckets() {
if bucket.Err != nil {
@@ -254,10 +257,10 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
return &client.Content{URL: *c.hostURL, Type: os.ModeDir}, nil
}
if object != "" {
metadata, err := c.api.StatObject(bucket, object)
if err != nil {
metadata, e := c.api.StatObject(bucket, object)
if e != nil {
c.mu.Unlock()
errResponse := minio.ToErrorResponse(err)
errResponse := minio.ToErrorResponse(e)
if errResponse != nil {
if errResponse.Code == "NoSuchKey" {
// Append "/" to the object name proactively and see if the Listing
@@ -277,7 +280,7 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
return nil, probe.NewError(client.PathNotFound{Path: c.hostURL.Path})
}
}
return nil, probe.NewError(err)
return nil, probe.NewError(e)
}
objectMetadata.URL = *c.hostURL
objectMetadata.Time = metadata.LastModified
@@ -286,10 +289,10 @@ func (c *s3Client) Stat() (*client.Content, *probe.Error) {
c.mu.Unlock()
return objectMetadata, nil
}
err := c.api.BucketExists(bucket)
if err != nil {
e := c.api.BucketExists(bucket)
if e != nil {
c.mu.Unlock()
return nil, probe.NewError(err)
return nil, probe.NewError(e)
}
bucketMetadata := new(client.Content)
bucketMetadata.URL = *c.hostURL
@@ -515,10 +518,10 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
contentCh <- content
}
case b != "" && !strings.HasSuffix(c.hostURL.Path, string(c.hostURL.Separator)) && o == "":
err := c.api.BucketExists(b)
if err != nil {
e := c.api.BucketExists(b)
if e != nil {
contentCh <- &client.Content{
Err: probe.NewError(err),
Err: probe.NewError(e),
}
}
content := new(client.Content)
@@ -526,8 +529,8 @@ func (c *s3Client) listInRoutine(contentCh chan *client.Content) {
content.Type = os.ModeDir
contentCh <- content
default:
metadata, err := c.api.StatObject(b, o)
switch err.(type) {
metadata, e := c.api.StatObject(b, o)
switch e.(type) {
case nil:
content := new(client.Content)
content.URL = *c.hostURL
+1 -1
View File
@@ -184,7 +184,7 @@ func (s *MySuite) TestObjectOperations(c *C) {
s3c, err := New(conf)
c.Assert(err, IsNil)
err = s3c.Put(bytes.NewReader(object.data), int64(len(object.data)))
err = s3c.Put(bytes.NewReader(object.data), int64(len(object.data)), "application/octet-stream")
c.Assert(err, IsNil)
content, err := s3c.Stat()
+14
View File
@@ -18,9 +18,11 @@ package main
import (
"path/filepath"
"strings"
"github.com/minio/mc/pkg/client"
"github.com/minio/minio-xl/pkg/probe"
"github.com/minio/minio/pkg/contentdb"
)
func isURLVirtualHostStyle(hostURL string) bool {
@@ -92,3 +94,15 @@ func isURLPrefixExists(urlPrefix string, incomplete bool) bool {
}
return false
}
// guessURLContentType - guess content-type of the URL.
// on failure just return 'application/octet-stream'.
func guessURLContentType(urlStr string) string {
url := client.NewURL(urlStr)
extension := strings.TrimPrefix(filepath.Ext(url.Path), ".")
contentType, e := contentdb.Lookup(extension)
if e != nil {
return "application/octet-stream"
}
return contentType
}
+26
View File
@@ -0,0 +1,26 @@
# Generate db.go from db.json downloaded nodejs mime-db project.
# NOTE: Autogenerated db.go needs to be vet proofed. \
Manually edit json -> JSON for all variable names
all: checkdeps download build
# go-bindata generates go source from any data file.
checkdeps:
@go get -u github.com/jteeuwen/go-bindata/...
# Download db.json from NodeJS's mime-db project. It is under MIT license.
download: checkdeps
@mkdir db
@wget -nv https://cdn.rawgit.com/jshttp/mime-db/master/db.json -O db/db.json
# After generating db.go, clean up downloaded db.json.
build: download
@go-bindata -pkg contentdb -o db.go db
@rm -fv db/db.json
@rm -rfv db
# Clean auto-generated files and backups.
clean:
@rm -rf db.go
@rm -f *~
+118
View File
@@ -0,0 +1,118 @@
/*
* mime-db: Mime Database, (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 contentdb is a database of file extension to mime content-type.
// Definitions are imported from NodeJS mime-db project under MIT license.
package contentdb
import (
"errors"
"fmt"
"strings"
"sync"
"encoding/json"
)
var (
// Internal lock.
mutex = &sync.Mutex{}
// Make note of initialization.
isInitialized = false
// Database of extension:content-type.
extDB map[string]string
)
// Load JSON data from gobindata and parse them into extDB.
func loadDB() error {
// Structure of JSON data from mime-db project.
type dbEntry struct {
Source string `json:"source"`
Compressible bool `json:"compresible"`
Extensions []string `json:"extensions"`
}
// Access embedded "db.json" inside go-bindata.
jsonDB, e := Asset("db/db.json")
if e != nil {
return e
}
// Convert db.json into go's typed structure.
db := make(map[string]dbEntry)
if e := json.Unmarshal(jsonDB, &db); e != nil {
return e
}
// Generate a new database from mime-db.
for key, val := range db {
if len(val.Extensions) > 0 {
/* Denormalize - each extension has its own
unique content-type now. Looks will be fast. */
for _, ext := range val.Extensions {
/* Single extension type may map to
multiple content-types. In that case,
simply prefer the longest content-type
to maintain some level of
consistency. Only guarantee is,
whatever content type is assigned, it
is appropriate and valid type. */
if strings.Compare(extDB[ext], key) < 0 {
extDB[ext] = key
}
}
}
}
return nil
}
// Init initializes contentdb for lookups. JSON structure is parsed into a simple map of extension and content-type.
func Init() error {
mutex.Lock()
defer mutex.Unlock()
if !isInitialized {
var e error
extDB = make(map[string]string)
if !isInitialized {
e = loadDB()
}
isInitialized = true
return e
}
return nil
}
// Lookup returns matching content-type for known types of file extensions.
func Lookup(extension string) (contentType string, e error) {
if !isInitialized {
return "", errors.New("contentdb is not initialized.")
}
return extDB[extension], e
}
// MustLookup returns matching content-type for known types of file extensions. In case of error, it panics.
func MustLookup(extension string) (contentType string) {
var e error
if contentType, e = Lookup(extension); e != nil {
panic(fmt.Sprintf("Lookup failed: %s\n", e))
}
return contentType
}
+46
View File
@@ -0,0 +1,46 @@
/*
* mime-db: Mime Database, (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 contentdb_test
import (
"testing"
"github.com/minio/minio/pkg/contentdb"
. "gopkg.in/check.v1"
)
func Test(t *testing.T) { TestingT(t) }
type MySuite struct{}
var _ = Suite(&MySuite{})
func (s *MySuite) TestLookup(c *C) {
// Test initializing.
e := contentdb.Init()
c.Assert(e, IsNil)
// Test MustLookup.
contentType, e := contentdb.Lookup("exe")
c.Assert(e, IsNil)
c.Assert(contentType, Not(Equals), "")
// Test MustLookup.
contentType = contentdb.MustLookup("exe")
c.Assert(contentType, Not(Equals), "")
}
File diff suppressed because one or more lines are too long
+5
View File
@@ -47,6 +47,11 @@
"revision": "a32fbc1006b4a09176c91f57d22e87faff22a423",
"revisionTime": "2015-11-17T22:59:41-08:00"
},
{
"path": "github.com/minio/minio/pkg/contentdb",
"revision": "bed528d5696872b03dd32d63599f5b9ed82cb361",
"revisionTime": "2015-12-03T01:11:14-08:00"
},
{
"path": "github.com/minio/pb",
"revision": "6a97c3b0da073f974e0b8d1ac1bc42c0a7adca46",