file.go 6.7 KB
Newer Older
M
Ming Deng 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
// Copyright 2014 beego Author. All Rights Reserved.
//
// 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 cache

import (
	"bytes"
	"crypto/md5"
	"encoding/gob"
	"encoding/hex"
	"encoding/json"
	"fmt"
	"io"
	"io/ioutil"
	"os"
	"path/filepath"
	"reflect"
	"strconv"
	"time"
)

I
IamCathal 已提交
33 34
// FileCacheItem is basic unit of file cache adapter which
// contains data and expire time.
M
Ming Deng 已提交
35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56
type FileCacheItem struct {
	Data       interface{}
	Lastaccess time.Time
	Expired    time.Time
}

// FileCache Config
var (
	FileCachePath           = "cache"     // cache directory
	FileCacheFileSuffix     = ".bin"      // cache file suffix
	FileCacheDirectoryLevel = 2           // cache file deep level if auto generated cache files.
	FileCacheEmbedExpiry    time.Duration // cache expire time, default is no expire forever.
)

// FileCache is cache adapter for file storage.
type FileCache struct {
	CachePath      string
	FileSuffix     string
	DirectoryLevel int
	EmbedExpiry    int
}

I
IamCathal 已提交
57
// NewFileCache creates a new file cache with no config.
I
IamCathal 已提交
58
// The level and expiry need to be set in the method StartAndGC as config string.
M
Ming Deng 已提交
59 60 61 62 63
func NewFileCache() Cache {
	//    return &FileCache{CachePath:FileCachePath, FileSuffix:FileCacheFileSuffix}
	return &FileCache{}
}

I
IamCathal 已提交
64 65
// StartAndGC starts gc for file cache.
// config must be in the format {CachePath:"/cache","FileSuffix":".bin","DirectoryLevel":"2","EmbedExpiry":"0"}
M
Ming Deng 已提交
66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93
func (fc *FileCache) StartAndGC(config string) error {

	cfg := make(map[string]string)
	err := json.Unmarshal([]byte(config), &cfg)
	if err != nil {
		return err
	}
	if _, ok := cfg["CachePath"]; !ok {
		cfg["CachePath"] = FileCachePath
	}
	if _, ok := cfg["FileSuffix"]; !ok {
		cfg["FileSuffix"] = FileCacheFileSuffix
	}
	if _, ok := cfg["DirectoryLevel"]; !ok {
		cfg["DirectoryLevel"] = strconv.Itoa(FileCacheDirectoryLevel)
	}
	if _, ok := cfg["EmbedExpiry"]; !ok {
		cfg["EmbedExpiry"] = strconv.FormatInt(int64(FileCacheEmbedExpiry.Seconds()), 10)
	}
	fc.CachePath = cfg["CachePath"]
	fc.FileSuffix = cfg["FileSuffix"]
	fc.DirectoryLevel, _ = strconv.Atoi(cfg["DirectoryLevel"])
	fc.EmbedExpiry, _ = strconv.Atoi(cfg["EmbedExpiry"])

	fc.Init()
	return nil
}

I
IamCathal 已提交
94
// Init makes new a dir for file cache if it does not already exist
M
Ming Deng 已提交
95 96 97 98 99 100
func (fc *FileCache) Init() {
	if ok, _ := exists(fc.CachePath); !ok { // todo : error handle
		_ = os.MkdirAll(fc.CachePath, os.ModePerm) // todo : error handle
	}
}

I
IamCathal 已提交
101
// getCachedFilename returns an md5 encoded file name.
M
Ming Deng 已提交
102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
func (fc *FileCache) getCacheFileName(key string) string {
	m := md5.New()
	io.WriteString(m, key)
	keyMd5 := hex.EncodeToString(m.Sum(nil))
	cachePath := fc.CachePath
	switch fc.DirectoryLevel {
	case 2:
		cachePath = filepath.Join(cachePath, keyMd5[0:2], keyMd5[2:4])
	case 1:
		cachePath = filepath.Join(cachePath, keyMd5[0:2])
	}

	if ok, _ := exists(cachePath); !ok { // todo : error handle
		_ = os.MkdirAll(cachePath, os.ModePerm) // todo : error handle
	}

	return filepath.Join(cachePath, fmt.Sprintf("%s%s", keyMd5, fc.FileSuffix))
}

// Get value from file cache.
I
IamCathal 已提交
122
// if nonexistent or expired return an empty string.
M
Ming Deng 已提交
123 124 125 126 127 128 129 130 131 132 133 134 135 136
func (fc *FileCache) Get(key string) interface{} {
	fileData, err := FileGetContents(fc.getCacheFileName(key))
	if err != nil {
		return ""
	}
	var to FileCacheItem
	GobDecode(fileData, &to)
	if to.Expired.Before(time.Now()) {
		return ""
	}
	return to.Data
}

// GetMulti gets values from file cache.
I
IamCathal 已提交
137
// if nonexistent or expired return an empty string.
M
Ming Deng 已提交
138 139 140 141 142 143 144 145 146
func (fc *FileCache) GetMulti(keys []string) []interface{} {
	var rc []interface{}
	for _, key := range keys {
		rc = append(rc, fc.Get(key))
	}
	return rc
}

// Put value into file cache.
I
IamCathal 已提交
147
// timeout: how long this file should be kept in ms
M
Ming Deng 已提交
148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174
// if timeout equals fc.EmbedExpiry(default is 0), cache this item forever.
func (fc *FileCache) Put(key string, val interface{}, timeout time.Duration) error {
	gob.Register(val)

	item := FileCacheItem{Data: val}
	if timeout == time.Duration(fc.EmbedExpiry) {
		item.Expired = time.Now().Add((86400 * 365 * 10) * time.Second) // ten years
	} else {
		item.Expired = time.Now().Add(timeout)
	}
	item.Lastaccess = time.Now()
	data, err := GobEncode(item)
	if err != nil {
		return err
	}
	return FilePutContents(fc.getCacheFileName(key), data)
}

// Delete file cache value.
func (fc *FileCache) Delete(key string) error {
	filename := fc.getCacheFileName(key)
	if ok, _ := exists(filename); ok {
		return os.Remove(filename)
	}
	return nil
}

I
IamCathal 已提交
175 176
// Incr increases cached int value.
// fc value is saved forever unless deleted.
M
Ming Deng 已提交
177 178 179 180 181 182 183 184 185 186 187 188
func (fc *FileCache) Incr(key string) error {
	data := fc.Get(key)
	var incr int
	if reflect.TypeOf(data).Name() != "int" {
		incr = 0
	} else {
		incr = data.(int) + 1
	}
	fc.Put(key, incr, time.Duration(fc.EmbedExpiry))
	return nil
}

I
IamCathal 已提交
189
// Decr decreases cached int value.
M
Ming Deng 已提交
190 191 192 193 194 195 196 197 198 199 200 201
func (fc *FileCache) Decr(key string) error {
	data := fc.Get(key)
	var decr int
	if reflect.TypeOf(data).Name() != "int" || data.(int)-1 <= 0 {
		decr = 0
	} else {
		decr = data.(int) - 1
	}
	fc.Put(key, decr, time.Duration(fc.EmbedExpiry))
	return nil
}

I
IamCathal 已提交
202
// IsExist checks if value exists.
M
Ming Deng 已提交
203 204 205 206 207
func (fc *FileCache) IsExist(key string) bool {
	ret, _ := exists(fc.getCacheFileName(key))
	return ret
}

I
IamCathal 已提交
208
// ClearAll cleans cached files (not implemented)
M
Ming Deng 已提交
209 210 211 212
func (fc *FileCache) ClearAll() error {
	return nil
}

I
IamCathal 已提交
213
// Check if a file exists
M
Ming Deng 已提交
214 215 216 217 218 219 220 221 222 223 224
func exists(path string) (bool, error) {
	_, err := os.Stat(path)
	if err == nil {
		return true, nil
	}
	if os.IsNotExist(err) {
		return false, nil
	}
	return false, err
}

I
IamCathal 已提交
225 226
// FileGetContents Reads bytes from a file.
// if non-existent, create this file.
M
Ming Deng 已提交
227 228 229 230
func FileGetContents(filename string) (data []byte, e error) {
	return ioutil.ReadFile(filename)
}

I
IamCathal 已提交
231 232
// FilePutContents puts bytes into a file.
// if non-existent, create this file.
M
Ming Deng 已提交
233 234 235 236
func FilePutContents(filename string, content []byte) error {
	return ioutil.WriteFile(filename, content, os.ModePerm)
}

I
IamCathal 已提交
237
// GobEncode Gob encodes a file cache item.
M
Ming Deng 已提交
238 239 240 241 242 243 244 245 246 247
func GobEncode(data interface{}) ([]byte, error) {
	buf := bytes.NewBuffer(nil)
	enc := gob.NewEncoder(buf)
	err := enc.Encode(data)
	if err != nil {
		return nil, err
	}
	return buf.Bytes(), err
}

I
IamCathal 已提交
248
// GobDecode Gob decodes a file cache item.
M
Ming Deng 已提交
249 250 251 252 253 254 255 256 257
func GobDecode(data []byte, to *FileCacheItem) error {
	buf := bytes.NewBuffer(data)
	dec := gob.NewDecoder(buf)
	return dec.Decode(&to)
}

func init() {
	Register("file", NewFileCache)
}