-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathcache.go
More file actions
91 lines (70 loc) · 1.93 KB
/
cache.go
File metadata and controls
91 lines (70 loc) · 1.93 KB
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
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
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
package main
import (
"fmt"
"github.com/golang/groupcache"
"log"
"net/http"
"strconv"
"strings"
)
var pool *groupcache.HTTPPool
var sizeCache *groupcache.Group
var chunkCache *groupcache.Group
func cacheInit() {
fixedAddr := "http://" + poolAddr
fixedPeers := strings.Split(poolPeers, ",")
for index, peer := range fixedPeers {
fixedPeers[index] = "http://" + peer
}
log.Println("Cache pool peers:", fixedPeers)
log.Println("Cache pool address:", fixedAddr)
fmt.Println()
pool = groupcache.NewHTTPPool(fixedAddr)
pool.Set(fixedPeers...)
sizeCache = groupcache.NewGroup("size-cache", sizeCacheSize, groupcache.GetterFunc(cacheSizeGetter))
chunkCache = groupcache.NewGroup("chunk-cache", chunkCacheSize, groupcache.GetterFunc(cacheChunkGetter))
go http.ListenAndServe(poolAddr, pool)
}
func cacheGetFileSize(file string) (int64, error) {
var size string
err := sizeCache.Get(nil, file, groupcache.StringSink(&size))
if err != nil {
return -1, err
}
return strconv.ParseInt(size, 16, 64)
}
func cacheGetFileChunk(file string, chunk int64) (groupcache.ByteView, error) {
var key = fmt.Sprintf("%s#%d", file, chunk)
var view = groupcache.ByteView{}
err := chunkCache.Get(nil, key, groupcache.ByteViewSink(&view))
if err != nil {
return view, err
}
return view, nil
}
func cacheUpdatePeerList(peerList []string) {
pool.Set(peerList...)
}
func cacheSizeGetter(ctx groupcache.Context, key string, dest groupcache.Sink) error {
size, err := backendGetFileSize(key)
if err != nil {
return err
}
dest.SetString(strconv.FormatInt(size, 16))
return nil
}
func cacheChunkGetter(ctx groupcache.Context, key string, dest groupcache.Sink) error {
sep := strings.LastIndex(key, "#")
file := key[:sep]
chunk := key[sep+1:]
chunkNum, err := strconv.ParseInt(chunk, 10, 64)
if err != nil {
return err
}
chunkData, err := diskGetFileChunk(file, chunkNum)
if err != nil {
return err
}
dest.SetBytes(chunkData)
return nil
}