mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-11-25 21:57:05 +01:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
83efe1547d | ||
|
|
48919009fc | ||
|
|
f66fef0ec5 | ||
|
|
478fe0ecf2 | ||
|
|
7ecc0f4b11 | ||
|
|
021ef0d14b | ||
|
|
e3fc676260 | ||
|
|
82c3ccc8dd | ||
|
|
80cefade65 | ||
|
|
bd97cbc523 | ||
|
|
c5f23b26fc | ||
|
|
a7faefd4ce | ||
|
|
b3513d3167 | ||
|
|
4ce6586710 | ||
|
|
68e2dee2cd | ||
|
|
366fe0d394 | ||
|
|
9fcff1bd9a | ||
|
|
7ab9160ee1 | ||
|
|
a337b844ec | ||
|
|
e936fe9001 | ||
|
|
c46e91d229 | ||
|
|
37b79174d1 | ||
|
|
b095496d30 | ||
|
|
14ec3bfc1d | ||
|
|
427c7fbf93 | ||
|
|
a72c92e55f | ||
|
|
3a67b6ddc1 | ||
|
|
7f85e15990 | ||
|
|
b20cdff82d | ||
|
|
813a4f7456 | ||
|
|
470d950918 | ||
|
|
4049c72e6c | ||
|
|
30f138a538 | ||
|
|
41f686ab9d | ||
|
|
98d66a569b | ||
|
|
654173e7c7 | ||
|
|
543476cba1 | ||
|
|
9a8e020559 | ||
|
|
f0d140f164 | ||
|
|
ee6067e98c | ||
|
|
c2ce97785f | ||
|
|
f302c9fda2 | ||
|
|
3cb0071025 | ||
|
|
043b7a7c65 | ||
|
|
bfd2739fce | ||
|
|
0656838fe5 | ||
|
|
4fb5bb09b6 | ||
|
|
e074a54a20 | ||
|
|
492f93416d | ||
|
|
18b3afc97a | ||
|
|
0c898df430 | ||
|
|
c8f54aad8b | ||
|
|
8de0027df5 | ||
|
|
5b0f5f456e | ||
|
|
59022b6fe0 | ||
|
|
8b15523c9d | ||
|
|
e05cc109a6 | ||
|
|
a55ae8ad52 | ||
|
|
76da296799 | ||
|
|
3065506b38 | ||
|
|
d953ed442c | ||
|
|
1be354bdce | ||
|
|
adc8d344a5 | ||
|
|
e767c3ea4f | ||
|
|
e46c3415f7 | ||
|
|
4beaaa0650 | ||
|
|
9fa648e570 | ||
|
|
66e7013dfe | ||
|
|
07a51815e9 | ||
|
|
90a6f43c56 | ||
|
|
53cf1b4900 | ||
|
|
ed44f12f6d | ||
|
|
7b6837cbc2 | ||
|
|
b14332df96 | ||
|
|
da9b672d1b | ||
|
|
86a7c56275 | ||
|
|
13e7069eb9 | ||
|
|
54dd925283 | ||
|
|
80398a2a3a | ||
|
|
4f28876c8d | ||
|
|
e61c9af523 | ||
|
|
4d1ac7332e | ||
|
|
e2100d0626 | ||
|
|
47b6ce93f8 | ||
|
|
0d8cf87a8c | ||
|
|
f9c20aff9d | ||
|
|
83ce8c30fc | ||
|
|
19159ec479 | ||
|
|
9cb034d49e | ||
|
|
d1562e48e1 |
No files matched your search
+16
-2
@@ -1,8 +1,8 @@
|
||||
sudo: false
|
||||
language: go
|
||||
go:
|
||||
- 1.5
|
||||
- 1.6
|
||||
- 1.7
|
||||
- 1.8.3
|
||||
- tip
|
||||
|
||||
before_install:
|
||||
@@ -14,8 +14,11 @@ install:
|
||||
script:
|
||||
- go test ./weed/...
|
||||
|
||||
before_deploy:
|
||||
- make release
|
||||
deploy:
|
||||
provider: releases
|
||||
skip_cleanup: true
|
||||
api_key:
|
||||
secure: ERL986+ncQ8lwAJUYDrQ8s2/FxF/cyNIwJIFCqspnWxQgGNNyokET9HapmlPSxjpFRF0q6L2WCg9OY3mSVRq4oI6hg1igOQ12KlLyN71XSJ3c8w0Ay5ho48TQ9l3f3Iu97mntBCe9l0R9pnT8wj1VI8YJxloXwUMG2yeTjA9aBI=
|
||||
file:
|
||||
@@ -26,5 +29,16 @@ deploy:
|
||||
- build/darwin_amd64.tar.gz
|
||||
- build/windows_386.zip
|
||||
- build/windows_amd64.zip
|
||||
- build/freebsd_arm.tar.gz
|
||||
- build/freebsd_amd64.tar.gz
|
||||
- build/freebsd_386.tar.gz
|
||||
- build/netbsd_arm.tar.gz
|
||||
- build/netbsd_amd64.tar.gz
|
||||
- build/netbsd_386.tar.gz
|
||||
- build/openbsd_arm.tar.gz
|
||||
- build/openbsd_amd64.tar.gz
|
||||
- build/openbsd_386.tar.gz
|
||||
on:
|
||||
tags: true
|
||||
repo: chrislusf/seaweedfs
|
||||
go: tip
|
||||
@@ -15,7 +15,7 @@ zip = cd build && zip $(1)_$(2).zip $(appname)$(3) && rm $(appname)$(3)
|
||||
|
||||
all: build
|
||||
|
||||
.PHONY : clean deps build linux release windows_build darwin_build linux_build clean
|
||||
.PHONY : clean deps build linux release windows_build darwin_build linux_build bsd_build clean
|
||||
|
||||
clean:
|
||||
go clean -i $(GO_FLAGS) $(SOURCE_DIR)
|
||||
@@ -32,7 +32,7 @@ linux: deps
|
||||
mkdir -p linux
|
||||
GOOS=linux GOARCH=amd64 go build $(GO_FLAGS) -o linux/$(BINARY) $(SOURCE_DIR)
|
||||
|
||||
release: windows_build darwin_build linux_build
|
||||
release: deps windows_build darwin_build linux_build bsd_build
|
||||
|
||||
##### LINUX BUILDS #####
|
||||
linux_build: build/linux_arm.tar.gz build/linux_arm64.tar.gz build/linux_386.tar.gz build/linux_amd64.tar.gz
|
||||
@@ -69,4 +69,45 @@ build/windows_386.zip: $(sources)
|
||||
|
||||
build/windows_amd64.zip: $(sources)
|
||||
$(call build,windows,amd64,.exe)
|
||||
$(call zip,windows,amd64,.exe)
|
||||
$(call zip,windows,amd64,.exe)
|
||||
|
||||
##### BSD BUILDS #####
|
||||
bsd_build: build/freebsd_arm.tar.gz build/freebsd_386.tar.gz build/freebsd_amd64.tar.gz \
|
||||
build/netbsd_arm.tar.gz build/netbsd_386.tar.gz build/netbsd_amd64.tar.gz \
|
||||
build/openbsd_arm.tar.gz build/openbsd_386.tar.gz build/openbsd_amd64.tar.gz
|
||||
|
||||
build/freebsd_386.tar.gz: $(sources)
|
||||
$(call build,freebsd,386,)
|
||||
$(call tar,freebsd,386)
|
||||
|
||||
build/freebsd_amd64.tar.gz: $(sources)
|
||||
$(call build,freebsd,amd64,)
|
||||
$(call tar,freebsd,amd64)
|
||||
|
||||
build/freebsd_arm.tar.gz: $(sources)
|
||||
$(call build,freebsd,arm,)
|
||||
$(call tar,freebsd,arm)
|
||||
|
||||
build/netbsd_386.tar.gz: $(sources)
|
||||
$(call build,netbsd,386,)
|
||||
$(call tar,netbsd,386)
|
||||
|
||||
build/netbsd_amd64.tar.gz: $(sources)
|
||||
$(call build,netbsd,amd64,)
|
||||
$(call tar,netbsd,amd64)
|
||||
|
||||
build/netbsd_arm.tar.gz: $(sources)
|
||||
$(call build,netbsd,arm,)
|
||||
$(call tar,netbsd,arm)
|
||||
|
||||
build/openbsd_386.tar.gz: $(sources)
|
||||
$(call build,openbsd,386,)
|
||||
$(call tar,openbsd,386)
|
||||
|
||||
build/openbsd_amd64.tar.gz: $(sources)
|
||||
$(call build,openbsd,amd64,)
|
||||
$(call tar,openbsd,amd64)
|
||||
|
||||
build/openbsd_arm.tar.gz: $(sources)
|
||||
$(call build,openbsd,arm,)
|
||||
$(call tar,openbsd,arm)
|
||||
@@ -3,11 +3,16 @@
|
||||
[](https://travis-ci.org/chrislusf/seaweedfs)
|
||||
[](https://godoc.org/github.com/chrislusf/seaweedfs/weed)
|
||||
[](https://github.com/chrislusf/seaweedfs/wiki)
|
||||
[](https://bintray.com/chrislusf/seaweedfs/seaweedfs)
|
||||
|
||||

|
||||
|
||||
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EEECLJ8QGTTPC)
|
||||
|
||||
- [Download Binaries for different platforms](https://github.com/chrislusf/seaweedfs/releases/latest)
|
||||
- [SeaweedFS Mailing List](https://groups.google.com/d/forum/seaweedfs)
|
||||
- [Wiki Documentation](https://github.com/chrislusf/seaweedfs/wiki)
|
||||
|
||||
|
||||
[](https://www.paypal.com/cgi-bin/webscr?cmd=_s-xclick&hosted_button_id=EEECLJ8QGTTPC)
|
||||
|
||||
## Introduction
|
||||
|
||||
@@ -24,11 +29,6 @@ There is only a 40 bytes disk storage overhead for each file's metadata. It is s
|
||||
|
||||
SeaweedFS started by implementing [Facebook's Haystack design paper](http://www.usenix.org/event/osdi10/tech/full_papers/Beaver.pdf). SeaweedFS is currently growing, with more features on the way.
|
||||
|
||||
Download latest compiled binaries for different platforms here:
|
||||
[](https://bintray.com/chrislusf/seaweedfs/seaweedfs)
|
||||
|
||||
[SeaweedFS Discussion Group](https://groups.google.com/d/forum/seaweedfs)
|
||||
|
||||
## Additional Features
|
||||
* Can choose no replication or different replication level, rack and data center aware
|
||||
* Automatic master servers failover - no single point of failure (SPOF)
|
||||
@@ -39,7 +39,7 @@ Download latest compiled binaries for different platforms here:
|
||||
* Optional [filer server][Filer] provides "normal" directories and files via http
|
||||
* Optionally fix the orientation for jpeg pictures
|
||||
* Support Etag, Accept-Range, Last-Modified, etc.
|
||||
* Support in-memory/leveldb/boltdb mode tuning for memory/performance balance.
|
||||
* Support in-memory/leveldb/boltdb/btree mode tuning for memory/performance balance.
|
||||
|
||||
[Filer]: https://github.com/chrislusf/seaweedfs/wiki/Filer
|
||||
|
||||
@@ -135,6 +135,8 @@ If you want get a scaled version of an image, you can add some params:
|
||||
|
||||
```
|
||||
http://localhost:8080/3/01637037d6.jpg?height=200&width=200
|
||||
http://localhost:8080/3/01637037d6.jpg?height=200&width=200&mode=fit
|
||||
http://localhost:8080/3/01637037d6.jpg?height=200&width=200&mode=fill
|
||||
```
|
||||
|
||||
### Rack-Aware and Data Center-Aware Replication ###
|
||||
@@ -171,8 +173,6 @@ Volume servers can start with a specific data center name:
|
||||
weed volume -dir=/tmp/2 -port=8081 -dataCenter=dc2
|
||||
```
|
||||
|
||||
Or the master server can determine the data center via volume server's IP address and settings in weed.conf file.
|
||||
|
||||
When requesting a file key, an optional "dataCenter" parameter can limit the assigned volume to the specific data center. For example, this specifies that the assigned volume should be limited to 'dc1':
|
||||
|
||||
```
|
||||
|
||||
+6
-7
@@ -1,11 +1,10 @@
|
||||
FROM progrium/busybox
|
||||
FROM frolvlad/alpine-glibc:alpine-3.5
|
||||
|
||||
RUN opkg-install curl
|
||||
RUN echo tlsv1 >> ~/.curlrc
|
||||
|
||||
RUN curl -Lks https://bintray.com$(curl -Lk http://bintray.com/chrislusf/seaweedfs/seaweedfs/_latestVersion | grep linux_amd64.tar.gz | sed -n "/href/ s/.*href=['\"]\([^'\"]*\)['\"].*/\1/gp") | gunzip | tar -xf - && \
|
||||
mv go_*amd64/weed /usr/bin/ && \
|
||||
rm -r go_*amd64
|
||||
RUN apk add --no-cache --virtual=build-dependencies --update curl wget ca-certificates && \
|
||||
wget -P /tmp https://github.com/$(curl -s -L https://github.com/chrislusf/seaweedfs/releases/latest | egrep -o '/chrislusf/seaweedfs/releases/download/.*/linux_amd64.tar.gz') && \
|
||||
tar -C /usr/bin/ -xzvf /tmp/linux_amd64.tar.gz && \
|
||||
apk del curl wget ca-certificates build-dependencies && \
|
||||
rm -rf /tmp/*
|
||||
|
||||
EXPOSE 8080
|
||||
EXPOSE 9333
|
||||
|
||||
@@ -60,7 +60,7 @@ func main() {
|
||||
|
||||
iterateEntries(datFile, indexFile, func(n *storage.Needle, offset int64) {
|
||||
fmt.Printf("file id=%d name=%s size=%d dataSize=%d\n", n.Id, string(n.Name), n.Size, n.DataSize)
|
||||
s, e := n.Append(newDatFile, storage.Version2)
|
||||
s, _, e := n.Append(newDatFile, storage.Version2)
|
||||
fmt.Printf("size %d error %v\n", s, e)
|
||||
})
|
||||
|
||||
|
||||
@@ -75,7 +75,7 @@ func runBackup(cmd *Command, args []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
v, err := storage.NewVolume(*s.dir, *s.collection, vid, storage.NeedleMapInMemory, replication, ttl)
|
||||
v, err := storage.NewVolume(*s.dir, *s.collection, vid, storage.NeedleMapInMemory, replication, ttl, 0)
|
||||
if err != nil {
|
||||
fmt.Printf("Error creating or reading from volume %d: %v\n", vid, err)
|
||||
return true
|
||||
|
||||
@@ -201,9 +201,11 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
}()
|
||||
}
|
||||
|
||||
random := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
for id := range idChan {
|
||||
start := time.Now()
|
||||
fileSize := int64(*b.fileSize + rand.Intn(64))
|
||||
fileSize := int64(*b.fileSize + random.Intn(64))
|
||||
fp := &operation.FilePart{Reader: &FakeReader{id: uint64(id), size: fileSize}, FileSize: fileSize}
|
||||
ar := &operation.VolumeAssignRequest{
|
||||
Count: 1,
|
||||
@@ -212,7 +214,7 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
if assignResult, err := operation.Assign(*b.server, ar); err == nil {
|
||||
fp.Server, fp.Fid, fp.Collection = assignResult.Url, assignResult.Fid, *b.collection
|
||||
if _, err := fp.Upload(0, *b.server, secret); err == nil {
|
||||
if rand.Intn(100) < *b.deletePercentage {
|
||||
if random.Intn(100) < *b.deletePercentage {
|
||||
s.total++
|
||||
delayedDeleteChan <- &delayedFile{time.Now().Add(time.Second), fp}
|
||||
} else {
|
||||
@@ -239,6 +241,8 @@ func writeFiles(idChan chan int, fileIdLineChan chan string, s *stat) {
|
||||
|
||||
func readFiles(fileIdLineChan chan string, s *stat) {
|
||||
defer wait.Done()
|
||||
random := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
for fid := range fileIdLineChan {
|
||||
if len(fid) == 0 {
|
||||
continue
|
||||
@@ -258,7 +262,7 @@ func readFiles(fileIdLineChan chan string, s *stat) {
|
||||
println("!!!! volume id ", vid, " location not found!!!!!")
|
||||
continue
|
||||
}
|
||||
server := ret.Locations[rand.Intn(len(ret.Locations))].Url
|
||||
server := ret.Locations[random.Intn(len(ret.Locations))].Url
|
||||
url := "http://" + server + "/" + fid
|
||||
if bytesRead, err := util.Get(url); err == nil {
|
||||
s.completed++
|
||||
@@ -297,6 +301,8 @@ func readFileIds(fileName string, fileIdLineChan chan string) {
|
||||
}
|
||||
defer file.Close()
|
||||
|
||||
random := rand.New(rand.NewSource(time.Now().UnixNano()))
|
||||
|
||||
r := bufio.NewReader(file)
|
||||
if *b.sequentialRead {
|
||||
for {
|
||||
@@ -317,7 +323,7 @@ func readFileIds(fileName string, fileIdLineChan chan string) {
|
||||
}
|
||||
if len(lines) > 0 {
|
||||
for i := 0; i < readStats.total; i++ {
|
||||
fileIdLineChan <- lines[rand.Intn(len(lines))]
|
||||
fileIdLineChan <- lines[random.Intn(len(lines))]
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -20,10 +20,11 @@ var cmdCompact = &Command{
|
||||
}
|
||||
|
||||
var (
|
||||
compactVolumePath = cmdCompact.Flag.String("dir", ".", "data directory to store files")
|
||||
compactVolumeCollection = cmdCompact.Flag.String("collection", "", "volume collection name")
|
||||
compactVolumeId = cmdCompact.Flag.Int("volumeId", -1, "a volume id. The volume should already exist in the dir.")
|
||||
compactMethod = cmdCompact.Flag.Int("method", 0, "option to choose which compact method. use 0 or 1.")
|
||||
compactVolumePath = cmdCompact.Flag.String("dir", ".", "data directory to store files")
|
||||
compactVolumeCollection = cmdCompact.Flag.String("collection", "", "volume collection name")
|
||||
compactVolumeId = cmdCompact.Flag.Int("volumeId", -1, "a volume id. The volume should already exist in the dir.")
|
||||
compactMethod = cmdCompact.Flag.Int("method", 0, "option to choose which compact method. use 0 or 1.")
|
||||
compactVolumePreallocate = cmdCompact.Flag.Int64("preallocateMB", 0, "preallocate volume disk space")
|
||||
)
|
||||
|
||||
func runCompact(cmd *Command, args []string) bool {
|
||||
@@ -34,7 +35,7 @@ func runCompact(cmd *Command, args []string) bool {
|
||||
|
||||
vid := storage.VolumeId(*compactVolumeId)
|
||||
v, err := storage.NewVolume(*compactVolumePath, *compactVolumeCollection, vid,
|
||||
storage.NeedleMapInMemory, nil, nil)
|
||||
storage.NeedleMapInMemory, nil, nil, *compactVolumePreallocate*(1<<20))
|
||||
if err != nil {
|
||||
glog.Fatalf("Load Volume [ERROR] %s\n", err)
|
||||
}
|
||||
|
||||
@@ -118,7 +118,7 @@ func runExport(cmd *Command, args []string) bool {
|
||||
}
|
||||
defer indexFile.Close()
|
||||
|
||||
needleMap, err := storage.LoadNeedleMap(indexFile)
|
||||
needleMap, err := storage.LoadBtreeNeedleMap(indexFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("cannot load needle map from %s: %s", indexFile.Name(), err)
|
||||
}
|
||||
|
||||
+42
-12
@@ -19,6 +19,7 @@ type FilerOptions struct {
|
||||
master *string
|
||||
ip *string
|
||||
port *int
|
||||
publicPort *int
|
||||
collection *string
|
||||
defaultReplicaPlacement *string
|
||||
dir *string
|
||||
@@ -40,6 +41,7 @@ func init() {
|
||||
f.collection = cmdFiler.Flag.String("collection", "", "all data will be stored in this collection")
|
||||
f.ip = cmdFiler.Flag.String("ip", "", "filer server http listen ip address")
|
||||
f.port = cmdFiler.Flag.Int("port", 8888, "filer server http listen port")
|
||||
f.publicPort = cmdFiler.Flag.Int("port.public", 0, "port opened to public")
|
||||
f.dir = cmdFiler.Flag.String("dir", os.TempDir(), "directory to store meta data")
|
||||
f.defaultReplicaPlacement = cmdFiler.Flag.String("defaultReplicaPlacement", "000", "default replication type if not specified")
|
||||
f.redirectOnRead = cmdFiler.Flag.Bool("redirectOnRead", false, "whether proxy or redirect to volume server during file GET request")
|
||||
@@ -83,29 +85,57 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
glog.Fatalf("Check Meta Folder (-dir) Writable %s : %s", *f.dir, err)
|
||||
}
|
||||
|
||||
r := http.NewServeMux()
|
||||
_, nfs_err := weed_server.NewFilerServer(r, *f.ip, *f.port, *f.master, *f.dir, *f.collection,
|
||||
*f.defaultReplicaPlacement, *f.redirectOnRead, *f.disableDirListing,
|
||||
*f.confFile,
|
||||
*f.maxMB,
|
||||
*f.secretKey,
|
||||
*f.cassandra_server, *f.cassandra_keyspace,
|
||||
*f.redis_server, *f.redis_password, *f.redis_database,
|
||||
f.start()
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
func (fo *FilerOptions) start() {
|
||||
|
||||
defaultMux := http.NewServeMux()
|
||||
publicVolumeMux := defaultMux
|
||||
|
||||
if *fo.publicPort != 0 {
|
||||
publicVolumeMux = http.NewServeMux()
|
||||
}
|
||||
|
||||
_, nfs_err := weed_server.NewFilerServer(defaultMux, publicVolumeMux,
|
||||
*fo.ip, *fo.port, *fo.master, *fo.dir, *fo.collection,
|
||||
*fo.defaultReplicaPlacement, *fo.redirectOnRead, *fo.disableDirListing,
|
||||
*fo.confFile,
|
||||
*fo.maxMB,
|
||||
*fo.secretKey,
|
||||
*fo.cassandra_server, *fo.cassandra_keyspace,
|
||||
*fo.redis_server, *fo.redis_password, *fo.redis_database,
|
||||
)
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
}
|
||||
glog.V(0).Infoln("Start Seaweed Filer", util.VERSION, "at port", strconv.Itoa(*f.port))
|
||||
|
||||
if *fo.publicPort != 0 {
|
||||
publicListeningAddress := *fo.ip + ":" + strconv.Itoa(*fo.publicPort)
|
||||
glog.V(0).Infoln("Start Seaweed filer server", util.VERSION, "public at", publicListeningAddress)
|
||||
publicListener, e := util.NewListener(publicListeningAddress, 0)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer server public listener error on port %d:%v", *fo.publicPort, e)
|
||||
}
|
||||
go func() {
|
||||
if e := http.Serve(publicListener, publicVolumeMux); e != nil {
|
||||
glog.Fatalf("Volume server fail to serve public: %v", e)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
glog.V(0).Infoln("Start Seaweed Filer", util.VERSION, "at port", strconv.Itoa(*fo.port))
|
||||
filerListener, e := util.NewListener(
|
||||
":"+strconv.Itoa(*f.port),
|
||||
":"+strconv.Itoa(*fo.port),
|
||||
time.Duration(10)*time.Second,
|
||||
)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer listener error: %v", e)
|
||||
}
|
||||
if e := http.Serve(filerListener, r); e != nil {
|
||||
if e := http.Serve(filerListener, defaultMux); e != nil {
|
||||
glog.Fatalf("Filer Fail to serve: %v", e)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -126,7 +126,7 @@ func doEachCopy(fileOrDir string, host string, path string) bool {
|
||||
}
|
||||
|
||||
results, err := operation.SubmitFiles(*copy.master, parts,
|
||||
*copy.replication, *copy.collection,
|
||||
*copy.replication, *copy.collection, "",
|
||||
*copy.ttl, *copy.maxMB, copy.secret)
|
||||
if err != nil {
|
||||
fmt.Printf("Failed to submit file %s: %v", fileOrDir, err)
|
||||
|
||||
+2
-2
@@ -43,7 +43,7 @@ func runFix(cmd *Command, args []string) bool {
|
||||
}
|
||||
defer indexFile.Close()
|
||||
|
||||
nm := storage.NewNeedleMap(indexFile)
|
||||
nm := storage.NewBtreeNeedleMap(indexFile)
|
||||
defer nm.Close()
|
||||
|
||||
vid := storage.VolumeId(*fixVolumeId)
|
||||
@@ -58,7 +58,7 @@ func runFix(cmd *Command, args []string) bool {
|
||||
glog.V(2).Infof("saved %d with error %v", n.Size, pe)
|
||||
} else {
|
||||
glog.V(2).Infof("skipping deleted file ...")
|
||||
return nm.Delete(n.Id)
|
||||
return nm.Delete(n.Id, uint32(offset/storage.NeedlePaddingSize))
|
||||
}
|
||||
return nil
|
||||
})
|
||||
|
||||
+33
-11
@@ -10,9 +10,13 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/pb"
|
||||
"github.com/chrislusf/seaweedfs/weed/server"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/soheilhy/cmux"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
)
|
||||
|
||||
func init() {
|
||||
@@ -35,15 +39,15 @@ var (
|
||||
metaFolder = cmdMaster.Flag.String("mdir", os.TempDir(), "data directory to store meta data")
|
||||
masterPeers = cmdMaster.Flag.String("peers", "", "other master nodes in comma separated ip:port list, example: 127.0.0.1:9093,127.0.0.1:9094")
|
||||
volumeSizeLimitMB = cmdMaster.Flag.Uint("volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
|
||||
volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
mpulse = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
|
||||
confFile = cmdMaster.Flag.String("conf", "/etc/weedfs/weedfs.conf", "Deprecating! xml configuration file")
|
||||
defaultReplicaPlacement = cmdMaster.Flag.String("defaultReplication", "000", "Default replication type if not specified.")
|
||||
mTimeout = cmdMaster.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
mMaxCpu = cmdMaster.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
|
||||
garbageThreshold = cmdMaster.Flag.String("garbageThreshold", "0.3", "threshold to vacuum and reclaim spaces")
|
||||
masterWhiteListOption = cmdMaster.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
masterSecureKey = cmdMaster.Flag.String("secure.secret", "", "secret to encrypt Json Web Token(JWT)")
|
||||
masterCpuProfile = cmdMaster.Flag.String("cpuprofile", "", "cpu profile output file")
|
||||
// mTimeout = cmdMaster.Flag.Int("idleTimeout", 30, "connection idle seconds")
|
||||
mMaxCpu = cmdMaster.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
|
||||
garbageThreshold = cmdMaster.Flag.String("garbageThreshold", "0.3", "threshold to vacuum and reclaim spaces")
|
||||
masterWhiteListOption = cmdMaster.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
masterSecureKey = cmdMaster.Flag.String("secure.secret", "", "secret to encrypt Json Web Token(JWT)")
|
||||
masterCpuProfile = cmdMaster.Flag.String("cpuprofile", "", "cpu profile output file")
|
||||
|
||||
masterWhiteList []string
|
||||
)
|
||||
@@ -73,7 +77,8 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
|
||||
r := mux.NewRouter()
|
||||
ms := weed_server.NewMasterServer(r, *mport, *metaFolder,
|
||||
*volumeSizeLimitMB, *mpulse, *confFile, *defaultReplicaPlacement, *garbageThreshold,
|
||||
*volumeSizeLimitMB, *volumePreallocate,
|
||||
*mpulse, *defaultReplicaPlacement, *garbageThreshold,
|
||||
masterWhiteList, *masterSecureKey,
|
||||
)
|
||||
|
||||
@@ -81,7 +86,7 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
|
||||
glog.V(0).Infoln("Start Seaweed Master", util.VERSION, "at", listeningAddress)
|
||||
|
||||
listener, e := util.NewListener(listeningAddress, time.Duration(*mTimeout)*time.Second)
|
||||
listener, e := util.NewListener(listeningAddress, 0)
|
||||
if e != nil {
|
||||
glog.Fatalf("Master startup error: %v", e)
|
||||
}
|
||||
@@ -97,8 +102,25 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
ms.SetRaftServer(raftServer)
|
||||
}()
|
||||
|
||||
if e := http.Serve(listener, r); e != nil {
|
||||
glog.Fatalf("Fail to serve: %v", e)
|
||||
// start grpc and http server
|
||||
m := cmux.New(listener)
|
||||
|
||||
grpcL := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
|
||||
httpL := m.Match(cmux.Any())
|
||||
|
||||
// Create your protocol servers.
|
||||
grpcS := grpc.NewServer()
|
||||
pb.RegisterSeaweedServer(grpcS, ms)
|
||||
reflection.Register(grpcS)
|
||||
|
||||
httpS := &http.Server{Handler: r}
|
||||
|
||||
go grpcS.Serve(grpcL)
|
||||
go httpS.Serve(httpL)
|
||||
|
||||
if err := m.Serve(); err != nil {
|
||||
glog.Fatalf("master server failed to serve: %v", err)
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
@@ -26,7 +26,7 @@ var cmdMount = &Command{
|
||||
2) have a "weed filer" running
|
||||
These 2 requirements can be achieved with one command "weed server -filer=true"
|
||||
|
||||
This uses bazil.org/fuse, whichenables writing FUSE file systems on
|
||||
This uses bazil.org/fuse, which enables writing FUSE file systems on
|
||||
Linux, and OS X.
|
||||
|
||||
On OS X, it requires OSXFUSE (http://osxfuse.github.com/).
|
||||
|
||||
+79
-38
@@ -4,8 +4,11 @@ package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"path"
|
||||
|
||||
"bazil.org/fuse"
|
||||
"bazil.org/fuse/fs"
|
||||
"github.com/chrislusf/seaweedfs/weed/filer"
|
||||
@@ -22,7 +25,7 @@ func runMount(cmd *Command, args []string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
c, err := fuse.Mount(*mountOptions.dir)
|
||||
c, err := fuse.Mount(*mountOptions.dir, fuse.LocalVolume())
|
||||
if err != nil {
|
||||
glog.Fatal(err)
|
||||
return false
|
||||
@@ -47,60 +50,98 @@ func runMount(cmd *Command, args []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
type File struct {
|
||||
FileId filer.FileId
|
||||
Name string
|
||||
}
|
||||
|
||||
func (File) Attr(context context.Context, attr *fuse.Attr) error {
|
||||
return nil
|
||||
}
|
||||
func (File) ReadAll(ctx context.Context) ([]byte, error) {
|
||||
return []byte("hello, world\n"), nil
|
||||
}
|
||||
|
||||
type Dir struct {
|
||||
Path string
|
||||
Id uint64
|
||||
}
|
||||
|
||||
func (dir Dir) Attr(context context.Context, attr *fuse.Attr) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dir Dir) Lookup(ctx context.Context, name string) (fs.Node, error) {
|
||||
files_result, e := filer.ListFiles(*mountOptions.filer, dir.Path, name)
|
||||
if e != nil {
|
||||
return nil, fuse.ENOENT
|
||||
}
|
||||
if len(files_result.Files) > 0 {
|
||||
return File{files_result.Files[0].Id, files_result.Files[0].Name}, nil
|
||||
}
|
||||
return nil, fmt.Errorf("File Not Found for %s", name)
|
||||
}
|
||||
|
||||
type WFS struct{}
|
||||
|
||||
func (WFS) Root() (fs.Node, error) {
|
||||
return Dir{}, nil
|
||||
return &Dir{Path: "/"}, nil
|
||||
}
|
||||
|
||||
func (dir *Dir) ReadDir(ctx context.Context) ([]fuse.Dirent, error) {
|
||||
var fileIdMap = make(map[uint64]filer.FileId)
|
||||
|
||||
type Dir struct {
|
||||
Id uint64
|
||||
Path string
|
||||
DirentMap map[string]*fuse.Dirent
|
||||
}
|
||||
|
||||
func (dir *Dir) Attr(context context.Context, attr *fuse.Attr) error {
|
||||
attr.Inode = dir.Id
|
||||
attr.Mode = os.ModeDir | 0555
|
||||
return nil
|
||||
}
|
||||
|
||||
func (dir *Dir) Lookup(ctx context.Context, name string) (fs.Node, error) {
|
||||
if dirent, ok := dir.DirentMap[name]; ok {
|
||||
if dirent.Type == fuse.DT_File {
|
||||
return &File{Id: dirent.Inode, FileId: fileIdMap[dirent.Inode], Name: dirent.Name}, nil
|
||||
}
|
||||
return &Dir{
|
||||
Id: dirent.Inode,
|
||||
Path: path.Join(dir.Path, dirent.Name),
|
||||
}, nil
|
||||
}
|
||||
return nil, fuse.ENOENT
|
||||
}
|
||||
|
||||
func (dir *Dir) ReadDirAll(ctx context.Context) ([]fuse.Dirent, error) {
|
||||
var ret []fuse.Dirent
|
||||
if dir.DirentMap == nil {
|
||||
dir.DirentMap = make(map[string]*fuse.Dirent)
|
||||
}
|
||||
if dirs, e := filer.ListDirectories(*mountOptions.filer, dir.Path); e == nil {
|
||||
for _, d := range dirs.Directories {
|
||||
dirId := uint64(d.Id)
|
||||
ret = append(ret, fuse.Dirent{Inode: dirId, Name: d.Name, Type: fuse.DT_Dir})
|
||||
dirent := fuse.Dirent{Inode: dirId, Name: d.Name, Type: fuse.DT_Dir}
|
||||
ret = append(ret, dirent)
|
||||
dir.DirentMap[d.Name] = &dirent
|
||||
}
|
||||
}
|
||||
if files, e := filer.ListFiles(*mountOptions.filer, dir.Path, ""); e == nil {
|
||||
for _, f := range files.Files {
|
||||
if fileId, e := storage.ParseFileId(string(f.Id)); e == nil {
|
||||
fileInode := uint64(fileId.VolumeId)<<48 + fileId.Key
|
||||
ret = append(ret, fuse.Dirent{Inode: fileInode, Name: f.Name, Type: fuse.DT_File})
|
||||
dirent := fuse.Dirent{Inode: fileInode, Name: f.Name, Type: fuse.DT_File}
|
||||
ret = append(ret, dirent)
|
||||
dir.DirentMap[f.Name] = &dirent
|
||||
fileIdMap[fileInode] = f.Id
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
|
||||
func (dir *Dir) Remove(ctx context.Context, req *fuse.RemoveRequest) error {
|
||||
name := path.Join(dir.Path, req.Name)
|
||||
err := filer.DeleteDirectoryOrFile(*mountOptions.filer, name, req.Dir)
|
||||
if err != nil {
|
||||
fmt.Printf("Delete file %s [ERROR] %s\n", name, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
type File struct {
|
||||
Id uint64
|
||||
FileId filer.FileId
|
||||
Name string
|
||||
}
|
||||
|
||||
func (file *File) Attr(context context.Context, attr *fuse.Attr) error {
|
||||
attr.Inode = file.Id
|
||||
attr.Mode = 0444
|
||||
ret, err := filer.GetFileSize(*mountOptions.filer, string(file.FileId))
|
||||
if err == nil {
|
||||
attr.Size = ret.Size
|
||||
} else {
|
||||
fmt.Printf("Get file %s attr [ERROR] %s\n", file.Name, err)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
func (file *File) ReadAll(ctx context.Context) ([]byte, error) {
|
||||
ret, err := filer.GetFileContent(*mountOptions.filer, string(file.FileId))
|
||||
if err == nil {
|
||||
return ret.Content, nil
|
||||
}
|
||||
fmt.Printf("Get file %s content [ERROR] %s\n", file.Name, err)
|
||||
return nil, err
|
||||
}
|
||||
+37
-31
@@ -11,10 +11,14 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/pb"
|
||||
"github.com/chrislusf/seaweedfs/weed/server"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/soheilhy/cmux"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
)
|
||||
|
||||
type ServerOptions struct {
|
||||
@@ -51,7 +55,7 @@ var (
|
||||
serverIp = cmdServer.Flag.String("ip", "localhost", "ip or server name")
|
||||
serverBindIp = cmdServer.Flag.String("ip.bind", "0.0.0.0", "ip address to bind to")
|
||||
serverMaxCpu = cmdServer.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
|
||||
serverTimeout = cmdServer.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
serverTimeout = cmdServer.Flag.Int("idleTimeout", 30, "connection idle seconds")
|
||||
serverDataCenter = cmdServer.Flag.String("dataCenter", "", "current volume server's data center name")
|
||||
serverRack = cmdServer.Flag.String("rack", "", "current volume server's rack name")
|
||||
serverWhiteListOption = cmdServer.Flag.String("whiteList", "", "comma separated Ip addresses having write permission. No limit if empty.")
|
||||
@@ -61,14 +65,14 @@ var (
|
||||
masterPort = cmdServer.Flag.Int("master.port", 9333, "master server http listen port")
|
||||
masterMetaFolder = cmdServer.Flag.String("master.dir", "", "data directory to store meta data, default to same as -dir specified")
|
||||
masterVolumeSizeLimitMB = cmdServer.Flag.Uint("master.volumeSizeLimitMB", 30*1000, "Master stops directing writes to oversized volumes.")
|
||||
masterConfFile = cmdServer.Flag.String("master.conf", "/etc/weedfs/weedfs.conf", "xml configuration file")
|
||||
masterVolumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
masterDefaultReplicaPlacement = cmdServer.Flag.String("master.defaultReplicaPlacement", "000", "Default replication type if not specified.")
|
||||
volumePort = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
|
||||
volumePublicPort = cmdServer.Flag.Int("volume.port.public", 0, "volume server public port")
|
||||
volumeDataFolders = cmdServer.Flag.String("dir", os.TempDir(), "directories to store data files. dir[,dir]...")
|
||||
volumeMaxDataVolumeCounts = cmdServer.Flag.String("volume.max", "7", "maximum numbers of volumes, count[,count]...")
|
||||
volumePulse = cmdServer.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
|
||||
volumeIndexType = cmdServer.Flag.String("volume.index", "memory", "Choose [memory|leveldb|boltdb] mode for memory~performance balance.")
|
||||
volumeIndexType = cmdServer.Flag.String("volume.index", "memory", "Choose [memory|leveldb|boltdb|btree] mode for memory~performance balance.")
|
||||
volumeFixJpgOrientation = cmdServer.Flag.Bool("volume.images.fix.orientation", true, "Adjust jpg orientation when uploading.")
|
||||
volumeReadRedirect = cmdServer.Flag.Bool("volume.read.redirect", true, "Redirect moved or non-local volumes.")
|
||||
volumeServerPublicUrl = cmdServer.Flag.String("volume.publicUrl", "", "publicly accessible address")
|
||||
@@ -83,6 +87,7 @@ func init() {
|
||||
filerOptions.master = cmdServer.Flag.String("filer.master", "", "default to current master server")
|
||||
filerOptions.collection = cmdServer.Flag.String("filer.collection", "", "all data will be stored in this collection")
|
||||
filerOptions.port = cmdServer.Flag.Int("filer.port", 8888, "filer server http listen port")
|
||||
filerOptions.publicPort = cmdServer.Flag.Int("filer.port.public", 0, "filer server public http listen port")
|
||||
filerOptions.dir = cmdServer.Flag.String("filer.dir", "", "directory to store meta data, default to a 'filer' sub directory of what -dir is specified")
|
||||
filerOptions.defaultReplicaPlacement = cmdServer.Flag.String("filer.defaultReplicaPlacement", "", "Default replication type if not specified during runtime.")
|
||||
filerOptions.redirectOnRead = cmdServer.Flag.Bool("filer.redirectOnRead", false, "whether proxy or redirect to volume server during file GET request")
|
||||
@@ -112,6 +117,7 @@ func runServer(cmd *Command, args []string) bool {
|
||||
}
|
||||
|
||||
*filerOptions.master = *serverIp + ":" + strconv.Itoa(*masterPort)
|
||||
filerOptions.ip = serverIp
|
||||
|
||||
if *filerOptions.defaultReplicaPlacement == "" {
|
||||
*filerOptions.defaultReplicaPlacement = *masterDefaultReplicaPlacement
|
||||
@@ -168,30 +174,9 @@ func runServer(cmd *Command, args []string) bool {
|
||||
if *isStartingFiler {
|
||||
go func() {
|
||||
time.Sleep(1 * time.Second)
|
||||
r := http.NewServeMux()
|
||||
_, nfs_err := weed_server.NewFilerServer(r, *serverBindIp, *filerOptions.port, *filerOptions.master, *filerOptions.dir, *filerOptions.collection,
|
||||
*filerOptions.defaultReplicaPlacement,
|
||||
*filerOptions.redirectOnRead, *filerOptions.disableDirListing,
|
||||
*filerOptions.confFile,
|
||||
*filerOptions.maxMB,
|
||||
*filerOptions.secretKey,
|
||||
*filerOptions.cassandra_server, *filerOptions.cassandra_keyspace,
|
||||
*filerOptions.redis_server, *filerOptions.redis_password, *filerOptions.redis_database,
|
||||
)
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
}
|
||||
glog.V(0).Infoln("Start Seaweed Filer", util.VERSION, "at port", strconv.Itoa(*filerOptions.port))
|
||||
filerListener, e := util.NewListener(
|
||||
":"+strconv.Itoa(*filerOptions.port),
|
||||
time.Duration(10)*time.Second,
|
||||
)
|
||||
if e != nil {
|
||||
glog.Fatalf("Filer listener error: %v", e)
|
||||
}
|
||||
if e := http.Serve(filerListener, r); e != nil {
|
||||
glog.Fatalf("Filer Fail to serve: %v", e)
|
||||
}
|
||||
|
||||
filerOptions.start()
|
||||
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -204,12 +189,13 @@ func runServer(cmd *Command, args []string) bool {
|
||||
go func() {
|
||||
r := mux.NewRouter()
|
||||
ms := weed_server.NewMasterServer(r, *masterPort, *masterMetaFolder,
|
||||
*masterVolumeSizeLimitMB, *volumePulse, *masterConfFile, *masterDefaultReplicaPlacement, *serverGarbageThreshold,
|
||||
*masterVolumeSizeLimitMB, *masterVolumePreallocate,
|
||||
*volumePulse, *masterDefaultReplicaPlacement, *serverGarbageThreshold,
|
||||
serverWhiteList, *serverSecureKey,
|
||||
)
|
||||
|
||||
glog.V(0).Infoln("Start Seaweed Master", util.VERSION, "at", *serverIp+":"+strconv.Itoa(*masterPort))
|
||||
masterListener, e := util.NewListener(*serverBindIp+":"+strconv.Itoa(*masterPort), time.Duration(*serverTimeout)*time.Second)
|
||||
masterListener, e := util.NewListener(*serverBindIp+":"+strconv.Itoa(*masterPort), 0)
|
||||
if e != nil {
|
||||
glog.Fatalf("Master startup error: %v", e)
|
||||
}
|
||||
@@ -228,9 +214,27 @@ func runServer(cmd *Command, args []string) bool {
|
||||
}()
|
||||
|
||||
raftWaitForMaster.Done()
|
||||
if e := http.Serve(masterListener, r); e != nil {
|
||||
glog.Fatalf("Master Fail to serve:%s", e.Error())
|
||||
|
||||
// start grpc and http server
|
||||
m := cmux.New(masterListener)
|
||||
|
||||
grpcL := m.Match(cmux.HTTP2HeaderField("content-type", "application/grpc"))
|
||||
httpL := m.Match(cmux.Any())
|
||||
|
||||
// Create your protocol servers.
|
||||
grpcS := grpc.NewServer()
|
||||
pb.RegisterSeaweedServer(grpcS, ms)
|
||||
reflection.Register(grpcS)
|
||||
|
||||
httpS := &http.Server{Handler: r}
|
||||
|
||||
go grpcS.Serve(grpcL)
|
||||
go httpS.Serve(httpL)
|
||||
|
||||
if err := m.Serve(); err != nil {
|
||||
glog.Fatalf("master server failed to serve: %v", err)
|
||||
}
|
||||
|
||||
}()
|
||||
|
||||
volumeWait.Wait()
|
||||
@@ -253,6 +257,8 @@ func runServer(cmd *Command, args []string) bool {
|
||||
volumeNeedleMapKind = storage.NeedleMapLevelDb
|
||||
case "boltdb":
|
||||
volumeNeedleMapKind = storage.NeedleMapBoltDb
|
||||
case "btree":
|
||||
volumeNeedleMapKind = storage.NeedleMapBtree
|
||||
}
|
||||
volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
|
||||
*serverIp, *volumePort, *volumeServerPublicUrl,
|
||||
|
||||
@@ -20,6 +20,7 @@ type UploadOptions struct {
|
||||
include *string
|
||||
replication *string
|
||||
collection *string
|
||||
dataCenter *string
|
||||
ttl *string
|
||||
maxMB *int
|
||||
secretKey *string
|
||||
@@ -33,6 +34,7 @@ func init() {
|
||||
upload.include = cmdUpload.Flag.String("include", "", "pattens of files to upload, e.g., *.pdf, *.html, ab?d.txt, works together with -dir")
|
||||
upload.replication = cmdUpload.Flag.String("replication", "", "replication type")
|
||||
upload.collection = cmdUpload.Flag.String("collection", "", "optional collection name")
|
||||
upload.dataCenter = cmdUpload.Flag.String("dataCenter", "", "optional data center name")
|
||||
upload.ttl = cmdUpload.Flag.String("ttl", "", "time to live, e.g.: 1m, 1h, 1d, 1M, 1y")
|
||||
upload.maxMB = cmdUpload.Flag.Int("maxMB", 0, "split files larger than the limit")
|
||||
upload.secretKey = cmdUpload.Flag.String("secure.secret", "", "secret to encrypt Json Web Token(JWT)")
|
||||
@@ -80,7 +82,7 @@ func runUpload(cmd *Command, args []string) bool {
|
||||
return e
|
||||
}
|
||||
results, e := operation.SubmitFiles(*upload.master, parts,
|
||||
*upload.replication, *upload.collection,
|
||||
*upload.replication, *upload.collection, *upload.dataCenter,
|
||||
*upload.ttl, *upload.maxMB, secret)
|
||||
bytes, _ := json.Marshal(results)
|
||||
fmt.Println(string(bytes))
|
||||
@@ -99,7 +101,7 @@ func runUpload(cmd *Command, args []string) bool {
|
||||
fmt.Println(e.Error())
|
||||
}
|
||||
results, _ := operation.SubmitFiles(*upload.master, parts,
|
||||
*upload.replication, *upload.collection,
|
||||
*upload.replication, *upload.collection, *upload.dataCenter,
|
||||
*upload.ttl, *upload.maxMB, secret)
|
||||
bytes, _ := json.Marshal(results)
|
||||
fmt.Println(string(bytes))
|
||||
|
||||
@@ -48,11 +48,11 @@ func init() {
|
||||
v.bindIp = cmdVolume.Flag.String("ip.bind", "0.0.0.0", "ip address to bind to")
|
||||
v.master = cmdVolume.Flag.String("mserver", "localhost:9333", "master server location")
|
||||
v.pulseSeconds = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than or equal to the master's setting")
|
||||
v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 10, "connection idle seconds")
|
||||
v.idleConnectionTimeout = cmdVolume.Flag.Int("idleTimeout", 30, "connection idle seconds")
|
||||
v.maxCpu = cmdVolume.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
|
||||
v.dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
|
||||
v.rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
|
||||
v.indexType = cmdVolume.Flag.String("index", "memory", "Choose [memory|leveldb|boltdb] mode for memory~performance balance.")
|
||||
v.indexType = cmdVolume.Flag.String("index", "memory", "Choose [memory|leveldb|boltdb|btree] mode for memory~performance balance.")
|
||||
v.fixJpgOrientation = cmdVolume.Flag.Bool("images.fix.orientation", true, "Adjust jpg orientation when uploading.")
|
||||
v.readRedirect = cmdVolume.Flag.Bool("read.redirect", true, "Redirect moved or non-local volumes.")
|
||||
v.enableBytesCache = cmdVolume.Flag.Bool("cache.enable", false, "direct cache instead of OS cache, cost more memory.")
|
||||
@@ -126,6 +126,8 @@ func runVolume(cmd *Command, args []string) bool {
|
||||
volumeNeedleMapKind = storage.NeedleMapLevelDb
|
||||
case "boltdb":
|
||||
volumeNeedleMapKind = storage.NeedleMapBoltDb
|
||||
case "btree":
|
||||
volumeNeedleMapKind = storage.NeedleMapBtree
|
||||
}
|
||||
volumeServer := weed_server.NewVolumeServer(volumeMux, publicVolumeMux,
|
||||
*v.ip, *v.port, *v.publicUrl,
|
||||
|
||||
@@ -4,16 +4,16 @@ import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
|
||||
"net/url"
|
||||
)
|
||||
|
||||
type ApiRequest struct {
|
||||
Command string //"listFiles", "listDirectories"
|
||||
Command string //"listFiles", "listDirectories", "getFileSize"
|
||||
Directory string
|
||||
FileName string
|
||||
FileId string
|
||||
}
|
||||
|
||||
type ListFilesResult struct {
|
||||
@@ -21,16 +21,47 @@ type ListFilesResult struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func ListFiles(server string, directory string, fileName string) (*ListFilesResult, error) {
|
||||
var ret ListFilesResult
|
||||
if err := call(server, ApiRequest{Command: "listFiles", Directory: directory, FileName: fileName}, &ret); err == nil {
|
||||
func ListFiles(server string, directory string, fileName string) (ret *ListFilesResult, err error) {
|
||||
ret = new(ListFilesResult)
|
||||
if err = call(server, ApiRequest{Command: "listFiles", Directory: directory, FileName: fileName}, ret); err == nil {
|
||||
if ret.Error != "" {
|
||||
return nil, errors.New(ret.Error)
|
||||
}
|
||||
return &ret, nil
|
||||
} else {
|
||||
return nil, err
|
||||
return ret, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type GetFileSizeResult struct {
|
||||
Size uint64
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func GetFileSize(server string, fileId string) (ret *GetFileSizeResult, err error) {
|
||||
ret = new(GetFileSizeResult)
|
||||
if err = call(server, ApiRequest{Command: "getFileSize", FileId: fileId}, ret); err == nil {
|
||||
if ret.Error != "" {
|
||||
return nil, errors.New(ret.Error)
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type GetFileContentResult struct {
|
||||
Content []byte
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func GetFileContent(server string, fileId string) (ret *GetFileContentResult, err error) {
|
||||
ret = new(GetFileContentResult)
|
||||
if err = call(server, ApiRequest{Command: "getFileContent", FileId: fileId}, ret); err == nil {
|
||||
if ret.Error != "" {
|
||||
return nil, errors.New(ret.Error)
|
||||
}
|
||||
return ret, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
type ListDirectoriesResult struct {
|
||||
@@ -38,16 +69,23 @@ type ListDirectoriesResult struct {
|
||||
Error string `json:"error,omitempty"`
|
||||
}
|
||||
|
||||
func ListDirectories(server string, directory string) (*ListDirectoriesResult, error) {
|
||||
var ret ListDirectoriesResult
|
||||
if err := call(server, ApiRequest{Command: "listDirectories", Directory: directory}, &ret); err == nil {
|
||||
func ListDirectories(server string, directory string) (ret *ListDirectoriesResult, err error) {
|
||||
ret = new(ListDirectoriesResult)
|
||||
if err := call(server, ApiRequest{Command: "listDirectories", Directory: directory}, ret); err == nil {
|
||||
if ret.Error != "" {
|
||||
return nil, errors.New(ret.Error)
|
||||
}
|
||||
return &ret, nil
|
||||
} else {
|
||||
return nil, err
|
||||
return ret, nil
|
||||
}
|
||||
return nil, err
|
||||
}
|
||||
|
||||
func DeleteDirectoryOrFile(server string, path string, isDir bool) error {
|
||||
destUrl := fmt.Sprintf("http://%s%s", server, path)
|
||||
if isDir {
|
||||
destUrl += "/?recursive=true"
|
||||
}
|
||||
return util.Delete(destUrl, "")
|
||||
}
|
||||
|
||||
func call(server string, request ApiRequest, ret interface{}) error {
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"fmt"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/filer"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
@@ -14,6 +15,7 @@ type FilerEmbedded struct {
|
||||
master string
|
||||
directories *DirectoryManagerInMap
|
||||
files *FileListInLevelDb
|
||||
mvMutex sync.Mutex
|
||||
}
|
||||
|
||||
func NewFilerEmbedded(master string, dir string) (filer *FilerEmbedded, err error) {
|
||||
@@ -121,6 +123,9 @@ mv fromFile toDir
|
||||
mv fromFile toFile
|
||||
*/
|
||||
func (filer *FilerEmbedded) Move(fromPath string, toPath string) error {
|
||||
filer.mvMutex.Lock()
|
||||
defer filer.mvMutex.Unlock()
|
||||
|
||||
if _, dir_err := filer.FindDirectory(fromPath); dir_err == nil {
|
||||
if _, err := filer.FindDirectory(toPath); err == nil {
|
||||
// move folder under an existing folder
|
||||
|
||||
@@ -184,7 +184,7 @@ func (s *MySqlStore) Close() {
|
||||
var createTable = `
|
||||
CREATE TABLE IF NOT EXISTS %s (
|
||||
id bigint(20) NOT NULL AUTO_INCREMENT,
|
||||
uriPath char(256) NOT NULL DEFAULT "" COMMENT 'http uriPath',
|
||||
uriPath char(255) NOT NULL DEFAULT "" COMMENT 'http uriPath',
|
||||
fid char(36) NOT NULL DEFAULT "" COMMENT 'seaweedfs fid',
|
||||
createTime int(10) NOT NULL DEFAULT 0 COMMENT 'createdTime in unix timestamp',
|
||||
updateTime int(10) NOT NULL DEFAULT 0 COMMENT 'updatedTime in unix timestamp',
|
||||
|
||||
@@ -18,10 +18,10 @@ func MaybePreprocessImage(filename string, data []byte, width, height int) (resi
|
||||
ext = strings.ToLower(ext)
|
||||
switch ext {
|
||||
case ".png", ".gif":
|
||||
return Resized(ext, data, width, height)
|
||||
return Resized(ext, data, width, height, "")
|
||||
case ".jpg", ".jpeg":
|
||||
data = FixJpgOrientation(data)
|
||||
return Resized(ext, data, width, height)
|
||||
return Resized(ext, data, width, height, "")
|
||||
}
|
||||
return data, 0, 0
|
||||
}
|
||||
+13
-6
@@ -11,7 +11,7 @@ import (
|
||||
"github.com/disintegration/imaging"
|
||||
)
|
||||
|
||||
func Resized(ext string, data []byte, width, height int) (resized []byte, w int, h int) {
|
||||
func Resized(ext string, data []byte, width, height int, mode string) (resized []byte, w int, h int) {
|
||||
if width == 0 && height == 0 {
|
||||
return data, 0, 0
|
||||
}
|
||||
@@ -20,11 +20,18 @@ func Resized(ext string, data []byte, width, height int) (resized []byte, w int,
|
||||
bounds := srcImage.Bounds()
|
||||
var dstImage *image.NRGBA
|
||||
if bounds.Dx() > width && width != 0 || bounds.Dy() > height && height != 0 {
|
||||
if width == height && bounds.Dx() != bounds.Dy() {
|
||||
dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
|
||||
w, h = width, height
|
||||
} else {
|
||||
dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
|
||||
switch mode {
|
||||
case "fit":
|
||||
dstImage = imaging.Fit(srcImage, width, height, imaging.Lanczos)
|
||||
case "fill":
|
||||
dstImage = imaging.Fill(srcImage, width, height, imaging.Center, imaging.Lanczos)
|
||||
default:
|
||||
if width == height && bounds.Dx() != bounds.Dy() {
|
||||
dstImage = imaging.Thumbnail(srcImage, width, height, imaging.Lanczos)
|
||||
w, h = width, height
|
||||
} else {
|
||||
dstImage = imaging.Resize(srcImage, width, height, imaging.Lanczos)
|
||||
}
|
||||
}
|
||||
} else {
|
||||
return data, bounds.Dx(), bounds.Dy()
|
||||
|
||||
@@ -13,20 +13,20 @@ type ClusterStatusResult struct {
|
||||
Peers []string `json:"Peers,omitempty"`
|
||||
}
|
||||
|
||||
func ListMasters(server string) ([]string, error) {
|
||||
func ListMasters(server string) (leader string, peers []string, err error) {
|
||||
jsonBlob, err := util.Get("http://" + server + "/cluster/status")
|
||||
glog.V(2).Info("list masters result :", string(jsonBlob))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return "", nil, err
|
||||
}
|
||||
var ret ClusterStatusResult
|
||||
err = json.Unmarshal(jsonBlob, &ret)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return "", nil, err
|
||||
}
|
||||
masters := ret.Peers
|
||||
peers = ret.Peers
|
||||
if ret.IsLeader {
|
||||
masters = append(masters, ret.Leader)
|
||||
peers = append(peers, ret.Leader)
|
||||
}
|
||||
return masters, nil
|
||||
return ret.Leader, peers, nil
|
||||
}
|
||||
+48
-21
@@ -23,6 +23,7 @@ type FilePart struct {
|
||||
ModTime int64 //in seconds
|
||||
Replication string
|
||||
Collection string
|
||||
DataCenter string
|
||||
Ttl string
|
||||
Server string //this comes from assign result
|
||||
Fid string //this comes from assign result, but customizable
|
||||
@@ -37,7 +38,7 @@ type SubmitResult struct {
|
||||
}
|
||||
|
||||
func SubmitFiles(master string, files []FilePart,
|
||||
replication string, collection string, ttl string, maxMB int,
|
||||
replication string, collection string, dataCenter string, ttl string, maxMB int,
|
||||
secret security.Secret,
|
||||
) ([]SubmitResult, error) {
|
||||
results := make([]SubmitResult, len(files))
|
||||
@@ -48,6 +49,7 @@ func SubmitFiles(master string, files []FilePart,
|
||||
Count: uint64(len(files)),
|
||||
Replication: replication,
|
||||
Collection: collection,
|
||||
DataCenter: dataCenter,
|
||||
Ttl: ttl,
|
||||
}
|
||||
ret, err := Assign(master, ar)
|
||||
@@ -65,6 +67,7 @@ func SubmitFiles(master string, files []FilePart,
|
||||
file.Server = ret.Url
|
||||
file.Replication = replication
|
||||
file.Collection = collection
|
||||
file.DataCenter = dataCenter
|
||||
results[index].Size, err = file.Upload(maxMB, master, secret)
|
||||
if err != nil {
|
||||
results[index].Error = err.Error()
|
||||
@@ -129,11 +132,46 @@ func (fi FilePart) Upload(maxMB int, master string, secret security.Secret) (ret
|
||||
Chunks: make([]*ChunkInfo, 0, chunks),
|
||||
}
|
||||
|
||||
var ret *AssignResult
|
||||
var id string
|
||||
if fi.DataCenter != "" {
|
||||
ar := &VolumeAssignRequest{
|
||||
Count: uint64(chunks),
|
||||
Replication: fi.Replication,
|
||||
Collection: fi.Collection,
|
||||
Ttl: fi.Ttl,
|
||||
}
|
||||
ret, err = Assign(master, ar)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
for i := int64(0); i < chunks; i++ {
|
||||
id, count, e := upload_one_chunk(
|
||||
if fi.DataCenter == "" {
|
||||
ar := &VolumeAssignRequest{
|
||||
Count: 1,
|
||||
Replication: fi.Replication,
|
||||
Collection: fi.Collection,
|
||||
Ttl: fi.Ttl,
|
||||
}
|
||||
ret, err = Assign(master, ar)
|
||||
if err != nil {
|
||||
// delete all uploaded chunks
|
||||
cm.DeleteChunks(master)
|
||||
return
|
||||
}
|
||||
id = ret.Fid
|
||||
} else {
|
||||
id = ret.Fid
|
||||
if i > 0 {
|
||||
id += "_" + strconv.FormatInt(i, 10)
|
||||
}
|
||||
}
|
||||
fileUrl := "http://" + ret.Url + "/" + id
|
||||
count, e := upload_one_chunk(
|
||||
baseName+"-"+strconv.FormatInt(i+1, 10),
|
||||
io.LimitReader(fi.Reader, chunkSize),
|
||||
master, fi.Replication, fi.Collection, fi.Ttl,
|
||||
master, fileUrl,
|
||||
jwt)
|
||||
if e != nil {
|
||||
// delete all uploaded chunks
|
||||
@@ -155,7 +193,7 @@ func (fi FilePart) Upload(maxMB int, master string, secret security.Secret) (ret
|
||||
cm.DeleteChunks(master)
|
||||
}
|
||||
} else {
|
||||
ret, e := Upload(fileUrl, baseName, fi.Reader, fi.IsGzipped, fi.MimeType, jwt)
|
||||
ret, e := Upload(fileUrl, baseName, fi.Reader, fi.IsGzipped, fi.MimeType, nil, jwt)
|
||||
if e != nil {
|
||||
return 0, e
|
||||
}
|
||||
@@ -165,26 +203,15 @@ func (fi FilePart) Upload(maxMB int, master string, secret security.Secret) (ret
|
||||
}
|
||||
|
||||
func upload_one_chunk(filename string, reader io.Reader, master,
|
||||
replication string, collection string, ttl string, jwt security.EncodedJwt,
|
||||
) (fid string, size uint32, e error) {
|
||||
ar := &VolumeAssignRequest{
|
||||
Count: 1,
|
||||
Replication: replication,
|
||||
Collection: collection,
|
||||
Ttl: ttl,
|
||||
}
|
||||
ret, err := Assign(master, ar)
|
||||
if err != nil {
|
||||
return "", 0, err
|
||||
}
|
||||
fileUrl, fid := "http://"+ret.Url+"/"+ret.Fid, ret.Fid
|
||||
fileUrl string, jwt security.EncodedJwt,
|
||||
) (size uint32, e error) {
|
||||
glog.V(4).Info("Uploading part ", filename, " to ", fileUrl, "...")
|
||||
uploadResult, uploadError := Upload(fileUrl, filename, reader, false,
|
||||
"application/octet-stream", jwt)
|
||||
"application/octet-stream", nil, jwt)
|
||||
if uploadError != nil {
|
||||
return fid, 0, uploadError
|
||||
return 0, uploadError
|
||||
}
|
||||
return fid, uploadResult.Size, nil
|
||||
return uploadResult.Size, nil
|
||||
}
|
||||
|
||||
func upload_chunked_file_manifest(fileUrl string, manifest *ChunkManifest, jwt security.EncodedJwt) error {
|
||||
@@ -198,6 +225,6 @@ func upload_chunked_file_manifest(fileUrl string, manifest *ChunkManifest, jwt s
|
||||
q := u.Query()
|
||||
q.Set("cm", "true")
|
||||
u.RawQuery = q.Encode()
|
||||
_, e = Upload(u.String(), manifest.Name, bufReader, false, "application/json", jwt)
|
||||
_, e = Upload(u.String(), manifest.Name, bufReader, false, "application/json", nil, jwt)
|
||||
return e
|
||||
}
|
||||
@@ -1,203 +0,0 @@
|
||||
// Code generated by protoc-gen-go.
|
||||
// source: system_message.proto
|
||||
// DO NOT EDIT!
|
||||
|
||||
/*
|
||||
Package operation is a generated protocol buffer package.
|
||||
|
||||
It is generated from these files:
|
||||
system_message.proto
|
||||
|
||||
It has these top-level messages:
|
||||
VolumeInformationMessage
|
||||
JoinMessage
|
||||
*/
|
||||
package operation
|
||||
|
||||
import proto "github.com/golang/protobuf/proto"
|
||||
import math "math"
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = math.Inf
|
||||
|
||||
type VolumeInformationMessage struct {
|
||||
Id *uint32 `protobuf:"varint,1,req,name=id" json:"id,omitempty"`
|
||||
Size *uint64 `protobuf:"varint,2,req,name=size" json:"size,omitempty"`
|
||||
Collection *string `protobuf:"bytes,3,opt,name=collection" json:"collection,omitempty"`
|
||||
FileCount *uint64 `protobuf:"varint,4,req,name=file_count" json:"file_count,omitempty"`
|
||||
DeleteCount *uint64 `protobuf:"varint,5,req,name=delete_count" json:"delete_count,omitempty"`
|
||||
DeletedByteCount *uint64 `protobuf:"varint,6,req,name=deleted_byte_count" json:"deleted_byte_count,omitempty"`
|
||||
ReadOnly *bool `protobuf:"varint,7,opt,name=read_only" json:"read_only,omitempty"`
|
||||
ReplicaPlacement *uint32 `protobuf:"varint,8,req,name=replica_placement" json:"replica_placement,omitempty"`
|
||||
Version *uint32 `protobuf:"varint,9,opt,name=version,def=2" json:"version,omitempty"`
|
||||
Ttl *uint32 `protobuf:"varint,10,opt,name=ttl" json:"ttl,omitempty"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) Reset() { *m = VolumeInformationMessage{} }
|
||||
func (m *VolumeInformationMessage) String() string { return proto.CompactTextString(m) }
|
||||
func (*VolumeInformationMessage) ProtoMessage() {}
|
||||
|
||||
const Default_VolumeInformationMessage_Version uint32 = 2
|
||||
|
||||
func (m *VolumeInformationMessage) GetId() uint32 {
|
||||
if m != nil && m.Id != nil {
|
||||
return *m.Id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetSize() uint64 {
|
||||
if m != nil && m.Size != nil {
|
||||
return *m.Size
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetCollection() string {
|
||||
if m != nil && m.Collection != nil {
|
||||
return *m.Collection
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetFileCount() uint64 {
|
||||
if m != nil && m.FileCount != nil {
|
||||
return *m.FileCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetDeleteCount() uint64 {
|
||||
if m != nil && m.DeleteCount != nil {
|
||||
return *m.DeleteCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetDeletedByteCount() uint64 {
|
||||
if m != nil && m.DeletedByteCount != nil {
|
||||
return *m.DeletedByteCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetReadOnly() bool {
|
||||
if m != nil && m.ReadOnly != nil {
|
||||
return *m.ReadOnly
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetReplicaPlacement() uint32 {
|
||||
if m != nil && m.ReplicaPlacement != nil {
|
||||
return *m.ReplicaPlacement
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetVersion() uint32 {
|
||||
if m != nil && m.Version != nil {
|
||||
return *m.Version
|
||||
}
|
||||
return Default_VolumeInformationMessage_Version
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetTtl() uint32 {
|
||||
if m != nil && m.Ttl != nil {
|
||||
return *m.Ttl
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type JoinMessage struct {
|
||||
IsInit *bool `protobuf:"varint,1,opt,name=is_init" json:"is_init,omitempty"`
|
||||
Ip *string `protobuf:"bytes,2,req,name=ip" json:"ip,omitempty"`
|
||||
Port *uint32 `protobuf:"varint,3,req,name=port" json:"port,omitempty"`
|
||||
PublicUrl *string `protobuf:"bytes,4,opt,name=public_url" json:"public_url,omitempty"`
|
||||
MaxVolumeCount *uint32 `protobuf:"varint,5,req,name=max_volume_count" json:"max_volume_count,omitempty"`
|
||||
MaxFileKey *uint64 `protobuf:"varint,6,req,name=max_file_key" json:"max_file_key,omitempty"`
|
||||
DataCenter *string `protobuf:"bytes,7,opt,name=data_center" json:"data_center,omitempty"`
|
||||
Rack *string `protobuf:"bytes,8,opt,name=rack" json:"rack,omitempty"`
|
||||
Volumes []*VolumeInformationMessage `protobuf:"bytes,9,rep,name=volumes" json:"volumes,omitempty"`
|
||||
AdminPort *uint32 `protobuf:"varint,10,opt,name=admin_port" json:"admin_port,omitempty"`
|
||||
XXX_unrecognized []byte `json:"-"`
|
||||
}
|
||||
|
||||
func (m *JoinMessage) Reset() { *m = JoinMessage{} }
|
||||
func (m *JoinMessage) String() string { return proto.CompactTextString(m) }
|
||||
func (*JoinMessage) ProtoMessage() {}
|
||||
|
||||
func (m *JoinMessage) GetIsInit() bool {
|
||||
if m != nil && m.IsInit != nil {
|
||||
return *m.IsInit
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetIp() string {
|
||||
if m != nil && m.Ip != nil {
|
||||
return *m.Ip
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetPort() uint32 {
|
||||
if m != nil && m.Port != nil {
|
||||
return *m.Port
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetPublicUrl() string {
|
||||
if m != nil && m.PublicUrl != nil {
|
||||
return *m.PublicUrl
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetMaxVolumeCount() uint32 {
|
||||
if m != nil && m.MaxVolumeCount != nil {
|
||||
return *m.MaxVolumeCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetMaxFileKey() uint64 {
|
||||
if m != nil && m.MaxFileKey != nil {
|
||||
return *m.MaxFileKey
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetDataCenter() string {
|
||||
if m != nil && m.DataCenter != nil {
|
||||
return *m.DataCenter
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetRack() string {
|
||||
if m != nil && m.Rack != nil {
|
||||
return *m.Rack
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetVolumes() []*VolumeInformationMessage {
|
||||
if m != nil {
|
||||
return m.Volumes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (m *JoinMessage) GetAdminPort() uint32 {
|
||||
if m != nil && m.AdminPort != nil {
|
||||
return *m.AdminPort
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func init() {
|
||||
}
|
||||
@@ -1,59 +0,0 @@
|
||||
package operation
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"log"
|
||||
"testing"
|
||||
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
func TestSerialDeserial(t *testing.T) {
|
||||
volumeMessage := &VolumeInformationMessage{
|
||||
Id: proto.Uint32(12),
|
||||
Size: proto.Uint64(2341234),
|
||||
Collection: proto.String("benchmark"),
|
||||
FileCount: proto.Uint64(2341234),
|
||||
DeleteCount: proto.Uint64(234),
|
||||
DeletedByteCount: proto.Uint64(21234),
|
||||
ReadOnly: proto.Bool(false),
|
||||
ReplicaPlacement: proto.Uint32(210),
|
||||
Version: proto.Uint32(2),
|
||||
}
|
||||
var volumeMessages []*VolumeInformationMessage
|
||||
volumeMessages = append(volumeMessages, volumeMessage)
|
||||
|
||||
joinMessage := &JoinMessage{
|
||||
IsInit: proto.Bool(true),
|
||||
Ip: proto.String("127.0.3.12"),
|
||||
Port: proto.Uint32(34546),
|
||||
PublicUrl: proto.String("localhost:2342"),
|
||||
MaxVolumeCount: proto.Uint32(210),
|
||||
MaxFileKey: proto.Uint64(324234423),
|
||||
DataCenter: proto.String("dc1"),
|
||||
Rack: proto.String("rack2"),
|
||||
Volumes: volumeMessages,
|
||||
}
|
||||
|
||||
data, err := proto.Marshal(joinMessage)
|
||||
if err != nil {
|
||||
log.Fatal("marshaling error: ", err)
|
||||
}
|
||||
newMessage := &JoinMessage{}
|
||||
err = proto.Unmarshal(data, newMessage)
|
||||
if err != nil {
|
||||
log.Fatal("unmarshaling error: ", err)
|
||||
}
|
||||
log.Println("The pb data size is", len(data))
|
||||
|
||||
jsonData, jsonError := json.Marshal(joinMessage)
|
||||
if jsonError != nil {
|
||||
log.Fatal("json marshaling error: ", jsonError)
|
||||
}
|
||||
log.Println("The json data size is", len(jsonData), string(jsonData))
|
||||
|
||||
// Now test and newTest contain the same data.
|
||||
if *joinMessage.PublicUrl != *newMessage.PublicUrl {
|
||||
log.Fatalf("data mismatch %q != %q", *joinMessage.PublicUrl, *newMessage.PublicUrl)
|
||||
}
|
||||
}
|
||||
@@ -36,13 +36,13 @@ func init() {
|
||||
|
||||
var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
|
||||
|
||||
func Upload(uploadUrl string, filename string, reader io.Reader, isGzipped bool, mtype string, jwt security.EncodedJwt) (*UploadResult, error) {
|
||||
func Upload(uploadUrl string, filename string, reader io.Reader, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
|
||||
return upload_content(uploadUrl, func(w io.Writer) (err error) {
|
||||
_, err = io.Copy(w, reader)
|
||||
return
|
||||
}, filename, isGzipped, mtype, jwt)
|
||||
}, filename, isGzipped, mtype, pairMap, jwt)
|
||||
}
|
||||
func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error, filename string, isGzipped bool, mtype string, jwt security.EncodedJwt) (*UploadResult, error) {
|
||||
func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error, filename string, isGzipped bool, mtype string, pairMap map[string]string, jwt security.EncodedJwt) (*UploadResult, error) {
|
||||
body_buf := bytes.NewBufferString("")
|
||||
body_writer := multipart.NewWriter(body_buf)
|
||||
h := make(textproto.MIMEHeader)
|
||||
@@ -59,6 +59,7 @@ func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error
|
||||
if jwt != "" {
|
||||
h.Set("Authorization", "BEARER "+string(jwt))
|
||||
}
|
||||
|
||||
file_writer, cp_err := body_writer.CreatePart(h)
|
||||
if cp_err != nil {
|
||||
glog.V(0).Infoln("error creating form file", cp_err.Error())
|
||||
@@ -73,7 +74,17 @@ func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error
|
||||
glog.V(0).Infoln("error closing body", err)
|
||||
return nil, err
|
||||
}
|
||||
resp, post_err := client.Post(uploadUrl, content_type, body_buf)
|
||||
|
||||
req, postErr := http.NewRequest("POST", uploadUrl, body_buf)
|
||||
if postErr != nil {
|
||||
glog.V(0).Infoln("failing to upload to", uploadUrl, postErr.Error())
|
||||
return nil, postErr
|
||||
}
|
||||
req.Header.Set("Content-Type", content_type)
|
||||
for k, v := range pairMap {
|
||||
req.Header.Set(k, v)
|
||||
}
|
||||
resp, post_err := client.Do(req)
|
||||
if post_err != nil {
|
||||
glog.V(0).Infoln("failing to upload to", uploadUrl, post_err.Error())
|
||||
return nil, post_err
|
||||
@@ -86,7 +97,7 @@ func upload_content(uploadUrl string, fillBufferFunction func(w io.Writer) error
|
||||
var ret UploadResult
|
||||
unmarshal_err := json.Unmarshal(resp_body, &ret)
|
||||
if unmarshal_err != nil {
|
||||
glog.V(0).Infoln("failing to read upload resonse", uploadUrl, string(resp_body))
|
||||
glog.V(0).Infoln("failing to read upload response", uploadUrl, string(resp_body))
|
||||
return nil, unmarshal_err
|
||||
}
|
||||
if ret.Error != "" {
|
||||
|
||||
@@ -0,0 +1,6 @@
|
||||
all: gen
|
||||
|
||||
.PHONY : gen
|
||||
|
||||
gen:
|
||||
protoc seaweed.proto --go_out=plugins=grpc:.
|
||||
@@ -0,0 +1,384 @@
|
||||
// Code generated by protoc-gen-go.
|
||||
// source: seaweed.proto
|
||||
// DO NOT EDIT!
|
||||
|
||||
/*
|
||||
Package pb is a generated protocol buffer package.
|
||||
|
||||
It is generated from these files:
|
||||
seaweed.proto
|
||||
|
||||
It has these top-level messages:
|
||||
Heartbeat
|
||||
HeartbeatResponse
|
||||
VolumeInformationMessage
|
||||
*/
|
||||
package pb
|
||||
|
||||
import proto "github.com/golang/protobuf/proto"
|
||||
import fmt "fmt"
|
||||
import math "math"
|
||||
|
||||
import (
|
||||
context "golang.org/x/net/context"
|
||||
grpc "google.golang.org/grpc"
|
||||
)
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ = proto.Marshal
|
||||
var _ = fmt.Errorf
|
||||
var _ = math.Inf
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the proto package it is being compiled against.
|
||||
// A compilation error at this line likely means your copy of the
|
||||
// proto package needs to be updated.
|
||||
const _ = proto.ProtoPackageIsVersion2 // please upgrade the proto package
|
||||
|
||||
type Heartbeat struct {
|
||||
Ip string `protobuf:"bytes,1,opt,name=ip" json:"ip,omitempty"`
|
||||
Port uint32 `protobuf:"varint,2,opt,name=port" json:"port,omitempty"`
|
||||
PublicUrl string `protobuf:"bytes,3,opt,name=public_url,json=publicUrl" json:"public_url,omitempty"`
|
||||
MaxVolumeCount uint32 `protobuf:"varint,4,opt,name=max_volume_count,json=maxVolumeCount" json:"max_volume_count,omitempty"`
|
||||
MaxFileKey uint64 `protobuf:"varint,5,opt,name=max_file_key,json=maxFileKey" json:"max_file_key,omitempty"`
|
||||
DataCenter string `protobuf:"bytes,6,opt,name=data_center,json=dataCenter" json:"data_center,omitempty"`
|
||||
Rack string `protobuf:"bytes,7,opt,name=rack" json:"rack,omitempty"`
|
||||
AdminPort uint32 `protobuf:"varint,8,opt,name=admin_port,json=adminPort" json:"admin_port,omitempty"`
|
||||
Volumes []*VolumeInformationMessage `protobuf:"bytes,9,rep,name=volumes" json:"volumes,omitempty"`
|
||||
}
|
||||
|
||||
func (m *Heartbeat) Reset() { *m = Heartbeat{} }
|
||||
func (m *Heartbeat) String() string { return proto.CompactTextString(m) }
|
||||
func (*Heartbeat) ProtoMessage() {}
|
||||
func (*Heartbeat) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{0} }
|
||||
|
||||
func (m *Heartbeat) GetIp() string {
|
||||
if m != nil {
|
||||
return m.Ip
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetPort() uint32 {
|
||||
if m != nil {
|
||||
return m.Port
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetPublicUrl() string {
|
||||
if m != nil {
|
||||
return m.PublicUrl
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetMaxVolumeCount() uint32 {
|
||||
if m != nil {
|
||||
return m.MaxVolumeCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetMaxFileKey() uint64 {
|
||||
if m != nil {
|
||||
return m.MaxFileKey
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetDataCenter() string {
|
||||
if m != nil {
|
||||
return m.DataCenter
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetRack() string {
|
||||
if m != nil {
|
||||
return m.Rack
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetAdminPort() uint32 {
|
||||
if m != nil {
|
||||
return m.AdminPort
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *Heartbeat) GetVolumes() []*VolumeInformationMessage {
|
||||
if m != nil {
|
||||
return m.Volumes
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
type HeartbeatResponse struct {
|
||||
VolumeSizeLimit uint64 `protobuf:"varint,1,opt,name=volumeSizeLimit" json:"volumeSizeLimit,omitempty"`
|
||||
SecretKey string `protobuf:"bytes,2,opt,name=secretKey" json:"secretKey,omitempty"`
|
||||
Leader string `protobuf:"bytes,3,opt,name=leader" json:"leader,omitempty"`
|
||||
}
|
||||
|
||||
func (m *HeartbeatResponse) Reset() { *m = HeartbeatResponse{} }
|
||||
func (m *HeartbeatResponse) String() string { return proto.CompactTextString(m) }
|
||||
func (*HeartbeatResponse) ProtoMessage() {}
|
||||
func (*HeartbeatResponse) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{1} }
|
||||
|
||||
func (m *HeartbeatResponse) GetVolumeSizeLimit() uint64 {
|
||||
if m != nil {
|
||||
return m.VolumeSizeLimit
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *HeartbeatResponse) GetSecretKey() string {
|
||||
if m != nil {
|
||||
return m.SecretKey
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *HeartbeatResponse) GetLeader() string {
|
||||
if m != nil {
|
||||
return m.Leader
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
type VolumeInformationMessage struct {
|
||||
Id uint32 `protobuf:"varint,1,opt,name=id" json:"id,omitempty"`
|
||||
Size uint64 `protobuf:"varint,2,opt,name=size" json:"size,omitempty"`
|
||||
Collection string `protobuf:"bytes,3,opt,name=collection" json:"collection,omitempty"`
|
||||
FileCount uint64 `protobuf:"varint,4,opt,name=file_count,json=fileCount" json:"file_count,omitempty"`
|
||||
DeleteCount uint64 `protobuf:"varint,5,opt,name=delete_count,json=deleteCount" json:"delete_count,omitempty"`
|
||||
DeletedByteCount uint64 `protobuf:"varint,6,opt,name=deleted_byte_count,json=deletedByteCount" json:"deleted_byte_count,omitempty"`
|
||||
ReadOnly bool `protobuf:"varint,7,opt,name=read_only,json=readOnly" json:"read_only,omitempty"`
|
||||
ReplicaPlacement uint32 `protobuf:"varint,8,opt,name=replica_placement,json=replicaPlacement" json:"replica_placement,omitempty"`
|
||||
Version uint32 `protobuf:"varint,9,opt,name=version" json:"version,omitempty"`
|
||||
Ttl uint32 `protobuf:"varint,10,opt,name=ttl" json:"ttl,omitempty"`
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) Reset() { *m = VolumeInformationMessage{} }
|
||||
func (m *VolumeInformationMessage) String() string { return proto.CompactTextString(m) }
|
||||
func (*VolumeInformationMessage) ProtoMessage() {}
|
||||
func (*VolumeInformationMessage) Descriptor() ([]byte, []int) { return fileDescriptor0, []int{2} }
|
||||
|
||||
func (m *VolumeInformationMessage) GetId() uint32 {
|
||||
if m != nil {
|
||||
return m.Id
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetSize() uint64 {
|
||||
if m != nil {
|
||||
return m.Size
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetCollection() string {
|
||||
if m != nil {
|
||||
return m.Collection
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetFileCount() uint64 {
|
||||
if m != nil {
|
||||
return m.FileCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetDeleteCount() uint64 {
|
||||
if m != nil {
|
||||
return m.DeleteCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetDeletedByteCount() uint64 {
|
||||
if m != nil {
|
||||
return m.DeletedByteCount
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetReadOnly() bool {
|
||||
if m != nil {
|
||||
return m.ReadOnly
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetReplicaPlacement() uint32 {
|
||||
if m != nil {
|
||||
return m.ReplicaPlacement
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetVersion() uint32 {
|
||||
if m != nil {
|
||||
return m.Version
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func (m *VolumeInformationMessage) GetTtl() uint32 {
|
||||
if m != nil {
|
||||
return m.Ttl
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
func init() {
|
||||
proto.RegisterType((*Heartbeat)(nil), "pb.Heartbeat")
|
||||
proto.RegisterType((*HeartbeatResponse)(nil), "pb.HeartbeatResponse")
|
||||
proto.RegisterType((*VolumeInformationMessage)(nil), "pb.VolumeInformationMessage")
|
||||
}
|
||||
|
||||
// Reference imports to suppress errors if they are not otherwise used.
|
||||
var _ context.Context
|
||||
var _ grpc.ClientConn
|
||||
|
||||
// This is a compile-time assertion to ensure that this generated file
|
||||
// is compatible with the grpc package it is being compiled against.
|
||||
const _ = grpc.SupportPackageIsVersion4
|
||||
|
||||
// Client API for Seaweed service
|
||||
|
||||
type SeaweedClient interface {
|
||||
SendHeartbeat(ctx context.Context, opts ...grpc.CallOption) (Seaweed_SendHeartbeatClient, error)
|
||||
}
|
||||
|
||||
type seaweedClient struct {
|
||||
cc *grpc.ClientConn
|
||||
}
|
||||
|
||||
func NewSeaweedClient(cc *grpc.ClientConn) SeaweedClient {
|
||||
return &seaweedClient{cc}
|
||||
}
|
||||
|
||||
func (c *seaweedClient) SendHeartbeat(ctx context.Context, opts ...grpc.CallOption) (Seaweed_SendHeartbeatClient, error) {
|
||||
stream, err := grpc.NewClientStream(ctx, &_Seaweed_serviceDesc.Streams[0], c.cc, "/pb.Seaweed/SendHeartbeat", opts...)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
x := &seaweedSendHeartbeatClient{stream}
|
||||
return x, nil
|
||||
}
|
||||
|
||||
type Seaweed_SendHeartbeatClient interface {
|
||||
Send(*Heartbeat) error
|
||||
Recv() (*HeartbeatResponse, error)
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
type seaweedSendHeartbeatClient struct {
|
||||
grpc.ClientStream
|
||||
}
|
||||
|
||||
func (x *seaweedSendHeartbeatClient) Send(m *Heartbeat) error {
|
||||
return x.ClientStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *seaweedSendHeartbeatClient) Recv() (*HeartbeatResponse, error) {
|
||||
m := new(HeartbeatResponse)
|
||||
if err := x.ClientStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
// Server API for Seaweed service
|
||||
|
||||
type SeaweedServer interface {
|
||||
SendHeartbeat(Seaweed_SendHeartbeatServer) error
|
||||
}
|
||||
|
||||
func RegisterSeaweedServer(s *grpc.Server, srv SeaweedServer) {
|
||||
s.RegisterService(&_Seaweed_serviceDesc, srv)
|
||||
}
|
||||
|
||||
func _Seaweed_SendHeartbeat_Handler(srv interface{}, stream grpc.ServerStream) error {
|
||||
return srv.(SeaweedServer).SendHeartbeat(&seaweedSendHeartbeatServer{stream})
|
||||
}
|
||||
|
||||
type Seaweed_SendHeartbeatServer interface {
|
||||
Send(*HeartbeatResponse) error
|
||||
Recv() (*Heartbeat, error)
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
type seaweedSendHeartbeatServer struct {
|
||||
grpc.ServerStream
|
||||
}
|
||||
|
||||
func (x *seaweedSendHeartbeatServer) Send(m *HeartbeatResponse) error {
|
||||
return x.ServerStream.SendMsg(m)
|
||||
}
|
||||
|
||||
func (x *seaweedSendHeartbeatServer) Recv() (*Heartbeat, error) {
|
||||
m := new(Heartbeat)
|
||||
if err := x.ServerStream.RecvMsg(m); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return m, nil
|
||||
}
|
||||
|
||||
var _Seaweed_serviceDesc = grpc.ServiceDesc{
|
||||
ServiceName: "pb.Seaweed",
|
||||
HandlerType: (*SeaweedServer)(nil),
|
||||
Methods: []grpc.MethodDesc{},
|
||||
Streams: []grpc.StreamDesc{
|
||||
{
|
||||
StreamName: "SendHeartbeat",
|
||||
Handler: _Seaweed_SendHeartbeat_Handler,
|
||||
ServerStreams: true,
|
||||
ClientStreams: true,
|
||||
},
|
||||
},
|
||||
Metadata: "seaweed.proto",
|
||||
}
|
||||
|
||||
func init() { proto.RegisterFile("seaweed.proto", fileDescriptor0) }
|
||||
|
||||
var fileDescriptor0 = []byte{
|
||||
// 498 bytes of a gzipped FileDescriptorProto
|
||||
0x1f, 0x8b, 0x08, 0x00, 0x00, 0x09, 0x6e, 0x88, 0x02, 0xff, 0x74, 0x93, 0xdf, 0x6e, 0xd3, 0x30,
|
||||
0x14, 0xc6, 0x49, 0x1a, 0xda, 0xe6, 0x74, 0x1d, 0x9d, 0x25, 0x90, 0x05, 0x03, 0x4a, 0xaf, 0x22,
|
||||
0x81, 0x2a, 0x34, 0x24, 0x6e, 0xb8, 0x63, 0xd2, 0x04, 0x1a, 0x88, 0xc9, 0x15, 0xdc, 0x46, 0x4e,
|
||||
0x72, 0x86, 0xac, 0x39, 0x7f, 0xe4, 0xb8, 0xa3, 0xd9, 0x03, 0xf1, 0x24, 0x3c, 0x18, 0xf2, 0x71,
|
||||
0xd2, 0x02, 0x12, 0x77, 0xe7, 0xfc, 0xce, 0x17, 0xfb, 0xf4, 0xfb, 0x5c, 0x98, 0xb7, 0x28, 0x7f,
|
||||
0x20, 0x16, 0xeb, 0xc6, 0xd4, 0xb6, 0x66, 0x61, 0x93, 0xad, 0x7e, 0x86, 0x10, 0x7f, 0x40, 0x69,
|
||||
0x6c, 0x86, 0xd2, 0xb2, 0x63, 0x08, 0x55, 0xc3, 0x83, 0x65, 0x90, 0xc4, 0x22, 0x54, 0x0d, 0x63,
|
||||
0x10, 0x35, 0xb5, 0xb1, 0x3c, 0x5c, 0x06, 0xc9, 0x5c, 0x50, 0xcd, 0x9e, 0x02, 0x34, 0xdb, 0x4c,
|
||||
0xab, 0x3c, 0xdd, 0x1a, 0xcd, 0x47, 0xa4, 0x8d, 0x3d, 0xf9, 0x6a, 0x34, 0x4b, 0x60, 0x51, 0xca,
|
||||
0x5d, 0x7a, 0x5b, 0xeb, 0x6d, 0x89, 0x69, 0x5e, 0x6f, 0x2b, 0xcb, 0x23, 0xfa, 0xfc, 0xb8, 0x94,
|
||||
0xbb, 0x6f, 0x84, 0xcf, 0x1d, 0x65, 0x4b, 0x38, 0x72, 0xca, 0x6b, 0xa5, 0x31, 0xbd, 0xc1, 0x8e,
|
||||
0xdf, 0x5f, 0x06, 0x49, 0x24, 0xa0, 0x94, 0xbb, 0x0b, 0xa5, 0xf1, 0x12, 0x3b, 0xf6, 0x1c, 0x66,
|
||||
0x85, 0xb4, 0x32, 0xcd, 0xb1, 0xb2, 0x68, 0xf8, 0x98, 0xee, 0x02, 0x87, 0xce, 0x89, 0xb8, 0xfd,
|
||||
0x8c, 0xcc, 0x6f, 0xf8, 0x84, 0x26, 0x54, 0xbb, 0xfd, 0x64, 0x51, 0xaa, 0x2a, 0xa5, 0xcd, 0xa7,
|
||||
0x74, 0x75, 0x4c, 0xe4, 0xca, 0xad, 0xff, 0x16, 0x26, 0x7e, 0xb7, 0x96, 0xc7, 0xcb, 0x51, 0x32,
|
||||
0x3b, 0x3b, 0x5d, 0x37, 0xd9, 0xda, 0xef, 0xf5, 0xb1, 0xba, 0xae, 0x4d, 0x29, 0xad, 0xaa, 0xab,
|
||||
0xcf, 0xd8, 0xb6, 0xf2, 0x3b, 0x8a, 0x41, 0xbc, 0x6a, 0xe1, 0x64, 0xef, 0x93, 0xc0, 0xb6, 0xa9,
|
||||
0xab, 0x16, 0x59, 0x02, 0x0f, 0xfc, 0x7c, 0xa3, 0xee, 0xf0, 0x93, 0x2a, 0x95, 0x25, 0xf3, 0x22,
|
||||
0xf1, 0x2f, 0x66, 0xa7, 0x10, 0xb7, 0x98, 0x1b, 0xb4, 0x97, 0xd8, 0x91, 0x9d, 0xb1, 0x38, 0x00,
|
||||
0xf6, 0x08, 0xc6, 0x1a, 0x65, 0x81, 0xa6, 0xf7, 0xb3, 0xef, 0x56, 0xbf, 0x42, 0xe0, 0xff, 0x5b,
|
||||
0x8d, 0xc2, 0x2a, 0xe8, 0xbe, 0xb9, 0x08, 0x55, 0xe1, 0xcc, 0x68, 0xd5, 0x1d, 0xd2, 0xe9, 0x91,
|
||||
0xa0, 0x9a, 0x3d, 0x03, 0xc8, 0x6b, 0xad, 0x31, 0x77, 0x1f, 0xf6, 0x87, 0xff, 0x41, 0x9c, 0x59,
|
||||
0xe4, 0xff, 0x21, 0xa7, 0x48, 0xc4, 0x8e, 0xf8, 0x88, 0x5e, 0xc0, 0x51, 0x81, 0x1a, 0xed, 0x20,
|
||||
0xf0, 0x11, 0xcd, 0x3c, 0xf3, 0x92, 0x57, 0xc0, 0x7c, 0x5b, 0xa4, 0x59, 0xb7, 0x17, 0x8e, 0x49,
|
||||
0xb8, 0xe8, 0x27, 0xef, 0xbb, 0x41, 0xfd, 0x04, 0x62, 0x83, 0xb2, 0x48, 0xeb, 0x4a, 0x77, 0x94,
|
||||
0xda, 0x54, 0x4c, 0x1d, 0xf8, 0x52, 0xe9, 0x8e, 0xbd, 0x84, 0x13, 0x83, 0x8d, 0x56, 0xb9, 0x4c,
|
||||
0x1b, 0x2d, 0x73, 0x2c, 0xb1, 0x1a, 0x02, 0x5c, 0xf4, 0x83, 0xab, 0x81, 0x33, 0x0e, 0x93, 0x5b,
|
||||
0x34, 0xad, 0xfb, 0x59, 0x31, 0x49, 0x86, 0x96, 0x2d, 0x60, 0x64, 0xad, 0xe6, 0x40, 0xd4, 0x95,
|
||||
0x67, 0x17, 0x30, 0xd9, 0xf8, 0x97, 0xcf, 0xde, 0xc1, 0x7c, 0x83, 0x55, 0x71, 0x78, 0xf2, 0x73,
|
||||
0x17, 0xff, 0xbe, 0x7d, 0xfc, 0xf0, 0xaf, 0x76, 0x08, 0x7a, 0x75, 0x2f, 0x09, 0x5e, 0x07, 0xd9,
|
||||
0x98, 0xfe, 0x37, 0x6f, 0x7e, 0x07, 0x00, 0x00, 0xff, 0xff, 0x7c, 0xda, 0x3f, 0x9c, 0x48, 0x03,
|
||||
0x00, 0x00,
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
syntax = "proto3";
|
||||
|
||||
package pb;
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
service Seaweed {
|
||||
rpc SendHeartbeat(stream Heartbeat) returns (stream HeartbeatResponse) {}
|
||||
}
|
||||
|
||||
//////////////////////////////////////////////////
|
||||
|
||||
message Heartbeat {
|
||||
string ip = 1;
|
||||
uint32 port = 2;
|
||||
string public_url = 3;
|
||||
uint32 max_volume_count = 4;
|
||||
uint64 max_file_key = 5;
|
||||
string data_center = 6;
|
||||
string rack = 7;
|
||||
uint32 admin_port = 8;
|
||||
repeated VolumeInformationMessage volumes = 9;
|
||||
}
|
||||
message HeartbeatResponse {
|
||||
uint64 volumeSizeLimit = 1;
|
||||
string secretKey = 2;
|
||||
string leader = 3;
|
||||
}
|
||||
|
||||
message VolumeInformationMessage {
|
||||
uint32 id = 1;
|
||||
uint64 size = 2;
|
||||
string collection = 3;
|
||||
uint64 file_count = 4;
|
||||
uint64 delete_count = 5;
|
||||
uint64 deleted_byte_count = 6;
|
||||
bool read_only = 7;
|
||||
uint32 replica_placement = 8;
|
||||
uint32 version = 9;
|
||||
uint32 ttl = 10;
|
||||
}
|
||||
@@ -1,4 +0,0 @@
|
||||
TARG=../operation
|
||||
|
||||
all:
|
||||
protoc --go_out=$(TARG) system_message.proto
|
||||
@@ -1,27 +0,0 @@
|
||||
package operation;
|
||||
|
||||
message VolumeInformationMessage {
|
||||
required uint32 id = 1;
|
||||
required uint64 size = 2;
|
||||
optional string collection = 3;
|
||||
required uint64 file_count = 4;
|
||||
required uint64 delete_count = 5;
|
||||
required uint64 deleted_byte_count = 6;
|
||||
optional bool read_only = 7;
|
||||
required uint32 replica_placement = 8;
|
||||
optional uint32 version = 9 [default=2];
|
||||
optional uint32 ttl = 10;
|
||||
}
|
||||
|
||||
message JoinMessage {
|
||||
optional bool is_init = 1;
|
||||
required string ip = 2;
|
||||
required uint32 port = 3;
|
||||
optional string public_url = 4;
|
||||
required uint32 max_volume_count = 5;
|
||||
required uint64 max_file_key = 6;
|
||||
optional string data_center = 7;
|
||||
optional string rack = 8;
|
||||
repeated VolumeInformationMessage volumes = 9;
|
||||
optional uint32 admin_port = 10;
|
||||
}
|
||||
@@ -86,7 +86,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st
|
||||
}
|
||||
|
||||
debug("parsing upload file...")
|
||||
fname, data, mimeType, isGzipped, lastModified, _, _, pe := storage.ParseUpload(r)
|
||||
fname, data, mimeType, pairMap, isGzipped, lastModified, _, _, pe := storage.ParseUpload(r)
|
||||
if pe != nil {
|
||||
writeJsonError(w, r, http.StatusBadRequest, pe)
|
||||
return
|
||||
@@ -112,7 +112,7 @@ func submitForClientHandler(w http.ResponseWriter, r *http.Request, masterUrl st
|
||||
}
|
||||
|
||||
debug("upload file to store", url)
|
||||
uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, jwt)
|
||||
uploadResult, err := operation.Upload(url, fname, bytes.NewReader(data), isGzipped, mimeType, pairMap, jwt)
|
||||
if err != nil {
|
||||
writeJsonError(w, r, http.StatusInternalServerError, err)
|
||||
return
|
||||
|
||||
@@ -57,7 +57,7 @@ type FilerServer struct {
|
||||
masterNodes *storage.MasterNodes
|
||||
}
|
||||
|
||||
func NewFilerServer(r *http.ServeMux, ip string, port int, master string, dir string, collection string,
|
||||
func NewFilerServer(defaultMux, readonlyMux *http.ServeMux, ip string, port int, master string, dir string, collection string,
|
||||
replication string, redirectOnRead bool, disableDirListing bool,
|
||||
confFile string,
|
||||
maxMB int,
|
||||
@@ -105,11 +105,15 @@ func NewFilerServer(r *http.ServeMux, ip string, port int, master string, dir st
|
||||
return
|
||||
}
|
||||
|
||||
r.HandleFunc("/admin/mv", fs.moveHandler)
|
||||
r.HandleFunc("/admin/register", fs.registerHandler)
|
||||
defaultMux.HandleFunc("/admin/mv", fs.moveHandler)
|
||||
defaultMux.HandleFunc("/admin/register", fs.registerHandler)
|
||||
defaultMux.HandleFunc("/__api__", fs.apiHandler)
|
||||
}
|
||||
|
||||
r.HandleFunc("/", fs.filerHandler)
|
||||
defaultMux.HandleFunc("/", fs.filerHandler)
|
||||
if defaultMux != readonlyMux {
|
||||
readonlyMux.HandleFunc("/", fs.readonlyFilerHandler)
|
||||
}
|
||||
|
||||
go func() {
|
||||
connected := true
|
||||
@@ -117,17 +121,6 @@ func NewFilerServer(r *http.ServeMux, ip string, port int, master string, dir st
|
||||
fs.masterNodes = storage.NewMasterNodes(fs.master)
|
||||
glog.V(0).Infof("Filer server bootstraps with master %s", fs.getMasterNode())
|
||||
|
||||
//force initialize with all available master nodes
|
||||
for {
|
||||
_, err := fs.masterNodes.FindMaster()
|
||||
if err != nil {
|
||||
glog.Infof("filer server failed to get master cluster info:%s", err.Error())
|
||||
time.Sleep(3 * time.Second)
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
for {
|
||||
glog.V(4).Infof("Filer server sending to master %s", fs.getMasterNode())
|
||||
master, err := fs.detectHealthyMaster(fs.getMasterNode())
|
||||
|
||||
@@ -18,3 +18,12 @@ func (fs *FilerServer) filerHandler(w http.ResponseWriter, r *http.Request) {
|
||||
fs.PostHandler(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (fs *FilerServer) readonlyFilerHandler(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.Method {
|
||||
case "GET":
|
||||
fs.GetOrHeadHandler(w, r, true)
|
||||
case "HEAD":
|
||||
fs.GetOrHeadHandler(w, r, false)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,73 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/filer"
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func (fs *FilerServer) apiHandler(w http.ResponseWriter, r *http.Request) {
|
||||
request := r.FormValue("request")
|
||||
apiRequest := filer.ApiRequest{}
|
||||
|
||||
err := json.Unmarshal([]byte(request), &apiRequest)
|
||||
if err != nil {
|
||||
glog.V(0).Infoln("failing to read request", r.RequestURI, request)
|
||||
writeJsonError(w, r, http.StatusInternalServerError, err)
|
||||
}
|
||||
switch apiRequest.Command {
|
||||
case "listDirectories":
|
||||
res := filer.ListDirectoriesResult{}
|
||||
res.Directories, err = fs.filer.ListDirectories(apiRequest.Directory)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
}
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
case "listFiles":
|
||||
res := filer.ListFilesResult{}
|
||||
res.Files, err = fs.filer.ListFiles(apiRequest.Directory, apiRequest.FileName, 100)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
}
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
case "getFileSize":
|
||||
res := filer.GetFileSizeResult{}
|
||||
server, err := operation.LookupFileId(fs.getMasterNode(), apiRequest.FileId)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
return
|
||||
}
|
||||
head, err := util.Head(server)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
return
|
||||
}
|
||||
res.Size, err = strconv.ParseUint(head.Get("Content-Length"), 10, 0)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
}
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
case "getFileContent":
|
||||
res := filer.GetFileContentResult{}
|
||||
server, err := operation.LookupFileId(fs.getMasterNode(), apiRequest.FileId)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
return
|
||||
}
|
||||
res.Content, err = util.Get(server)
|
||||
if err != nil {
|
||||
res.Error = err.Error()
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
return
|
||||
}
|
||||
writeJsonQuiet(w, r, http.StatusOK, res)
|
||||
}
|
||||
}
|
||||
@@ -74,8 +74,8 @@ func (fs *FilerServer) listDirectoryHandler(w http.ResponseWriter, r *http.Reque
|
||||
lastFileName,
|
||||
shouldDisplayLoadMore,
|
||||
}
|
||||
|
||||
if strings.ToLower(r.Header.Get("Content-Type")) == "application/json" {
|
||||
|
||||
if r.Header.Get("Accept") == "application/json" {
|
||||
writeJsonQuiet(w, r, http.StatusOK, args)
|
||||
} else {
|
||||
ui.StatusTpl.Execute(w, args)
|
||||
|
||||
@@ -13,6 +13,8 @@ import (
|
||||
"net/http"
|
||||
"net/textproto"
|
||||
"net/url"
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/filer"
|
||||
@@ -20,8 +22,6 @@ import (
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"path"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type FilerPostResult struct {
|
||||
@@ -112,7 +112,7 @@ func (fs *FilerServer) multipartUploadAnalyzer(w http.ResponseWriter, r *http.Re
|
||||
if r.Method == "PUT" {
|
||||
buf, _ := ioutil.ReadAll(r.Body)
|
||||
r.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
|
||||
fileName, _, _, _, _, _, _, pe := storage.ParseUpload(r)
|
||||
fileName, _, _, _, _, _, _, _, pe := storage.ParseUpload(r)
|
||||
if pe != nil {
|
||||
glog.V(0).Infoln("failing to parse post body", pe.Error())
|
||||
writeJsonError(w, r, http.StatusInternalServerError, pe)
|
||||
@@ -521,7 +521,7 @@ func (fs *FilerServer) doUpload(urlLocation string, w http.ResponseWriter, r *ht
|
||||
err = nil
|
||||
|
||||
ioReader := ioutil.NopCloser(bytes.NewBuffer(chunkBuf))
|
||||
uploadResult, uploadError := operation.Upload(urlLocation, fileName, ioReader, false, contentType, fs.jwt(fileId))
|
||||
uploadResult, uploadError := operation.Upload(urlLocation, fileName, ioReader, false, contentType, nil, fs.jwt(fileId))
|
||||
if uploadResult != nil {
|
||||
glog.V(0).Infoln("Chunk upload result. Name:", uploadResult.Name, "Fid:", fileId, "Size:", uploadResult.Size)
|
||||
}
|
||||
@@ -532,7 +532,7 @@ func (fs *FilerServer) doUpload(urlLocation string, w http.ResponseWriter, r *ht
|
||||
}
|
||||
|
||||
// curl -X DELETE http://localhost:8888/path/to
|
||||
// curl -X DELETE http://localhost:8888/path/to?recursive=true
|
||||
// curl -X DELETE http://localhost:8888/path/to/?recursive=true
|
||||
func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
var err error
|
||||
var fid string
|
||||
|
||||
@@ -0,0 +1,79 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"net"
|
||||
"strings"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/pb"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
"github.com/chrislusf/seaweedfs/weed/topology"
|
||||
"google.golang.org/grpc/peer"
|
||||
)
|
||||
|
||||
func (ms MasterServer) SendHeartbeat(stream pb.Seaweed_SendHeartbeatServer) error {
|
||||
var dn *topology.DataNode
|
||||
t := ms.Topo
|
||||
for {
|
||||
heartbeat, err := stream.Recv()
|
||||
if err == nil {
|
||||
if dn == nil {
|
||||
t.Sequence.SetMax(heartbeat.MaxFileKey)
|
||||
if heartbeat.Ip == "" {
|
||||
if pr, ok := peer.FromContext(stream.Context()); ok {
|
||||
if pr.Addr != net.Addr(nil) {
|
||||
heartbeat.Ip = pr.Addr.String()[0:strings.LastIndex(pr.Addr.String(), ":")]
|
||||
glog.V(0).Infof("remote IP address is detected as %v", heartbeat.Ip)
|
||||
}
|
||||
}
|
||||
}
|
||||
dcName, rackName := t.Configuration.Locate(heartbeat.Ip, heartbeat.DataCenter, heartbeat.Rack)
|
||||
dc := t.GetOrCreateDataCenter(dcName)
|
||||
rack := dc.GetOrCreateRack(rackName)
|
||||
dn = rack.GetOrCreateDataNode(heartbeat.Ip,
|
||||
int(heartbeat.Port), heartbeat.PublicUrl,
|
||||
int(heartbeat.MaxVolumeCount))
|
||||
glog.V(0).Infof("added volume server %v:%d", heartbeat.GetIp(), heartbeat.GetPort())
|
||||
if err := stream.Send(&pb.HeartbeatResponse{
|
||||
VolumeSizeLimit: uint64(ms.volumeSizeLimitMB) * 1024 * 1024,
|
||||
SecretKey: string(ms.guard.SecretKey),
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
var volumeInfos []storage.VolumeInfo
|
||||
for _, v := range heartbeat.Volumes {
|
||||
if vi, err := storage.NewVolumeInfo(v); err == nil {
|
||||
volumeInfos = append(volumeInfos, vi)
|
||||
} else {
|
||||
glog.V(0).Infof("Fail to convert joined volume information: %v", err)
|
||||
}
|
||||
}
|
||||
deletedVolumes := dn.UpdateVolumes(volumeInfos)
|
||||
for _, v := range volumeInfos {
|
||||
t.RegisterVolumeLayout(v, dn)
|
||||
}
|
||||
for _, v := range deletedVolumes {
|
||||
t.UnRegisterVolumeLayout(v, dn)
|
||||
}
|
||||
|
||||
} else {
|
||||
if dn != nil {
|
||||
glog.V(0).Infof("lost volume server %s:%d", dn.Ip, dn.Port)
|
||||
t.UnRegisterDataNode(dn)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// tell the volume servers about the leader
|
||||
newLeader, err := t.Leader()
|
||||
if err == nil {
|
||||
if err := stream.Send(&pb.HeartbeatResponse{
|
||||
Leader: newLeader,
|
||||
}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -20,6 +20,7 @@ type MasterServer struct {
|
||||
port int
|
||||
metaFolder string
|
||||
volumeSizeLimitMB uint
|
||||
preallocate int64
|
||||
pulseSeconds int
|
||||
defaultReplicaPlacement string
|
||||
garbageThreshold string
|
||||
@@ -34,27 +35,29 @@ type MasterServer struct {
|
||||
|
||||
func NewMasterServer(r *mux.Router, port int, metaFolder string,
|
||||
volumeSizeLimitMB uint,
|
||||
preallocate bool,
|
||||
pulseSeconds int,
|
||||
confFile string,
|
||||
defaultReplicaPlacement string,
|
||||
garbageThreshold string,
|
||||
whiteList []string,
|
||||
secureKey string,
|
||||
) *MasterServer {
|
||||
|
||||
var preallocateSize int64
|
||||
if preallocate {
|
||||
preallocateSize = int64(volumeSizeLimitMB) * (1 << 20)
|
||||
}
|
||||
ms := &MasterServer{
|
||||
port: port,
|
||||
volumeSizeLimitMB: volumeSizeLimitMB,
|
||||
preallocate: preallocateSize,
|
||||
pulseSeconds: pulseSeconds,
|
||||
defaultReplicaPlacement: defaultReplicaPlacement,
|
||||
garbageThreshold: garbageThreshold,
|
||||
}
|
||||
ms.bounedLeaderChan = make(chan int, 16)
|
||||
seq := sequence.NewMemorySequencer()
|
||||
var e error
|
||||
if ms.Topo, e = topology.NewTopology("topo", confFile, seq,
|
||||
uint64(volumeSizeLimitMB)*1024*1024, pulseSeconds); e != nil {
|
||||
glog.Fatalf("cannot create topology:%s", e)
|
||||
}
|
||||
ms.Topo = topology.NewTopology("topo", seq, uint64(volumeSizeLimitMB)*1024*1024, pulseSeconds)
|
||||
ms.vg = topology.NewDefaultVolumeGrowth()
|
||||
glog.V(0).Infoln("Volume Size Limit is", volumeSizeLimitMB, "MB")
|
||||
|
||||
@@ -64,7 +67,6 @@ func NewMasterServer(r *mux.Router, port int, metaFolder string,
|
||||
r.HandleFunc("/ui/index.html", ms.uiStatusHandler)
|
||||
r.HandleFunc("/dir/assign", ms.proxyToLeader(ms.guard.WhiteList(ms.dirAssignHandler)))
|
||||
r.HandleFunc("/dir/lookup", ms.proxyToLeader(ms.guard.WhiteList(ms.dirLookupHandler)))
|
||||
r.HandleFunc("/dir/join", ms.proxyToLeader(ms.guard.WhiteList(ms.dirJoinHandler)))
|
||||
r.HandleFunc("/dir/status", ms.proxyToLeader(ms.guard.WhiteList(ms.dirStatusHandler)))
|
||||
r.HandleFunc("/col/delete", ms.proxyToLeader(ms.guard.WhiteList(ms.collectionDeleteHandler)))
|
||||
r.HandleFunc("/vol/lookup", ms.proxyToLeader(ms.guard.WhiteList(ms.volumeLookupHandler)))
|
||||
|
||||
@@ -1,21 +1,16 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
"github.com/chrislusf/seaweedfs/weed/topology"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"github.com/golang/protobuf/proto"
|
||||
)
|
||||
|
||||
func (ms *MasterServer) collectionDeleteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -34,37 +29,6 @@ func (ms *MasterServer) collectionDeleteHandler(w http.ResponseWriter, r *http.R
|
||||
ms.Topo.DeleteCollection(r.FormValue("collection"))
|
||||
}
|
||||
|
||||
func (ms *MasterServer) dirJoinHandler(w http.ResponseWriter, r *http.Request) {
|
||||
body, err := ioutil.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
writeJsonError(w, r, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
joinMessage := &operation.JoinMessage{}
|
||||
if err = proto.Unmarshal(body, joinMessage); err != nil {
|
||||
writeJsonError(w, r, http.StatusBadRequest, err)
|
||||
return
|
||||
}
|
||||
if *joinMessage.Ip == "" {
|
||||
*joinMessage.Ip = r.RemoteAddr[0:strings.LastIndex(r.RemoteAddr, ":")]
|
||||
}
|
||||
if glog.V(4) {
|
||||
if jsonData, jsonError := json.Marshal(joinMessage); jsonError != nil {
|
||||
glog.V(0).Infoln("json marshaling error: ", jsonError)
|
||||
writeJsonError(w, r, http.StatusBadRequest, jsonError)
|
||||
return
|
||||
} else {
|
||||
glog.V(4).Infoln("Proto size", len(body), "json size", len(jsonData), string(jsonData))
|
||||
}
|
||||
}
|
||||
|
||||
ms.Topo.ProcessJoinMessage(joinMessage)
|
||||
writeJsonQuiet(w, r, http.StatusOK, operation.JoinResult{
|
||||
VolumeSizeLimit: uint64(ms.volumeSizeLimitMB) * 1024 * 1024,
|
||||
SecretKey: string(ms.guard.SecretKey),
|
||||
})
|
||||
}
|
||||
|
||||
func (ms *MasterServer) dirStatusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
m := make(map[string]interface{})
|
||||
m["Version"] = util.VERSION
|
||||
@@ -181,10 +145,18 @@ func (ms *MasterServer) getVolumeGrowOption(r *http.Request) (*topology.VolumeGr
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
preallocate := ms.preallocate
|
||||
if r.FormValue("preallocate") != "" {
|
||||
preallocate, err = strconv.ParseInt(r.FormValue("preallocate"), 10, 64)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("Failed to parse int64 preallocate = %s: %v", r.FormValue("preallocate"), err)
|
||||
}
|
||||
}
|
||||
volumeGrowOption := &topology.VolumeGrowOption{
|
||||
Collection: r.FormValue("collection"),
|
||||
ReplicaPlacement: replicaPlacement,
|
||||
Ttl: ttl,
|
||||
Prealloacte: preallocate,
|
||||
DataCenter: r.FormValue("dataCenter"),
|
||||
Rack: r.FormValue("rack"),
|
||||
DataNode: r.FormValue("dataNode"),
|
||||
|
||||
@@ -65,8 +65,8 @@ func NewRaftServer(r *mux.Router, peers []string, httpAddr string, dataDir strin
|
||||
return nil
|
||||
}
|
||||
transporter.Install(s.raftServer, s)
|
||||
s.raftServer.SetHeartbeatInterval(1 * time.Second)
|
||||
s.raftServer.SetElectionTimeout(time.Duration(pulseSeconds) * 3450 * time.Millisecond)
|
||||
s.raftServer.SetHeartbeatInterval(500 * time.Millisecond)
|
||||
s.raftServer.SetElectionTimeout(time.Duration(pulseSeconds) * 500 * time.Millisecond)
|
||||
s.raftServer.Start()
|
||||
|
||||
s.router.HandleFunc("/cluster/join", s.joinHandler).Methods("POST")
|
||||
|
||||
@@ -0,0 +1,99 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/pb"
|
||||
"github.com/chrislusf/seaweedfs/weed/security"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
"golang.org/x/net/context"
|
||||
"google.golang.org/grpc"
|
||||
)
|
||||
|
||||
func (vs *VolumeServer) heartbeat() {
|
||||
|
||||
glog.V(0).Infof("Volume server bootstraps with master %s", vs.GetMasterNode())
|
||||
vs.masterNodes = storage.NewMasterNodes(vs.masterNode)
|
||||
vs.store.SetDataCenter(vs.dataCenter)
|
||||
vs.store.SetRack(vs.rack)
|
||||
|
||||
for {
|
||||
err := vs.doHeartbeat(time.Duration(vs.pulseSeconds) * time.Second)
|
||||
if err != nil {
|
||||
glog.V(0).Infof("heartbeat error: %v", err)
|
||||
time.Sleep(time.Duration(vs.pulseSeconds) * time.Second)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) doHeartbeat(sleepInterval time.Duration) error {
|
||||
|
||||
vs.masterNodes.Reset()
|
||||
masterNode, err := vs.masterNodes.FindMaster()
|
||||
if err != nil {
|
||||
return fmt.Errorf("No master found: %v", err)
|
||||
}
|
||||
|
||||
grpcConection, err := grpc.Dial(masterNode, grpc.WithInsecure())
|
||||
if err != nil {
|
||||
return fmt.Errorf("fail to dial: %v", err)
|
||||
}
|
||||
defer grpcConection.Close()
|
||||
|
||||
client := pb.NewSeaweedClient(grpcConection)
|
||||
stream, err := client.SendHeartbeat(context.Background())
|
||||
if err != nil {
|
||||
glog.V(0).Infof("%v.SendHeartbeat(_) = _, %v", client, err)
|
||||
return err
|
||||
}
|
||||
vs.SetMasterNode(masterNode)
|
||||
glog.V(0).Infof("Heartbeat to %s", masterNode)
|
||||
|
||||
vs.store.Client = stream
|
||||
defer func() { vs.store.Client = nil }()
|
||||
|
||||
doneChan := make(chan error, 1)
|
||||
|
||||
go func() {
|
||||
for {
|
||||
in, err := stream.Recv()
|
||||
if err != nil {
|
||||
doneChan <- err
|
||||
return
|
||||
}
|
||||
if in.GetVolumeSizeLimit() != 0 {
|
||||
vs.store.VolumeSizeLimit = in.GetVolumeSizeLimit()
|
||||
}
|
||||
if in.GetSecretKey() != "" {
|
||||
vs.guard.SecretKey = security.Secret(in.GetSecretKey())
|
||||
}
|
||||
if in.GetLeader() != "" && masterNode != in.GetLeader() {
|
||||
vs.masterNodes.SetPossibleLeader(in.GetLeader())
|
||||
doneChan <- nil
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
if err = stream.Send(vs.store.CollectHeartbeat()); err != nil {
|
||||
glog.V(0).Infof("Volume Server Failed to talk with master %s: %v", masterNode, err)
|
||||
return err
|
||||
}
|
||||
|
||||
tickChan := time.Tick(sleepInterval)
|
||||
|
||||
for {
|
||||
select {
|
||||
case <-tickChan:
|
||||
if err = stream.Send(vs.store.CollectHeartbeat()); err != nil {
|
||||
glog.V(0).Infof("Volume Server Failed to talk with master %s: %v", masterNode, err)
|
||||
return err
|
||||
}
|
||||
case err := <-doneChan:
|
||||
glog.V(0).Infof("Volume Server heart beat stops with %v", err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,10 +1,8 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"math/rand"
|
||||
"net/http"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/security"
|
||||
@@ -19,6 +17,7 @@ type VolumeServer struct {
|
||||
rack string
|
||||
store *storage.Store
|
||||
guard *security.Guard
|
||||
masterNodes *storage.MasterNodes
|
||||
|
||||
needleMapKind storage.NeedleMapType
|
||||
FixJpgOrientation bool
|
||||
@@ -59,6 +58,9 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string,
|
||||
adminMux.HandleFunc("/admin/sync/status", vs.guard.WhiteList(vs.getVolumeSyncStatusHandler))
|
||||
adminMux.HandleFunc("/admin/sync/index", vs.guard.WhiteList(vs.getVolumeIndexContentHandler))
|
||||
adminMux.HandleFunc("/admin/sync/data", vs.guard.WhiteList(vs.getVolumeDataContentHandler))
|
||||
adminMux.HandleFunc("/admin/volume/mount", vs.guard.WhiteList(vs.getVolumeMountHandler))
|
||||
adminMux.HandleFunc("/admin/volume/unmount", vs.guard.WhiteList(vs.getVolumeUnmountHandler))
|
||||
adminMux.HandleFunc("/admin/volume/delete", vs.guard.WhiteList(vs.getVolumeDeleteHandler))
|
||||
adminMux.HandleFunc("/stats/counter", vs.guard.WhiteList(statsCounterHandler))
|
||||
adminMux.HandleFunc("/stats/memory", vs.guard.WhiteList(statsMemoryHandler))
|
||||
adminMux.HandleFunc("/stats/disk", vs.guard.WhiteList(vs.statsDiskHandler))
|
||||
@@ -70,36 +72,7 @@ func NewVolumeServer(adminMux, publicMux *http.ServeMux, ip string,
|
||||
publicMux.HandleFunc("/", vs.publicReadOnlyHandler)
|
||||
}
|
||||
|
||||
go func() {
|
||||
connected := true
|
||||
|
||||
glog.V(0).Infof("Volume server bootstraps with master %s", vs.GetMasterNode())
|
||||
vs.store.SetBootstrapMaster(vs.GetMasterNode())
|
||||
vs.store.SetDataCenter(vs.dataCenter)
|
||||
vs.store.SetRack(vs.rack)
|
||||
for {
|
||||
glog.V(4).Infof("Volume server sending to master %s", vs.GetMasterNode())
|
||||
master, secretKey, err := vs.store.SendHeartbeatToMaster()
|
||||
if err == nil {
|
||||
if !connected {
|
||||
connected = true
|
||||
vs.SetMasterNode(master)
|
||||
vs.guard.SecretKey = secretKey
|
||||
glog.V(0).Infoln("Volume Server Connected with master at", master)
|
||||
}
|
||||
} else {
|
||||
glog.V(1).Infof("Volume Server Failed to talk with master %s: %v", vs.masterNode, err)
|
||||
if connected {
|
||||
connected = false
|
||||
}
|
||||
}
|
||||
if connected {
|
||||
time.Sleep(time.Duration(float32(vs.pulseSeconds*1e3)*(1+rand.Float32())) * time.Millisecond)
|
||||
} else {
|
||||
time.Sleep(time.Duration(float32(vs.pulseSeconds*1e3)*0.25) * time.Millisecond)
|
||||
}
|
||||
}
|
||||
}()
|
||||
go vs.heartbeat()
|
||||
|
||||
return vs
|
||||
}
|
||||
|
||||
@@ -1,12 +1,15 @@
|
||||
package weed_server
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/stats"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
)
|
||||
|
||||
func (vs *VolumeServer) statusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -17,13 +20,29 @@ func (vs *VolumeServer) statusHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) assignVolumeHandler(w http.ResponseWriter, r *http.Request) {
|
||||
err := vs.store.AddVolume(r.FormValue("volume"), r.FormValue("collection"), vs.needleMapKind, r.FormValue("replication"), r.FormValue("ttl"))
|
||||
var err error
|
||||
preallocate := int64(0)
|
||||
if r.FormValue("preallocate") != "" {
|
||||
preallocate, err = strconv.ParseInt(r.FormValue("preallocate"), 10, 64)
|
||||
if err != nil {
|
||||
glog.V(0).Infoln("ignoring invalid int64 value for preallocate = %v", r.FormValue("preallocate"))
|
||||
}
|
||||
}
|
||||
err = vs.store.AddVolume(
|
||||
r.FormValue("volume"),
|
||||
r.FormValue("collection"),
|
||||
vs.needleMapKind,
|
||||
r.FormValue("replication"),
|
||||
r.FormValue("ttl"),
|
||||
preallocate,
|
||||
)
|
||||
if err == nil {
|
||||
writeJsonQuiet(w, r, http.StatusAccepted, map[string]string{"error": ""})
|
||||
} else {
|
||||
writeJsonError(w, r, http.StatusNotAcceptable, err)
|
||||
}
|
||||
glog.V(2).Infoln("assign volume =", r.FormValue("volume"), ", collection =", r.FormValue("collection"), ", replication =", r.FormValue("replication"), ", error =", err)
|
||||
glog.V(2).Infoln("assign volume = %s, collection = %s , replication = %s, error = %v",
|
||||
r.FormValue("volume"), r.FormValue("collection"), r.FormValue("replication"), err)
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) deleteCollectionHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -33,7 +52,7 @@ func (vs *VolumeServer) deleteCollectionHandler(w http.ResponseWriter, r *http.R
|
||||
} else {
|
||||
writeJsonError(w, r, http.StatusInternalServerError, err)
|
||||
}
|
||||
glog.V(2).Infoln("deleting collection =", r.FormValue("collection"), ", error =", err)
|
||||
glog.V(2).Infof("deleting collection = %s, error = %v", r.FormValue("collection"), err)
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) statsDiskHandler(w http.ResponseWriter, r *http.Request) {
|
||||
@@ -48,3 +67,45 @@ func (vs *VolumeServer) statsDiskHandler(w http.ResponseWriter, r *http.Request)
|
||||
m["DiskStatuses"] = ds
|
||||
writeJsonQuiet(w, r, http.StatusOK, m)
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) getVolume(volumeParameterName string, r *http.Request) (*storage.Volume, error) {
|
||||
vid, err := vs.getVolumeId(volumeParameterName, r)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
v := vs.store.GetVolume(vid)
|
||||
if v == nil {
|
||||
return nil, fmt.Errorf("Not Found Volume Id %d", vid)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) getVolumeMountHandler(w http.ResponseWriter, r *http.Request) {
|
||||
vid, err := vs.getVolumeId("volume", r)
|
||||
if err != nil {
|
||||
writeJsonError(w, r, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
vs.store.MountVolume(vid)
|
||||
writeJsonQuiet(w, r, http.StatusOK, "Volume mounted")
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) getVolumeUnmountHandler(w http.ResponseWriter, r *http.Request) {
|
||||
vid, err := vs.getVolumeId("volume", r)
|
||||
if err != nil {
|
||||
writeJsonError(w, r, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
vs.store.UnmountVolume(vid)
|
||||
writeJsonQuiet(w, r, http.StatusOK, "Volume unmounted")
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) getVolumeDeleteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
vid, err := vs.getVolumeId("volume", r)
|
||||
if err != nil {
|
||||
writeJsonError(w, r, http.StatusNotFound, err)
|
||||
return
|
||||
}
|
||||
vs.store.DeleteVolume(vid)
|
||||
writeJsonQuiet(w, r, http.StatusOK, "Volume deleted")
|
||||
}
|
||||
@@ -12,6 +12,8 @@ import (
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"encoding/json"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/images"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
@@ -65,7 +67,7 @@ func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
|
||||
cookie := n.Cookie
|
||||
count, e := vs.store.ReadVolumeNeedle(volumeId, n)
|
||||
glog.V(4).Infoln("read bytes", count, "error", e)
|
||||
if e != nil || count <= 0 {
|
||||
if e != nil || count < 0 {
|
||||
glog.V(0).Infoln("read error:", e, r.URL.Path)
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
return
|
||||
@@ -94,6 +96,17 @@ func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
w.Header().Set("Etag", etag)
|
||||
|
||||
if n.HasPairs() {
|
||||
pairMap := make(map[string]string)
|
||||
err = json.Unmarshal(n.Pairs, &pairMap)
|
||||
if err != nil {
|
||||
glog.V(0).Infoln("Unmarshal pairs error:", err)
|
||||
}
|
||||
for k, v := range pairMap {
|
||||
w.Header().Set(k, v)
|
||||
}
|
||||
}
|
||||
|
||||
if vs.tryHandleChunkedFile(n, filename, w, r) {
|
||||
return
|
||||
}
|
||||
@@ -131,7 +144,7 @@ func (vs *VolumeServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request)
|
||||
if r.FormValue("height") != "" {
|
||||
height, _ = strconv.Atoi(r.FormValue("height"))
|
||||
}
|
||||
n.Data, _, _ = images.Resized(ext, n.Data, width, height)
|
||||
n.Data, _, _ = images.Resized(ext, n.Data, width, height, r.FormValue("mode"))
|
||||
}
|
||||
|
||||
if e := writeResponseContent(filename, mtype, bytes.NewReader(n.Data), w, r); e != nil {
|
||||
@@ -152,7 +165,7 @@ func (vs *VolumeServer) FaviconHandler(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) tryHandleChunkedFile(n *storage.Needle, fileName string, w http.ResponseWriter, r *http.Request) (processed bool) {
|
||||
if !n.IsChunkedManifest() {
|
||||
if !n.IsChunkedManifest() || r.URL.Query().Get("cm") == "false" {
|
||||
return false
|
||||
}
|
||||
|
||||
|
||||
@@ -68,20 +68,19 @@ func (vs *VolumeServer) getVolumeDataContentHandler(w http.ResponseWriter, r *ht
|
||||
w.Write(content)
|
||||
}
|
||||
|
||||
func (vs *VolumeServer) getVolume(volumeParameterName string, r *http.Request) (*storage.Volume, error) {
|
||||
func (vs *VolumeServer) getVolumeId(volumeParameterName string, r *http.Request) (storage.VolumeId, error) {
|
||||
volumeIdString := r.FormValue(volumeParameterName)
|
||||
|
||||
if volumeIdString == "" {
|
||||
err := fmt.Errorf("Empty Volume Id: Need to pass in %s=the_volume_id.", volumeParameterName)
|
||||
return nil, err
|
||||
return 0, err
|
||||
}
|
||||
|
||||
vid, err := storage.NewVolumeId(volumeIdString)
|
||||
if err != nil {
|
||||
err = fmt.Errorf("Volume Id %s is not a valid unsigned integer", volumeIdString)
|
||||
return nil, err
|
||||
return 0, err
|
||||
}
|
||||
v := vs.store.GetVolume(vid)
|
||||
if v == nil {
|
||||
return nil, fmt.Errorf("Not Found Volume Id %s: %d", volumeIdString, vid)
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
|
||||
return vid, err
|
||||
}
|
||||
@@ -39,14 +39,13 @@ func NewCompactSection(start Key) *CompactSection {
|
||||
}
|
||||
|
||||
//return old entry size
|
||||
func (cs *CompactSection) Set(key Key, offset uint32, size uint32) uint32 {
|
||||
ret := uint32(0)
|
||||
func (cs *CompactSection) Set(key Key, offset, size uint32) (oldOffset, oldSize uint32) {
|
||||
cs.Lock()
|
||||
if key > cs.end {
|
||||
cs.end = key
|
||||
}
|
||||
if i := cs.binarySearchValues(key); i >= 0 {
|
||||
ret = cs.values[i].Size
|
||||
oldOffset, oldSize = cs.values[i].Offset, cs.values[i].Size
|
||||
//println("key", key, "old size", ret)
|
||||
cs.values[i].Offset, cs.values[i].Size = offset, size
|
||||
} else {
|
||||
@@ -55,7 +54,7 @@ func (cs *CompactSection) Set(key Key, offset uint32, size uint32) uint32 {
|
||||
if needOverflow {
|
||||
//println("start", cs.start, "counter", cs.counter, "key", key)
|
||||
if oldValue, found := cs.overflow[key]; found {
|
||||
ret = oldValue.Size
|
||||
oldOffset, oldSize = oldValue.Offset, oldValue.Size
|
||||
}
|
||||
cs.overflow[key] = NeedleValue{Key: key, Offset: offset, Size: size}
|
||||
} else {
|
||||
@@ -66,7 +65,7 @@ func (cs *CompactSection) Set(key Key, offset uint32, size uint32) uint32 {
|
||||
}
|
||||
}
|
||||
cs.Unlock()
|
||||
return ret
|
||||
return
|
||||
}
|
||||
|
||||
//return old entry size
|
||||
@@ -129,7 +128,7 @@ func NewCompactMap() CompactMap {
|
||||
return CompactMap{}
|
||||
}
|
||||
|
||||
func (cm *CompactMap) Set(key Key, offset uint32, size uint32) uint32 {
|
||||
func (cm *CompactMap) Set(key Key, offset, size uint32) (oldOffset, oldSize uint32) {
|
||||
x := cm.binarySearchCompactSection(key)
|
||||
if x < 0 {
|
||||
//println(x, "creating", len(cm.list), "section, starting", key)
|
||||
|
||||
@@ -6,6 +6,8 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
|
||||
"fmt"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
@@ -22,7 +24,7 @@ func NewDiskLocation(dir string, maxVolumeCount int) *DiskLocation {
|
||||
return location
|
||||
}
|
||||
|
||||
func (l *DiskLocation) loadExistingVolume(dir os.FileInfo, needleMapKind NeedleMapType, mutex *sync.RWMutex) {
|
||||
func (l *DiskLocation) volumeIdFromPath(dir os.FileInfo) (VolumeId, string, error) {
|
||||
name := dir.Name()
|
||||
if !dir.IsDir() && strings.HasSuffix(name, ".dat") {
|
||||
collection := ""
|
||||
@@ -31,16 +33,28 @@ func (l *DiskLocation) loadExistingVolume(dir os.FileInfo, needleMapKind NeedleM
|
||||
if i > 0 {
|
||||
collection, base = base[0:i], base[i+1:]
|
||||
}
|
||||
if vid, err := NewVolumeId(base); err == nil {
|
||||
vol, err := NewVolumeId(base)
|
||||
return vol, collection, err
|
||||
}
|
||||
|
||||
return 0, "", fmt.Errorf("Path is not a volume: %s", name)
|
||||
}
|
||||
|
||||
func (l *DiskLocation) loadExistingVolume(dir os.FileInfo, needleMapKind NeedleMapType, mutex *sync.RWMutex) {
|
||||
name := dir.Name()
|
||||
if !dir.IsDir() && strings.HasSuffix(name, ".dat") {
|
||||
vid, collection, err := l.volumeIdFromPath(dir)
|
||||
if err == nil {
|
||||
mutex.RLock()
|
||||
_, found := l.volumes[vid]
|
||||
mutex.RUnlock()
|
||||
if !found {
|
||||
if v, e := NewVolume(l.Directory, collection, vid, needleMapKind, nil, nil); e == nil {
|
||||
if v, e := NewVolume(l.Directory, collection, vid, needleMapKind, nil, nil, 0); e == nil {
|
||||
mutex.Lock()
|
||||
l.volumes[vid] = v
|
||||
mutex.Unlock()
|
||||
glog.V(0).Infof("data file %s, replicaPlacement=%s v=%d size=%d ttl=%s", l.Directory+"/"+name, v.ReplicaPlacement, v.Version(), v.Size(), v.Ttl.String())
|
||||
glog.V(0).Infof("data file %s, replicaPlacement=%s v=%d size=%d ttl=%s",
|
||||
l.Directory+"/"+name, v.ReplicaPlacement, v.Version(), v.Size(), v.Ttl.String())
|
||||
} else {
|
||||
glog.V(0).Infof("new volume %s error %s", name, e)
|
||||
}
|
||||
@@ -120,6 +134,44 @@ func (l *DiskLocation) deleteVolumeById(vid VolumeId) (e error) {
|
||||
return
|
||||
}
|
||||
|
||||
func (l *DiskLocation) LoadVolume(vid VolumeId, needleMapKind NeedleMapType) bool {
|
||||
if dirs, err := ioutil.ReadDir(l.Directory); err == nil {
|
||||
for _, dir := range dirs {
|
||||
volId, _, err := l.volumeIdFromPath(dir)
|
||||
if vid == volId && err == nil {
|
||||
var mutex sync.RWMutex
|
||||
l.loadExistingVolume(dir, needleMapKind, &mutex)
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
func (l *DiskLocation) DeleteVolume(vid VolumeId) error {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
_, ok := l.volumes[vid]
|
||||
if !ok {
|
||||
return fmt.Errorf("Volume not found, VolumeId: %d", vid)
|
||||
}
|
||||
return l.deleteVolumeById(vid)
|
||||
}
|
||||
|
||||
func (l *DiskLocation) UnloadVolume(vid VolumeId) error {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
_, ok := l.volumes[vid]
|
||||
if !ok {
|
||||
return fmt.Errorf("Volume not loaded, VolumeId: %d", vid)
|
||||
}
|
||||
delete(l.volumes, vid)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (l *DiskLocation) SetVolume(vid VolumeId, volume *Volume) {
|
||||
l.Lock()
|
||||
defer l.Unlock()
|
||||
|
||||
+39
-8
@@ -1,8 +1,10 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io/ioutil"
|
||||
"math"
|
||||
"mime"
|
||||
"net/http"
|
||||
"path"
|
||||
@@ -20,6 +22,8 @@ const (
|
||||
NeedlePaddingSize = 8
|
||||
NeedleChecksumSize = 4
|
||||
MaxPossibleVolumeSize = 4 * 1024 * 1024 * 1024 * 8
|
||||
TombstoneFileSize = math.MaxUint32
|
||||
PairNamePrefix = "Seaweed-"
|
||||
)
|
||||
|
||||
/*
|
||||
@@ -38,6 +42,8 @@ type Needle struct {
|
||||
Name []byte `comment:"maximum 256 characters"` //version2
|
||||
MimeSize uint8 //version2
|
||||
Mime []byte `comment:"maximum 256 characters"` //version2
|
||||
PairsSize uint16 //version2
|
||||
Pairs []byte `comment:"additional name value pairs, json format, maximum 64kB"`
|
||||
LastModified uint64 //only store LastModifiedBytesLength bytes, which is 5 bytes to disk
|
||||
Ttl *TTL
|
||||
|
||||
@@ -53,8 +59,15 @@ func (n *Needle) String() (str string) {
|
||||
}
|
||||
|
||||
func ParseUpload(r *http.Request) (
|
||||
fileName string, data []byte, mimeType string, isGzipped bool,
|
||||
fileName string, data []byte, mimeType string, pairMap map[string]string, isGzipped bool,
|
||||
modifiedTime uint64, ttl *TTL, isChunkedFile bool, e error) {
|
||||
pairMap = make(map[string]string)
|
||||
for k, v := range r.Header {
|
||||
if len(v) > 0 && strings.HasPrefix(k, PairNamePrefix) {
|
||||
pairMap[k] = v[0]
|
||||
}
|
||||
}
|
||||
|
||||
form, fe := r.MultipartReader()
|
||||
if fe != nil {
|
||||
glog.V(0).Infoln("MultipartReader [ERROR]", fe)
|
||||
@@ -107,8 +120,9 @@ func ParseUpload(r *http.Request) (
|
||||
}
|
||||
|
||||
isChunkedFile, _ = strconv.ParseBool(r.FormValue("cm"))
|
||||
isGzipped = false
|
||||
|
||||
if !isChunkedFile {
|
||||
|
||||
dotIndex := strings.LastIndex(fileName, ".")
|
||||
ext, mtype := "", ""
|
||||
if dotIndex > 0 {
|
||||
@@ -120,6 +134,7 @@ func ParseUpload(r *http.Request) (
|
||||
mimeType = contentType //only return mime type if not deductable
|
||||
mtype = contentType
|
||||
}
|
||||
|
||||
if part.Header.Get("Content-Encoding") == "gzip" {
|
||||
isGzipped = true
|
||||
} else if operation.IsGzippable(ext, mtype) {
|
||||
@@ -129,11 +144,13 @@ func ParseUpload(r *http.Request) (
|
||||
isGzipped = true
|
||||
}
|
||||
if ext == ".gz" {
|
||||
isGzipped = true
|
||||
}
|
||||
if strings.HasSuffix(fileName, ".gz") &&
|
||||
!strings.HasSuffix(fileName, ".tar.gz") {
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
if strings.HasSuffix(fileName, ".css.gz") ||
|
||||
strings.HasSuffix(fileName, ".html.gz") ||
|
||||
strings.HasSuffix(fileName, ".txt.gz") ||
|
||||
strings.HasSuffix(fileName, ".js.gz") {
|
||||
fileName = fileName[:len(fileName)-3]
|
||||
isGzipped = true
|
||||
}
|
||||
}
|
||||
}
|
||||
modifiedTime, _ = strconv.ParseUint(r.FormValue("ts"), 10, 64)
|
||||
@@ -142,9 +159,10 @@ func ParseUpload(r *http.Request) (
|
||||
return
|
||||
}
|
||||
func NewNeedle(r *http.Request, fixJpgOrientation bool) (n *Needle, e error) {
|
||||
var pairMap map[string]string
|
||||
fname, mimeType, isGzipped, isChunkedFile := "", "", false, false
|
||||
n = new(Needle)
|
||||
fname, n.Data, mimeType, isGzipped, n.LastModified, n.Ttl, isChunkedFile, e = ParseUpload(r)
|
||||
fname, n.Data, mimeType, pairMap, isGzipped, n.LastModified, n.Ttl, isChunkedFile, e = ParseUpload(r)
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
@@ -156,6 +174,19 @@ func NewNeedle(r *http.Request, fixJpgOrientation bool) (n *Needle, e error) {
|
||||
n.Mime = []byte(mimeType)
|
||||
n.SetHasMime()
|
||||
}
|
||||
if len(pairMap) != 0 {
|
||||
trimmedPairMap := make(map[string]string)
|
||||
for k, v := range pairMap {
|
||||
trimmedPairMap[k[len(PairNamePrefix):]] = v
|
||||
}
|
||||
|
||||
pairs, _ := json.Marshal(trimmedPairMap)
|
||||
if len(pairs) < 65536 {
|
||||
n.Pairs = pairs
|
||||
n.PairsSize = uint16(len(pairs))
|
||||
n.SetHasPairs()
|
||||
}
|
||||
}
|
||||
if isGzipped {
|
||||
n.SetGzipped()
|
||||
}
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
package needle
|
||||
|
||||
import (
|
||||
"github.com/google/btree"
|
||||
)
|
||||
|
||||
//This map assumes mostly inserting increasing keys
|
||||
type BtreeMap struct {
|
||||
tree *btree.BTree
|
||||
}
|
||||
|
||||
func NewBtreeMap() *BtreeMap {
|
||||
return &BtreeMap{
|
||||
tree: btree.New(32),
|
||||
}
|
||||
}
|
||||
|
||||
func (cm *BtreeMap) Set(key Key, offset, size uint32) (oldOffset, oldSize uint32) {
|
||||
found := cm.tree.ReplaceOrInsert(NeedleValue{key, offset, size})
|
||||
if found != nil {
|
||||
old := found.(NeedleValue)
|
||||
return old.Offset, old.Size
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
func (cm *BtreeMap) Delete(key Key) (oldSize uint32) {
|
||||
found := cm.tree.Delete(NeedleValue{key, 0, 0})
|
||||
if found != nil {
|
||||
old := found.(NeedleValue)
|
||||
return old.Size
|
||||
}
|
||||
return
|
||||
}
|
||||
func (cm *BtreeMap) Get(key Key) (*NeedleValue, bool) {
|
||||
found := cm.tree.Get(NeedleValue{key, 0, 0})
|
||||
if found != nil {
|
||||
old := found.(NeedleValue)
|
||||
return &old, true
|
||||
}
|
||||
return nil, false
|
||||
}
|
||||
|
||||
// Visit visits all entries or stop if any error when visiting
|
||||
func (cm *BtreeMap) Visit(visit func(NeedleValue) error) (ret error) {
|
||||
cm.tree.Ascend(func(item btree.Item) bool {
|
||||
needle := item.(NeedleValue)
|
||||
ret = visit(needle)
|
||||
return ret == nil
|
||||
})
|
||||
return ret
|
||||
}
|
||||
@@ -0,0 +1,194 @@
|
||||
package needle
|
||||
|
||||
import (
|
||||
"sync"
|
||||
)
|
||||
|
||||
type CompactSection struct {
|
||||
sync.RWMutex
|
||||
values []NeedleValue
|
||||
overflow map[Key]NeedleValue
|
||||
start Key
|
||||
end Key
|
||||
counter int
|
||||
}
|
||||
|
||||
func NewCompactSection(start Key) *CompactSection {
|
||||
return &CompactSection{
|
||||
values: make([]NeedleValue, batch),
|
||||
overflow: make(map[Key]NeedleValue),
|
||||
start: start,
|
||||
}
|
||||
}
|
||||
|
||||
//return old entry size
|
||||
func (cs *CompactSection) Set(key Key, offset, size uint32) (oldOffset, oldSize uint32) {
|
||||
cs.Lock()
|
||||
if key > cs.end {
|
||||
cs.end = key
|
||||
}
|
||||
if i := cs.binarySearchValues(key); i >= 0 {
|
||||
oldOffset, oldSize = cs.values[i].Offset, cs.values[i].Size
|
||||
//println("key", key, "old size", ret)
|
||||
cs.values[i].Offset, cs.values[i].Size = offset, size
|
||||
} else {
|
||||
needOverflow := cs.counter >= batch
|
||||
needOverflow = needOverflow || cs.counter > 0 && cs.values[cs.counter-1].Key > key
|
||||
if needOverflow {
|
||||
//println("start", cs.start, "counter", cs.counter, "key", key)
|
||||
if oldValue, found := cs.overflow[key]; found {
|
||||
oldOffset, oldSize = oldValue.Offset, oldValue.Size
|
||||
}
|
||||
cs.overflow[key] = NeedleValue{Key: key, Offset: offset, Size: size}
|
||||
} else {
|
||||
p := &cs.values[cs.counter]
|
||||
p.Key, p.Offset, p.Size = key, offset, size
|
||||
//println("added index", cs.counter, "key", key, cs.values[cs.counter].Key)
|
||||
cs.counter++
|
||||
}
|
||||
}
|
||||
cs.Unlock()
|
||||
return
|
||||
}
|
||||
|
||||
//return old entry size
|
||||
func (cs *CompactSection) Delete(key Key) uint32 {
|
||||
cs.Lock()
|
||||
ret := uint32(0)
|
||||
if i := cs.binarySearchValues(key); i >= 0 {
|
||||
if cs.values[i].Size > 0 {
|
||||
ret = cs.values[i].Size
|
||||
cs.values[i].Size = 0
|
||||
}
|
||||
}
|
||||
if v, found := cs.overflow[key]; found {
|
||||
delete(cs.overflow, key)
|
||||
ret = v.Size
|
||||
}
|
||||
cs.Unlock()
|
||||
return ret
|
||||
}
|
||||
func (cs *CompactSection) Get(key Key) (*NeedleValue, bool) {
|
||||
cs.RLock()
|
||||
if v, ok := cs.overflow[key]; ok {
|
||||
cs.RUnlock()
|
||||
return &v, true
|
||||
}
|
||||
if i := cs.binarySearchValues(key); i >= 0 {
|
||||
cs.RUnlock()
|
||||
return &cs.values[i], true
|
||||
}
|
||||
cs.RUnlock()
|
||||
return nil, false
|
||||
}
|
||||
func (cs *CompactSection) binarySearchValues(key Key) int {
|
||||
l, h := 0, cs.counter-1
|
||||
if h >= 0 && cs.values[h].Key < key {
|
||||
return -2
|
||||
}
|
||||
//println("looking for key", key)
|
||||
for l <= h {
|
||||
m := (l + h) / 2
|
||||
//println("mid", m, "key", cs.values[m].Key, cs.values[m].Offset, cs.values[m].Size)
|
||||
if cs.values[m].Key < key {
|
||||
l = m + 1
|
||||
} else if key < cs.values[m].Key {
|
||||
h = m - 1
|
||||
} else {
|
||||
//println("found", m)
|
||||
return m
|
||||
}
|
||||
}
|
||||
return -1
|
||||
}
|
||||
|
||||
//This map assumes mostly inserting increasing keys
|
||||
//This map assumes mostly inserting increasing keys
|
||||
type CompactMap struct {
|
||||
list []*CompactSection
|
||||
}
|
||||
|
||||
func NewCompactMap() *CompactMap {
|
||||
return &CompactMap{}
|
||||
}
|
||||
|
||||
func (cm *CompactMap) Set(key Key, offset, size uint32) (oldOffset, oldSize uint32) {
|
||||
x := cm.binarySearchCompactSection(key)
|
||||
if x < 0 {
|
||||
//println(x, "creating", len(cm.list), "section, starting", key)
|
||||
cm.list = append(cm.list, NewCompactSection(key))
|
||||
x = len(cm.list) - 1
|
||||
//keep compact section sorted by start
|
||||
for x > 0 {
|
||||
if cm.list[x-1].start > cm.list[x].start {
|
||||
cm.list[x-1], cm.list[x] = cm.list[x], cm.list[x-1]
|
||||
x = x - 1
|
||||
} else {
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return cm.list[x].Set(key, offset, size)
|
||||
}
|
||||
func (cm *CompactMap) Delete(key Key) uint32 {
|
||||
x := cm.binarySearchCompactSection(key)
|
||||
if x < 0 {
|
||||
return uint32(0)
|
||||
}
|
||||
return cm.list[x].Delete(key)
|
||||
}
|
||||
func (cm *CompactMap) Get(key Key) (*NeedleValue, bool) {
|
||||
x := cm.binarySearchCompactSection(key)
|
||||
if x < 0 {
|
||||
return nil, false
|
||||
}
|
||||
return cm.list[x].Get(key)
|
||||
}
|
||||
func (cm *CompactMap) binarySearchCompactSection(key Key) int {
|
||||
l, h := 0, len(cm.list)-1
|
||||
if h < 0 {
|
||||
return -5
|
||||
}
|
||||
if cm.list[h].start <= key {
|
||||
if cm.list[h].counter < batch || key <= cm.list[h].end {
|
||||
return h
|
||||
}
|
||||
return -4
|
||||
}
|
||||
for l <= h {
|
||||
m := (l + h) / 2
|
||||
if key < cm.list[m].start {
|
||||
h = m - 1
|
||||
} else { // cm.list[m].start <= key
|
||||
if cm.list[m+1].start <= key {
|
||||
l = m + 1
|
||||
} else {
|
||||
return m
|
||||
}
|
||||
}
|
||||
}
|
||||
return -3
|
||||
}
|
||||
|
||||
// Visit visits all entries or stop if any error when visiting
|
||||
func (cm *CompactMap) Visit(visit func(NeedleValue) error) error {
|
||||
for _, cs := range cm.list {
|
||||
cs.RLock()
|
||||
for _, v := range cs.overflow {
|
||||
if err := visit(v); err != nil {
|
||||
cs.RUnlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
for _, v := range cs.values {
|
||||
if _, found := cs.overflow[v.Key]; !found {
|
||||
if err := visit(v); err != nil {
|
||||
cs.RUnlock()
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
cs.RUnlock()
|
||||
}
|
||||
return nil
|
||||
}
|
||||
+4
-5
@@ -1,4 +1,4 @@
|
||||
package storage
|
||||
package needle
|
||||
|
||||
import (
|
||||
"log"
|
||||
@@ -11,15 +11,15 @@ import (
|
||||
|
||||
func TestMemoryUsage(t *testing.T) {
|
||||
|
||||
indexFile, ie := os.OpenFile("../../test/sample.idx", os.O_RDWR|os.O_RDONLY, 0644)
|
||||
indexFile, ie := os.OpenFile("../../../test/sample.idx", os.O_RDWR|os.O_RDONLY, 0644)
|
||||
if ie != nil {
|
||||
log.Fatalln(ie)
|
||||
}
|
||||
LoadNewNeedleMap(indexFile)
|
||||
loadNewNeedleMap(indexFile)
|
||||
|
||||
}
|
||||
|
||||
func LoadNewNeedleMap(file *os.File) CompactMap {
|
||||
func loadNewNeedleMap(file *os.File) {
|
||||
m := NewCompactMap()
|
||||
bytes := make([]byte, 16*1024)
|
||||
count, e := file.Read(bytes)
|
||||
@@ -41,5 +41,4 @@ func LoadNewNeedleMap(file *os.File) CompactMap {
|
||||
|
||||
count, e = file.Read(bytes)
|
||||
}
|
||||
return m
|
||||
}
|
||||
@@ -1,4 +1,4 @@
|
||||
package storage
|
||||
package needle
|
||||
|
||||
import (
|
||||
"testing"
|
||||
@@ -0,0 +1,28 @@
|
||||
package needle
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
|
||||
"github.com/google/btree"
|
||||
)
|
||||
|
||||
const (
|
||||
batch = 100000
|
||||
)
|
||||
|
||||
type NeedleValue struct {
|
||||
Key Key
|
||||
Offset uint32 `comment:"Volume offset"` //since aligned to 8 bytes, range is 4G*8=32G
|
||||
Size uint32 `comment:"Size of the data portion"`
|
||||
}
|
||||
|
||||
func (this NeedleValue) Less(than btree.Item) bool {
|
||||
that := than.(NeedleValue)
|
||||
return this.Key < that.Key
|
||||
}
|
||||
|
||||
type Key uint64
|
||||
|
||||
func (k Key) String() string {
|
||||
return strconv.FormatUint(uint64(k), 10)
|
||||
}
|
||||
@@ -0,0 +1,8 @@
|
||||
package needle
|
||||
|
||||
type NeedleValueMap interface {
|
||||
Set(key Key, offset, size uint32) (oldOffset, oldSize uint32)
|
||||
Delete(key Key) uint32
|
||||
Get(key Key) (*NeedleValue, bool)
|
||||
Visit(visit func(NeedleValue) error) error
|
||||
}
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"os"
|
||||
"sync"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/needle"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -15,6 +16,7 @@ const (
|
||||
NeedleMapInMemory NeedleMapType = iota
|
||||
NeedleMapLevelDb
|
||||
NeedleMapBoltDb
|
||||
NeedleMapBtree
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -23,8 +25,8 @@ const (
|
||||
|
||||
type NeedleMapper interface {
|
||||
Put(key uint64, offset uint32, size uint32) error
|
||||
Get(key uint64) (element *NeedleValue, ok bool)
|
||||
Delete(key uint64) error
|
||||
Get(key uint64) (element *needle.NeedleValue, ok bool)
|
||||
Delete(key uint64, offset uint32) error
|
||||
Close()
|
||||
Destroy() error
|
||||
ContentSize() uint64
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"github.com/boltdb/bolt"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/needle"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -31,7 +32,7 @@ func NewBoltDbNeedleMap(dbFileName string, indexFile *os.File) (m *BoltDbNeedleM
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Loading %s...", indexFile.Name())
|
||||
nm, indexLoadError := LoadNeedleMap(indexFile)
|
||||
nm, indexLoadError := LoadBtreeNeedleMap(indexFile)
|
||||
if indexLoadError != nil {
|
||||
return nil, indexLoadError
|
||||
}
|
||||
@@ -63,7 +64,7 @@ func generateBoltDbFile(dbFileName string, indexFile *os.File) error {
|
||||
}
|
||||
defer db.Close()
|
||||
return WalkIndexFile(indexFile, func(key uint64, offset, size uint32) error {
|
||||
if offset > 0 {
|
||||
if offset > 0 && size != TombstoneFileSize {
|
||||
boltDbWrite(db, key, offset, size)
|
||||
} else {
|
||||
boltDbDelete(db, key)
|
||||
@@ -72,7 +73,7 @@ func generateBoltDbFile(dbFileName string, indexFile *os.File) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (m *BoltDbNeedleMap) Get(key uint64) (element *NeedleValue, ok bool) {
|
||||
func (m *BoltDbNeedleMap) Get(key uint64) (element *needle.NeedleValue, ok bool) {
|
||||
bytes := make([]byte, 8)
|
||||
var data []byte
|
||||
util.Uint64toBytes(bytes, key)
|
||||
@@ -91,7 +92,7 @@ func (m *BoltDbNeedleMap) Get(key uint64) (element *NeedleValue, ok bool) {
|
||||
}
|
||||
offset := util.BytesToUint32(data[0:4])
|
||||
size := util.BytesToUint32(data[4:8])
|
||||
return &NeedleValue{Key: Key(key), Offset: offset, Size: size}, true
|
||||
return &needle.NeedleValue{Key: needle.Key(key), Offset: offset, Size: size}, true
|
||||
}
|
||||
|
||||
func (m *BoltDbNeedleMap) Put(key uint64, offset uint32, size uint32) error {
|
||||
@@ -143,12 +144,12 @@ func boltDbDelete(db *bolt.DB, key uint64) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (m *BoltDbNeedleMap) Delete(key uint64) error {
|
||||
func (m *BoltDbNeedleMap) Delete(key uint64, offset uint32) error {
|
||||
if oldNeedle, ok := m.Get(key); ok {
|
||||
m.logDelete(oldNeedle.Size)
|
||||
}
|
||||
// write to index file first
|
||||
if err := m.appendToIndexFile(key, 0, 0); err != nil {
|
||||
if err := m.appendToIndexFile(key, offset, TombstoneFileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
return boltDbDelete(m.db, key)
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"path/filepath"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/needle"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"github.com/syndtr/goleveldb/leveldb"
|
||||
)
|
||||
@@ -29,7 +30,7 @@ func NewLevelDbNeedleMap(dbFileName string, indexFile *os.File) (m *LevelDbNeedl
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("Loading %s...", indexFile.Name())
|
||||
nm, indexLoadError := LoadNeedleMap(indexFile)
|
||||
nm, indexLoadError := LoadBtreeNeedleMap(indexFile)
|
||||
if indexLoadError != nil {
|
||||
return nil, indexLoadError
|
||||
}
|
||||
@@ -61,7 +62,7 @@ func generateLevelDbFile(dbFileName string, indexFile *os.File) error {
|
||||
}
|
||||
defer db.Close()
|
||||
return WalkIndexFile(indexFile, func(key uint64, offset, size uint32) error {
|
||||
if offset > 0 {
|
||||
if offset > 0 && size != TombstoneFileSize {
|
||||
levelDbWrite(db, key, offset, size)
|
||||
} else {
|
||||
levelDbDelete(db, key)
|
||||
@@ -70,7 +71,7 @@ func generateLevelDbFile(dbFileName string, indexFile *os.File) error {
|
||||
})
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) Get(key uint64) (element *NeedleValue, ok bool) {
|
||||
func (m *LevelDbNeedleMap) Get(key uint64) (element *needle.NeedleValue, ok bool) {
|
||||
bytes := make([]byte, 8)
|
||||
util.Uint64toBytes(bytes, key)
|
||||
data, err := m.db.Get(bytes, nil)
|
||||
@@ -79,7 +80,7 @@ func (m *LevelDbNeedleMap) Get(key uint64) (element *NeedleValue, ok bool) {
|
||||
}
|
||||
offset := util.BytesToUint32(data[0:4])
|
||||
size := util.BytesToUint32(data[4:8])
|
||||
return &NeedleValue{Key: Key(key), Offset: offset, Size: size}, true
|
||||
return &needle.NeedleValue{Key: needle.Key(key), Offset: offset, Size: size}, true
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) Put(key uint64, offset uint32, size uint32) error {
|
||||
@@ -112,12 +113,12 @@ func levelDbDelete(db *leveldb.DB, key uint64) error {
|
||||
return db.Delete(bytes, nil)
|
||||
}
|
||||
|
||||
func (m *LevelDbNeedleMap) Delete(key uint64) error {
|
||||
func (m *LevelDbNeedleMap) Delete(key uint64, offset uint32) error {
|
||||
if oldNeedle, ok := m.Get(key); ok {
|
||||
m.logDelete(oldNeedle.Size)
|
||||
}
|
||||
// write to index file first
|
||||
if err := m.appendToIndexFile(key, 0, 0); err != nil {
|
||||
if err := m.appendToIndexFile(key, offset, TombstoneFileSize); err != nil {
|
||||
return err
|
||||
}
|
||||
return levelDbDelete(m.db, key)
|
||||
|
||||
@@ -5,17 +5,26 @@ import (
|
||||
"os"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/needle"
|
||||
)
|
||||
|
||||
type NeedleMap struct {
|
||||
m CompactMap
|
||||
m needle.NeedleValueMap
|
||||
|
||||
baseNeedleMapper
|
||||
}
|
||||
|
||||
func NewNeedleMap(file *os.File) *NeedleMap {
|
||||
func NewCompactNeedleMap(file *os.File) *NeedleMap {
|
||||
nm := &NeedleMap{
|
||||
m: NewCompactMap(),
|
||||
m: needle.NewCompactMap(),
|
||||
}
|
||||
nm.indexFile = file
|
||||
return nm
|
||||
}
|
||||
|
||||
func NewBtreeNeedleMap(file *os.File) *NeedleMap {
|
||||
nm := &NeedleMap{
|
||||
m: needle.NewBtreeMap(),
|
||||
}
|
||||
nm.indexFile = file
|
||||
return nm
|
||||
@@ -25,23 +34,32 @@ const (
|
||||
RowsToRead = 1024
|
||||
)
|
||||
|
||||
func LoadNeedleMap(file *os.File) (*NeedleMap, error) {
|
||||
nm := NewNeedleMap(file)
|
||||
func LoadCompactNeedleMap(file *os.File) (*NeedleMap, error) {
|
||||
nm := NewCompactNeedleMap(file)
|
||||
return doLoading(file, nm)
|
||||
}
|
||||
|
||||
func LoadBtreeNeedleMap(file *os.File) (*NeedleMap, error) {
|
||||
nm := NewBtreeNeedleMap(file)
|
||||
return doLoading(file, nm)
|
||||
}
|
||||
|
||||
func doLoading(file *os.File, nm *NeedleMap) (*NeedleMap, error) {
|
||||
e := WalkIndexFile(file, func(key uint64, offset, size uint32) error {
|
||||
if key > nm.MaximumFileKey {
|
||||
nm.MaximumFileKey = key
|
||||
}
|
||||
nm.FileCounter++
|
||||
nm.FileByteCounter = nm.FileByteCounter + uint64(size)
|
||||
if offset > 0 {
|
||||
oldSize := nm.m.Set(Key(key), offset, size)
|
||||
if offset > 0 && size != TombstoneFileSize {
|
||||
nm.FileCounter++
|
||||
nm.FileByteCounter = nm.FileByteCounter + uint64(size)
|
||||
oldOffset, oldSize := nm.m.Set(needle.Key(key), offset, size)
|
||||
glog.V(3).Infoln("reading key", key, "offset", offset*NeedlePaddingSize, "size", size, "oldSize", oldSize)
|
||||
if oldSize > 0 {
|
||||
if oldOffset > 0 && oldSize != TombstoneFileSize {
|
||||
nm.DeletionCounter++
|
||||
nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(oldSize)
|
||||
}
|
||||
} else {
|
||||
oldSize := nm.m.Delete(Key(key))
|
||||
oldSize := nm.m.Delete(needle.Key(key))
|
||||
glog.V(3).Infoln("removing key", key, "offset", offset*NeedlePaddingSize, "size", size, "oldSize", oldSize)
|
||||
nm.DeletionCounter++
|
||||
nm.DeletionByteCounter = nm.DeletionByteCounter + uint64(oldSize)
|
||||
@@ -84,18 +102,18 @@ func WalkIndexFile(r *os.File, fn func(key uint64, offset, size uint32) error) e
|
||||
}
|
||||
|
||||
func (nm *NeedleMap) Put(key uint64, offset uint32, size uint32) error {
|
||||
oldSize := nm.m.Set(Key(key), offset, size)
|
||||
_, oldSize := nm.m.Set(needle.Key(key), offset, size)
|
||||
nm.logPut(key, oldSize, size)
|
||||
return nm.appendToIndexFile(key, offset, size)
|
||||
}
|
||||
func (nm *NeedleMap) Get(key uint64) (element *NeedleValue, ok bool) {
|
||||
element, ok = nm.m.Get(Key(key))
|
||||
func (nm *NeedleMap) Get(key uint64) (element *needle.NeedleValue, ok bool) {
|
||||
element, ok = nm.m.Get(needle.Key(key))
|
||||
return
|
||||
}
|
||||
func (nm *NeedleMap) Delete(key uint64) error {
|
||||
deletedBytes := nm.m.Delete(Key(key))
|
||||
func (nm *NeedleMap) Delete(key uint64, offset uint32) error {
|
||||
deletedBytes := nm.m.Delete(needle.Key(key))
|
||||
nm.logDelete(deletedBytes)
|
||||
return nm.appendToIndexFile(key, 0, 0)
|
||||
return nm.appendToIndexFile(key, offset, TombstoneFileSize)
|
||||
}
|
||||
func (nm *NeedleMap) Close() {
|
||||
_ = nm.indexFile.Close()
|
||||
|
||||
@@ -16,16 +16,17 @@ const (
|
||||
FlagHasMime = 0x04
|
||||
FlagHasLastModifiedDate = 0x08
|
||||
FlagHasTtl = 0x10
|
||||
FlagHasPairs = 0x20
|
||||
FlagIsChunkManifest = 0x80
|
||||
LastModifiedBytesLength = 5
|
||||
TtlBytesLength = 2
|
||||
)
|
||||
|
||||
func (n *Needle) DiskSize() int64 {
|
||||
padding := NeedlePaddingSize - ((NeedleHeaderSize + int64(n.Size) + NeedleChecksumSize) % NeedlePaddingSize)
|
||||
return NeedleHeaderSize + int64(n.Size) + padding + NeedleChecksumSize
|
||||
return getActualSize(n.Size)
|
||||
}
|
||||
func (n *Needle) Append(w io.Writer, version Version) (size uint32, err error) {
|
||||
|
||||
func (n *Needle) Append(w io.Writer, version Version) (size uint32, actualSize int64, err error) {
|
||||
if s, ok := w.(io.Seeker); ok {
|
||||
if end, e := s.Seek(0, 1); e == nil {
|
||||
defer func(s io.Seeker, off int64) {
|
||||
@@ -54,6 +55,7 @@ func (n *Needle) Append(w io.Writer, version Version) (size uint32, err error) {
|
||||
if _, err = w.Write(n.Data); err != nil {
|
||||
return
|
||||
}
|
||||
actualSize = NeedleHeaderSize + int64(n.Size)
|
||||
padding := NeedlePaddingSize - ((NeedleHeaderSize + n.Size + NeedleChecksumSize) % NeedlePaddingSize)
|
||||
util.Uint32toBytes(header[0:NeedleChecksumSize], n.Checksum.Value())
|
||||
_, err = w.Write(header[0 : NeedleChecksumSize+padding])
|
||||
@@ -77,6 +79,9 @@ func (n *Needle) Append(w io.Writer, version Version) (size uint32, err error) {
|
||||
if n.HasTtl() {
|
||||
n.Size = n.Size + TtlBytesLength
|
||||
}
|
||||
if n.HasPairs() {
|
||||
n.Size += 2 + uint32(n.PairsSize)
|
||||
}
|
||||
} else {
|
||||
n.Size = 0
|
||||
}
|
||||
@@ -127,19 +132,27 @@ func (n *Needle) Append(w io.Writer, version Version) (size uint32, err error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
if n.HasPairs() {
|
||||
util.Uint16toBytes(header[0:2], n.PairsSize)
|
||||
if _, err = w.Write(header[0:2]); err != nil {
|
||||
return
|
||||
}
|
||||
if _, err = w.Write(n.Pairs); err != nil {
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
padding := NeedlePaddingSize - ((NeedleHeaderSize + n.Size + NeedleChecksumSize) % NeedlePaddingSize)
|
||||
util.Uint32toBytes(header[0:NeedleChecksumSize], n.Checksum.Value())
|
||||
_, err = w.Write(header[0 : NeedleChecksumSize+padding])
|
||||
return n.DataSize, err
|
||||
|
||||
return n.DataSize, getActualSize(n.Size), err
|
||||
}
|
||||
return 0, fmt.Errorf("Unsupported Version! (%d)", version)
|
||||
return 0, 0, fmt.Errorf("Unsupported Version! (%d)", version)
|
||||
}
|
||||
|
||||
func ReadNeedleBlob(r *os.File, offset int64, size uint32) (dataSlice []byte, block *Block, err error) {
|
||||
padding := NeedlePaddingSize - ((NeedleHeaderSize + size + NeedleChecksumSize) % NeedlePaddingSize)
|
||||
readSize := NeedleHeaderSize + size + NeedleChecksumSize + padding
|
||||
return getBytesForFileBlock(r, offset, int(readSize))
|
||||
return getBytesForFileBlock(r, offset, int(getActualSize(size)))
|
||||
}
|
||||
|
||||
func (n *Needle) ReadData(r *os.File, offset int64, size uint32, version Version) (err error) {
|
||||
@@ -209,6 +222,13 @@ func (n *Needle) readNeedleDataVersion2(bytes []byte) {
|
||||
n.Ttl = LoadTTLFromBytes(bytes[index : index+TtlBytesLength])
|
||||
index = index + TtlBytesLength
|
||||
}
|
||||
if index < lenBytes && n.HasPairs() {
|
||||
n.PairsSize = util.BytesToUint16(bytes[index : index+2])
|
||||
index += 2
|
||||
end := index + int(n.PairsSize)
|
||||
n.Pairs = bytes[index:end]
|
||||
index = end
|
||||
}
|
||||
}
|
||||
|
||||
func ReadNeedleHeader(r *os.File, version Version, offset int64) (n *Needle, bodyLength uint32, err error) {
|
||||
@@ -292,3 +312,11 @@ func (n *Needle) IsChunkedManifest() bool {
|
||||
func (n *Needle) SetIsChunkManifest() {
|
||||
n.Flags = n.Flags | FlagIsChunkManifest
|
||||
}
|
||||
|
||||
func (n *Needle) HasPairs() bool {
|
||||
return n.Flags&FlagHasPairs != 0
|
||||
}
|
||||
|
||||
func (n *Needle) SetHasPairs() {
|
||||
n.Flags = n.Flags | FlagHasPairs
|
||||
}
|
||||
+102
-98
@@ -1,18 +1,14 @@
|
||||
package storage
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/security"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
"github.com/golang/protobuf/proto"
|
||||
"github.com/chrislusf/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -20,49 +16,52 @@ const (
|
||||
)
|
||||
|
||||
type MasterNodes struct {
|
||||
nodes []string
|
||||
lastNode int
|
||||
nodes []string
|
||||
leader string
|
||||
possibleLeader string
|
||||
}
|
||||
|
||||
func (mn *MasterNodes) String() string {
|
||||
return fmt.Sprintf("nodes:%v, lastNode:%d", mn.nodes, mn.lastNode)
|
||||
return fmt.Sprintf("nodes:%v, leader:%s", mn.nodes, mn.leader)
|
||||
}
|
||||
|
||||
func NewMasterNodes(bootstrapNode string) (mn *MasterNodes) {
|
||||
mn = &MasterNodes{nodes: []string{bootstrapNode}, lastNode: -1}
|
||||
mn = &MasterNodes{nodes: []string{bootstrapNode}, leader: ""}
|
||||
return
|
||||
}
|
||||
func (mn *MasterNodes) Reset() {
|
||||
glog.V(4).Infof("Resetting master nodes: %v", mn)
|
||||
if len(mn.nodes) > 1 && mn.lastNode >= 0 {
|
||||
glog.V(0).Infof("Reset master %s from: %v", mn.nodes[mn.lastNode], mn.nodes)
|
||||
mn.lastNode = -mn.lastNode - 1
|
||||
if mn.leader != "" {
|
||||
mn.leader = ""
|
||||
glog.V(0).Infof("Resetting master nodes: %v", mn)
|
||||
}
|
||||
}
|
||||
func (mn *MasterNodes) FindMaster() (string, error) {
|
||||
func (mn *MasterNodes) SetPossibleLeader(possibleLeader string) {
|
||||
// TODO try to check this leader first
|
||||
mn.possibleLeader = possibleLeader
|
||||
}
|
||||
func (mn *MasterNodes) FindMaster() (leader string, err error) {
|
||||
if len(mn.nodes) == 0 {
|
||||
return "", errors.New("No master node found!")
|
||||
}
|
||||
if mn.lastNode < 0 {
|
||||
if mn.leader == "" {
|
||||
for _, m := range mn.nodes {
|
||||
glog.V(4).Infof("Listing masters on %s", m)
|
||||
if masters, e := operation.ListMasters(m); e == nil {
|
||||
if len(masters) == 0 {
|
||||
continue
|
||||
if leader, masters, e := operation.ListMasters(m); e == nil {
|
||||
if leader != "" {
|
||||
mn.nodes = append(masters, m)
|
||||
mn.leader = leader
|
||||
glog.V(2).Infof("current master nodes is %v", mn)
|
||||
break
|
||||
}
|
||||
mn.nodes = append(masters, m)
|
||||
mn.lastNode = rand.Intn(len(mn.nodes))
|
||||
glog.V(2).Infof("current master nodes is %v", mn)
|
||||
break
|
||||
} else {
|
||||
glog.V(4).Infof("Failed listing masters on %s: %v", m, e)
|
||||
}
|
||||
}
|
||||
}
|
||||
if mn.lastNode < 0 {
|
||||
if mn.leader == "" {
|
||||
return "", errors.New("No master node available!")
|
||||
}
|
||||
return mn.nodes[mn.lastNode], nil
|
||||
return mn.leader, nil
|
||||
}
|
||||
|
||||
/*
|
||||
@@ -76,17 +75,18 @@ type Store struct {
|
||||
dataCenter string //optional informaton, overwriting master setting if exists
|
||||
rack string //optional information, overwriting master setting if exists
|
||||
connected bool
|
||||
volumeSizeLimit uint64 //read from the master
|
||||
masterNodes *MasterNodes
|
||||
VolumeSizeLimit uint64 //read from the master
|
||||
Client pb.Seaweed_SendHeartbeatClient
|
||||
NeedleMapType NeedleMapType
|
||||
}
|
||||
|
||||
func (s *Store) String() (str string) {
|
||||
str = fmt.Sprintf("Ip:%s, Port:%d, PublicUrl:%s, dataCenter:%s, rack:%s, connected:%v, volumeSizeLimit:%d, masterNodes:%s", s.Ip, s.Port, s.PublicUrl, s.dataCenter, s.rack, s.connected, s.volumeSizeLimit, s.masterNodes)
|
||||
str = fmt.Sprintf("Ip:%s, Port:%d, PublicUrl:%s, dataCenter:%s, rack:%s, connected:%v, volumeSizeLimit:%d", s.Ip, s.Port, s.PublicUrl, s.dataCenter, s.rack, s.connected, s.VolumeSizeLimit)
|
||||
return
|
||||
}
|
||||
|
||||
func NewStore(port int, ip, publicUrl string, dirnames []string, maxVolumeCounts []int, needleMapKind NeedleMapType) (s *Store) {
|
||||
s = &Store{Port: port, Ip: ip, PublicUrl: publicUrl}
|
||||
s = &Store{Port: port, Ip: ip, PublicUrl: publicUrl, NeedleMapType: needleMapKind}
|
||||
s.Locations = make([]*DiskLocation, 0)
|
||||
for i := 0; i < len(dirnames); i++ {
|
||||
location := NewDiskLocation(dirnames[i], maxVolumeCounts[i])
|
||||
@@ -95,7 +95,7 @@ func NewStore(port int, ip, publicUrl string, dirnames []string, maxVolumeCounts
|
||||
}
|
||||
return
|
||||
}
|
||||
func (s *Store) AddVolume(volumeListString string, collection string, needleMapKind NeedleMapType, replicaPlacement string, ttlString string) error {
|
||||
func (s *Store) AddVolume(volumeListString string, collection string, needleMapKind NeedleMapType, replicaPlacement string, ttlString string, preallocate int64) error {
|
||||
rt, e := NewReplicaPlacementFromString(replicaPlacement)
|
||||
if e != nil {
|
||||
return e
|
||||
@@ -111,7 +111,7 @@ func (s *Store) AddVolume(volumeListString string, collection string, needleMapK
|
||||
if err != nil {
|
||||
return fmt.Errorf("Volume Id %s is not a valid unsigned integer!", id_string)
|
||||
}
|
||||
e = s.addVolume(VolumeId(id), collection, needleMapKind, rt, ttl)
|
||||
e = s.addVolume(VolumeId(id), collection, needleMapKind, rt, ttl, preallocate)
|
||||
} else {
|
||||
pair := strings.Split(range_string, "-")
|
||||
start, start_err := strconv.ParseUint(pair[0], 10, 64)
|
||||
@@ -123,7 +123,7 @@ func (s *Store) AddVolume(volumeListString string, collection string, needleMapK
|
||||
return fmt.Errorf("Volume End Id %s is not a valid unsigned integer!", pair[1])
|
||||
}
|
||||
for id := start; id <= end; id++ {
|
||||
if err := s.addVolume(VolumeId(id), collection, needleMapKind, rt, ttl); err != nil {
|
||||
if err := s.addVolume(VolumeId(id), collection, needleMapKind, rt, ttl, preallocate); err != nil {
|
||||
e = err
|
||||
}
|
||||
}
|
||||
@@ -160,14 +160,14 @@ func (s *Store) findFreeLocation() (ret *DiskLocation) {
|
||||
}
|
||||
return ret
|
||||
}
|
||||
func (s *Store) addVolume(vid VolumeId, collection string, needleMapKind NeedleMapType, replicaPlacement *ReplicaPlacement, ttl *TTL) error {
|
||||
func (s *Store) addVolume(vid VolumeId, collection string, needleMapKind NeedleMapType, replicaPlacement *ReplicaPlacement, ttl *TTL, preallocate int64) error {
|
||||
if s.findVolume(vid) != nil {
|
||||
return fmt.Errorf("Volume Id %d already exists!", vid)
|
||||
}
|
||||
if location := s.findFreeLocation(); location != nil {
|
||||
glog.V(0).Infof("In dir %s adds volume:%v collection:%s replicaPlacement:%v ttl:%v",
|
||||
location.Directory, vid, collection, replicaPlacement, ttl)
|
||||
if volume, err := NewVolume(location.Directory, collection, vid, needleMapKind, replicaPlacement, ttl); err == nil {
|
||||
if volume, err := NewVolume(location.Directory, collection, vid, needleMapKind, replicaPlacement, ttl, preallocate); err == nil {
|
||||
location.SetVolume(vid, volume)
|
||||
return nil
|
||||
} else {
|
||||
@@ -208,15 +208,8 @@ func (s *Store) SetRack(rack string) {
|
||||
s.rack = rack
|
||||
}
|
||||
|
||||
func (s *Store) SetBootstrapMaster(bootstrapMaster string) {
|
||||
s.masterNodes = NewMasterNodes(bootstrapMaster)
|
||||
}
|
||||
func (s *Store) SendHeartbeatToMaster() (masterNode string, secretKey security.Secret, e error) {
|
||||
masterNode, e = s.masterNodes.FindMaster()
|
||||
if e != nil {
|
||||
return
|
||||
}
|
||||
var volumeMessages []*operation.VolumeInformationMessage
|
||||
func (s *Store) CollectHeartbeat() *pb.Heartbeat {
|
||||
var volumeMessages []*pb.VolumeInformationMessage
|
||||
maxVolumeCount := 0
|
||||
var maxFileKey uint64
|
||||
for _, location := range s.Locations {
|
||||
@@ -226,18 +219,18 @@ func (s *Store) SendHeartbeatToMaster() (masterNode string, secretKey security.S
|
||||
if maxFileKey < v.nm.MaxFileKey() {
|
||||
maxFileKey = v.nm.MaxFileKey()
|
||||
}
|
||||
if !v.expired(s.volumeSizeLimit) {
|
||||
volumeMessage := &operation.VolumeInformationMessage{
|
||||
Id: proto.Uint32(uint32(k)),
|
||||
Size: proto.Uint64(uint64(v.Size())),
|
||||
Collection: proto.String(v.Collection),
|
||||
FileCount: proto.Uint64(uint64(v.nm.FileCount())),
|
||||
DeleteCount: proto.Uint64(uint64(v.nm.DeletedCount())),
|
||||
DeletedByteCount: proto.Uint64(v.nm.DeletedSize()),
|
||||
ReadOnly: proto.Bool(v.readOnly),
|
||||
ReplicaPlacement: proto.Uint32(uint32(v.ReplicaPlacement.Byte())),
|
||||
Version: proto.Uint32(uint32(v.Version())),
|
||||
Ttl: proto.Uint32(v.Ttl.ToUint32()),
|
||||
if !v.expired(s.VolumeSizeLimit) {
|
||||
volumeMessage := &pb.VolumeInformationMessage{
|
||||
Id: uint32(k),
|
||||
Size: uint64(v.Size()),
|
||||
Collection: v.Collection,
|
||||
FileCount: uint64(v.nm.FileCount()),
|
||||
DeleteCount: uint64(v.nm.DeletedCount()),
|
||||
DeletedByteCount: v.nm.DeletedSize(),
|
||||
ReadOnly: v.readOnly,
|
||||
ReplicaPlacement: uint32(v.ReplicaPlacement.Byte()),
|
||||
Version: uint32(v.Version()),
|
||||
Ttl: v.Ttl.ToUint32(),
|
||||
}
|
||||
volumeMessages = append(volumeMessages, volumeMessage)
|
||||
} else {
|
||||
@@ -252,67 +245,35 @@ func (s *Store) SendHeartbeatToMaster() (masterNode string, secretKey security.S
|
||||
location.Unlock()
|
||||
}
|
||||
|
||||
joinMessage := &operation.JoinMessage{
|
||||
IsInit: proto.Bool(!s.connected),
|
||||
Ip: proto.String(s.Ip),
|
||||
Port: proto.Uint32(uint32(s.Port)),
|
||||
PublicUrl: proto.String(s.PublicUrl),
|
||||
MaxVolumeCount: proto.Uint32(uint32(maxVolumeCount)),
|
||||
MaxFileKey: proto.Uint64(maxFileKey),
|
||||
DataCenter: proto.String(s.dataCenter),
|
||||
Rack: proto.String(s.rack),
|
||||
return &pb.Heartbeat{
|
||||
Ip: s.Ip,
|
||||
Port: uint32(s.Port),
|
||||
PublicUrl: s.PublicUrl,
|
||||
MaxVolumeCount: uint32(maxVolumeCount),
|
||||
MaxFileKey: maxFileKey,
|
||||
DataCenter: s.dataCenter,
|
||||
Rack: s.rack,
|
||||
Volumes: volumeMessages,
|
||||
}
|
||||
|
||||
data, err := proto.Marshal(joinMessage)
|
||||
if err != nil {
|
||||
return "", "", err
|
||||
}
|
||||
|
||||
joinUrl := "http://" + masterNode + "/dir/join"
|
||||
glog.V(4).Infof("Connecting to %s ...", joinUrl)
|
||||
|
||||
jsonBlob, err := util.PostBytes(joinUrl, data)
|
||||
if err != nil {
|
||||
s.masterNodes.Reset()
|
||||
return "", "", err
|
||||
}
|
||||
var ret operation.JoinResult
|
||||
if err := json.Unmarshal(jsonBlob, &ret); err != nil {
|
||||
glog.V(0).Infof("Failed to join %s with response: %s", joinUrl, string(jsonBlob))
|
||||
s.masterNodes.Reset()
|
||||
return masterNode, "", err
|
||||
}
|
||||
if ret.Error != "" {
|
||||
s.masterNodes.Reset()
|
||||
return masterNode, "", errors.New(ret.Error)
|
||||
}
|
||||
s.volumeSizeLimit = ret.VolumeSizeLimit
|
||||
secretKey = security.Secret(ret.SecretKey)
|
||||
s.connected = true
|
||||
return
|
||||
}
|
||||
func (s *Store) Close() {
|
||||
for _, location := range s.Locations {
|
||||
location.Close()
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) Write(i VolumeId, n *Needle) (size uint32, err error) {
|
||||
if v := s.findVolume(i); v != nil {
|
||||
if v.readOnly {
|
||||
err = fmt.Errorf("Volume %d is read only", i)
|
||||
return
|
||||
}
|
||||
// TODO: count needle size ahead
|
||||
if MaxPossibleVolumeSize >= v.ContentSize()+uint64(size) {
|
||||
size, err = v.writeNeedle(n)
|
||||
} else {
|
||||
err = fmt.Errorf("Volume Size Limit %d Exceeded! Current size is %d", s.volumeSizeLimit, v.ContentSize())
|
||||
}
|
||||
if s.volumeSizeLimit < v.ContentSize()+3*uint64(size) {
|
||||
glog.V(0).Infoln("volume", i, "size", v.ContentSize(), "will exceed limit", s.volumeSizeLimit)
|
||||
if _, _, e := s.SendHeartbeatToMaster(); e != nil {
|
||||
glog.V(0).Infoln("error when reporting size:", e)
|
||||
}
|
||||
err = fmt.Errorf("Volume Size Limit %d Exceeded! Current size is %d", s.VolumeSizeLimit, v.ContentSize())
|
||||
}
|
||||
return
|
||||
}
|
||||
@@ -320,17 +281,27 @@ func (s *Store) Write(i VolumeId, n *Needle) (size uint32, err error) {
|
||||
err = fmt.Errorf("Volume %d not found!", i)
|
||||
return
|
||||
}
|
||||
|
||||
func (s *Store) updateMaster() {
|
||||
if s.Client != nil {
|
||||
if e := s.Client.Send(s.CollectHeartbeat()); e != nil {
|
||||
glog.V(0).Infoln("error when reporting size:", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Store) Delete(i VolumeId, n *Needle) (uint32, error) {
|
||||
if v := s.findVolume(i); v != nil && !v.readOnly {
|
||||
return v.deleteNeedle(n)
|
||||
}
|
||||
return 0, nil
|
||||
}
|
||||
|
||||
func (s *Store) ReadVolumeNeedle(i VolumeId, n *Needle) (int, error) {
|
||||
if v := s.findVolume(i); v != nil {
|
||||
return v.readNeedle(n)
|
||||
}
|
||||
return 0, fmt.Errorf("Volume %v not found!", i)
|
||||
return 0, fmt.Errorf("Volume %d not found!", i)
|
||||
}
|
||||
func (s *Store) GetVolume(i VolumeId) *Volume {
|
||||
return s.findVolume(i)
|
||||
@@ -340,3 +311,36 @@ func (s *Store) HasVolume(i VolumeId) bool {
|
||||
v := s.findVolume(i)
|
||||
return v != nil
|
||||
}
|
||||
|
||||
func (s *Store) MountVolume(i VolumeId) error {
|
||||
for _, location := range s.Locations {
|
||||
if found := location.LoadVolume(i, s.NeedleMapType); found == true {
|
||||
s.updateMaster()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("Volume %d not found on disk", i)
|
||||
}
|
||||
|
||||
func (s *Store) UnmountVolume(i VolumeId) error {
|
||||
for _, location := range s.Locations {
|
||||
if err := location.UnloadVolume(i); err == nil {
|
||||
s.updateMaster()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("Volume %d not found on disk", i)
|
||||
}
|
||||
|
||||
func (s *Store) DeleteVolume(i VolumeId) error {
|
||||
for _, location := range s.Locations {
|
||||
if error := location.deleteVolumeById(i); error == nil {
|
||||
s.updateMaster()
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return fmt.Errorf("Volume %d not found on disk", i)
|
||||
}
|
||||
@@ -28,11 +28,11 @@ type Volume struct {
|
||||
lastCompactRevision uint16
|
||||
}
|
||||
|
||||
func NewVolume(dirname string, collection string, id VolumeId, needleMapKind NeedleMapType, replicaPlacement *ReplicaPlacement, ttl *TTL) (v *Volume, e error) {
|
||||
func NewVolume(dirname string, collection string, id VolumeId, needleMapKind NeedleMapType, replicaPlacement *ReplicaPlacement, ttl *TTL, preallocate int64) (v *Volume, e error) {
|
||||
v = &Volume{dir: dirname, Collection: collection, Id: id}
|
||||
v.SuperBlock = SuperBlock{ReplicaPlacement: replicaPlacement, Ttl: ttl}
|
||||
v.needleMapKind = needleMapKind
|
||||
e = v.load(true, true, needleMapKind)
|
||||
e = v.load(true, true, needleMapKind, preallocate)
|
||||
return
|
||||
}
|
||||
func (v *Volume) String() string {
|
||||
|
||||
@@ -7,7 +7,12 @@ import (
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) error {
|
||||
func getActualSize(size uint32) int64 {
|
||||
padding := NeedlePaddingSize - ((NeedleHeaderSize + size + NeedleChecksumSize) % NeedlePaddingSize)
|
||||
return NeedleHeaderSize + int64(size) + NeedleChecksumSize + int64(padding)
|
||||
}
|
||||
|
||||
func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) (error) {
|
||||
var indexSize int64
|
||||
var e error
|
||||
if indexSize, e = verifyIndexFileIntegrity(indexFile); e != nil {
|
||||
@@ -21,12 +26,13 @@ func CheckVolumeDataIntegrity(v *Volume, indexFile *os.File) error {
|
||||
return fmt.Errorf("readLastIndexEntry %s failed: %v", indexFile.Name(), e)
|
||||
}
|
||||
key, offset, size := idxFileEntry(lastIdxEntry)
|
||||
if offset == 0 {
|
||||
if offset == 0 || size == TombstoneFileSize {
|
||||
return nil
|
||||
}
|
||||
if e = verifyNeedleIntegrity(v.dataFile, v.Version(), int64(offset)*NeedlePaddingSize, key, size); e != nil {
|
||||
return fmt.Errorf("verifyNeedleIntegrity %s failed: %v", indexFile.Name(), e)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,17 @@
|
||||
// +build !linux
|
||||
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
func createVolumeFile(fileName string, preallocate int64) (file *os.File, e error) {
|
||||
file, e = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644)
|
||||
if preallocate > 0 {
|
||||
glog.V(0).Infof("Preallocated disk space for %s is not supported", fileName)
|
||||
}
|
||||
return file, e
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
// +build linux
|
||||
|
||||
package storage
|
||||
|
||||
import (
|
||||
"os"
|
||||
"syscall"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
)
|
||||
|
||||
func createVolumeFile(fileName string, preallocate int64) (file *os.File, e error) {
|
||||
file, e = os.OpenFile(fileName, os.O_RDWR|os.O_CREATE, 0644)
|
||||
if preallocate != 0 {
|
||||
syscall.Fallocate(int(file.Fd()), 1, 0, preallocate)
|
||||
glog.V(0).Infof("Preallocated %d bytes disk space for %s", preallocate, fileName)
|
||||
}
|
||||
return file, e
|
||||
}
|
||||
+13
-12
@@ -2,8 +2,9 @@ package storage
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"sort"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/pb"
|
||||
)
|
||||
|
||||
type VolumeInfo struct {
|
||||
@@ -19,23 +20,23 @@ type VolumeInfo struct {
|
||||
ReadOnly bool
|
||||
}
|
||||
|
||||
func NewVolumeInfo(m *operation.VolumeInformationMessage) (vi VolumeInfo, err error) {
|
||||
func NewVolumeInfo(m *pb.VolumeInformationMessage) (vi VolumeInfo, err error) {
|
||||
vi = VolumeInfo{
|
||||
Id: VolumeId(*m.Id),
|
||||
Size: *m.Size,
|
||||
Collection: *m.Collection,
|
||||
FileCount: int(*m.FileCount),
|
||||
DeleteCount: int(*m.DeleteCount),
|
||||
DeletedByteCount: *m.DeletedByteCount,
|
||||
ReadOnly: *m.ReadOnly,
|
||||
Version: Version(*m.Version),
|
||||
Id: VolumeId(m.Id),
|
||||
Size: m.Size,
|
||||
Collection: m.Collection,
|
||||
FileCount: int(m.FileCount),
|
||||
DeleteCount: int(m.DeleteCount),
|
||||
DeletedByteCount: m.DeletedByteCount,
|
||||
ReadOnly: m.ReadOnly,
|
||||
Version: Version(m.Version),
|
||||
}
|
||||
rp, e := NewReplicaPlacementFromByte(byte(*m.ReplicaPlacement))
|
||||
rp, e := NewReplicaPlacementFromByte(byte(m.ReplicaPlacement))
|
||||
if e != nil {
|
||||
return vi, e
|
||||
}
|
||||
vi.ReplicaPlacement = rp
|
||||
vi.Ttl = LoadTTLFromUint32(*m.Ttl)
|
||||
vi.Ttl = LoadTTLFromUint32(m.Ttl)
|
||||
return vi, nil
|
||||
}
|
||||
|
||||
|
||||
@@ -12,11 +12,11 @@ func loadVolumeWithoutIndex(dirname string, collection string, id VolumeId, need
|
||||
v = &Volume{dir: dirname, Collection: collection, Id: id}
|
||||
v.SuperBlock = SuperBlock{}
|
||||
v.needleMapKind = needleMapKind
|
||||
e = v.load(false, false, needleMapKind)
|
||||
e = v.load(false, false, needleMapKind, 0)
|
||||
return
|
||||
}
|
||||
|
||||
func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind NeedleMapType) error {
|
||||
func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind NeedleMapType, preallocate int64) error {
|
||||
var e error
|
||||
fileName := v.FileName()
|
||||
|
||||
@@ -34,7 +34,7 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
}
|
||||
} else {
|
||||
if createDatIfMissing {
|
||||
v.dataFile, e = os.OpenFile(fileName+".dat", os.O_RDWR|os.O_CREATE, 0644)
|
||||
v.dataFile, e = createVolumeFile(fileName+".dat", preallocate)
|
||||
} else {
|
||||
return fmt.Errorf("Volume Data file %s.dat does not exist.", fileName)
|
||||
}
|
||||
@@ -70,22 +70,28 @@ func (v *Volume) load(alsoLoadIndex bool, createDatIfMissing bool, needleMapKind
|
||||
}
|
||||
switch needleMapKind {
|
||||
case NeedleMapInMemory:
|
||||
glog.V(0).Infoln("loading index file", fileName+".idx", "readonly", v.readOnly)
|
||||
if v.nm, e = LoadNeedleMap(indexFile); e != nil {
|
||||
glog.V(0).Infof("loading index %s error: %v", fileName+".idx", e)
|
||||
glog.V(0).Infoln("loading index", fileName+".idx", "to memory readonly", v.readOnly)
|
||||
if v.nm, e = LoadCompactNeedleMap(indexFile); e != nil {
|
||||
glog.V(0).Infof("loading index %s to memory error: %v", fileName+".idx", e)
|
||||
}
|
||||
case NeedleMapLevelDb:
|
||||
glog.V(0).Infoln("loading leveldb file", fileName+".ldb")
|
||||
glog.V(0).Infoln("loading leveldb", fileName+".ldb")
|
||||
if v.nm, e = NewLevelDbNeedleMap(fileName+".ldb", indexFile); e != nil {
|
||||
glog.V(0).Infof("loading leveldb %s error: %v", fileName+".ldb", e)
|
||||
}
|
||||
case NeedleMapBoltDb:
|
||||
glog.V(0).Infoln("loading boltdb file", fileName+".bdb")
|
||||
glog.V(0).Infoln("loading boltdb", fileName+".bdb")
|
||||
if v.nm, e = NewBoltDbNeedleMap(fileName+".bdb", indexFile); e != nil {
|
||||
glog.V(0).Infof("loading boltdb %s error: %v", fileName+".bdb", e)
|
||||
}
|
||||
case NeedleMapBtree:
|
||||
glog.V(0).Infoln("loading index", fileName+".idx", "to btree readonly", v.readOnly)
|
||||
if v.nm, e = LoadBtreeNeedleMap(indexFile); e != nil {
|
||||
glog.V(0).Infof("loading index %s to btree error: %v", fileName+".idx", e)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return e
|
||||
}
|
||||
|
||||
|
||||
@@ -69,7 +69,7 @@ func (v *Volume) AppendBlob(b []byte) (offset int64, err error) {
|
||||
return
|
||||
}
|
||||
}
|
||||
v.dataFile.Write(b)
|
||||
_, err = v.dataFile.Write(b)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -101,12 +101,13 @@ func (v *Volume) writeNeedle(n *Needle) (size uint32, err error) {
|
||||
}
|
||||
}
|
||||
|
||||
if size, err = n.Append(v.dataFile, v.Version()); err != nil {
|
||||
if size, _, err = n.Append(v.dataFile, v.Version()); err != nil {
|
||||
if e := v.dataFile.Truncate(offset); e != nil {
|
||||
err = fmt.Errorf("%s\ncannot truncate %s: %v", err, v.dataFile.Name(), e)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
nv, ok := v.nm.Get(n.Id)
|
||||
if !ok || int64(nv.Offset)*NeedlePaddingSize < offset {
|
||||
if err = v.nm.Put(n.Id, uint32(offset/NeedlePaddingSize), n.Size); err != nil {
|
||||
@@ -128,16 +129,17 @@ func (v *Volume) deleteNeedle(n *Needle) (uint32, error) {
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
nv, ok := v.nm.Get(n.Id)
|
||||
//fmt.Println("key", n.Id, "volume offset", nv.Offset, "data_size", n.Size, "cached size", nv.Size)
|
||||
if ok {
|
||||
if ok && nv.Size != TombstoneFileSize {
|
||||
size := nv.Size
|
||||
if err := v.nm.Delete(n.Id); err != nil {
|
||||
offset, err := v.dataFile.Seek(0, 2)
|
||||
if err != nil {
|
||||
return size, err
|
||||
}
|
||||
if _, err := v.dataFile.Seek(0, 2); err != nil {
|
||||
if err := v.nm.Delete(n.Id, uint32(offset/NeedlePaddingSize)); err != nil {
|
||||
return size, err
|
||||
}
|
||||
n.Data = nil
|
||||
_, err := n.Append(v.dataFile, v.Version())
|
||||
_, _, err = n.Append(v.dataFile, v.Version())
|
||||
return size, err
|
||||
}
|
||||
return 0, nil
|
||||
@@ -149,6 +151,9 @@ func (v *Volume) readNeedle(n *Needle) (int, error) {
|
||||
if !ok || nv.Offset == 0 {
|
||||
return -1, errors.New("Not Found")
|
||||
}
|
||||
if nv.Size == TombstoneFileSize {
|
||||
return -1, errors.New("Already Deleted")
|
||||
}
|
||||
err := n.ReadData(v.dataFile, int64(nv.Offset)*NeedlePaddingSize, nv.Size, v.Version())
|
||||
if err != nil {
|
||||
return 0, err
|
||||
|
||||
+15
-14
@@ -11,6 +11,7 @@ import (
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage/needle"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
@@ -48,7 +49,7 @@ optimized more later).
|
||||
func (v *Volume) Synchronize(volumeServer string) (err error) {
|
||||
var lastCompactRevision uint16 = 0
|
||||
var compactRevision uint16 = 0
|
||||
var masterMap CompactMap
|
||||
var masterMap *needle.CompactMap
|
||||
for i := 0; i < 3; i++ {
|
||||
if masterMap, _, compactRevision, err = fetchVolumeFileEntries(volumeServer, v.Id); err != nil {
|
||||
return fmt.Errorf("Failed to sync volume %d entries with %s: %v", v.Id, volumeServer, err)
|
||||
@@ -69,7 +70,7 @@ func (v *Volume) Synchronize(volumeServer string) (err error) {
|
||||
return
|
||||
}
|
||||
|
||||
type ByOffset []NeedleValue
|
||||
type ByOffset []needle.NeedleValue
|
||||
|
||||
func (a ByOffset) Len() int { return len(a) }
|
||||
func (a ByOffset) Swap(i, j int) { a[i], a[j] = a[j], a[i] }
|
||||
@@ -77,18 +78,18 @@ func (a ByOffset) Less(i, j int) bool { return a[i].Offset < a[j].Offset }
|
||||
|
||||
// trySynchronizing sync with remote volume server incrementally by
|
||||
// make up the local and remote delta.
|
||||
func (v *Volume) trySynchronizing(volumeServer string, masterMap CompactMap, compactRevision uint16) error {
|
||||
func (v *Volume) trySynchronizing(volumeServer string, masterMap *needle.CompactMap, compactRevision uint16) error {
|
||||
slaveIdxFile, err := os.Open(v.nm.IndexFileName())
|
||||
if err != nil {
|
||||
return fmt.Errorf("Open volume %d index file: %v", v.Id, err)
|
||||
}
|
||||
defer slaveIdxFile.Close()
|
||||
slaveMap, err := LoadNeedleMap(slaveIdxFile)
|
||||
slaveMap, err := LoadBtreeNeedleMap(slaveIdxFile)
|
||||
if err != nil {
|
||||
return fmt.Errorf("Load volume %d index file: %v", v.Id, err)
|
||||
}
|
||||
var delta []NeedleValue
|
||||
if err := masterMap.Visit(func(needleValue NeedleValue) error {
|
||||
var delta []needle.NeedleValue
|
||||
if err := masterMap.Visit(func(needleValue needle.NeedleValue) error {
|
||||
if needleValue.Key == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -100,7 +101,7 @@ func (v *Volume) trySynchronizing(volumeServer string, masterMap CompactMap, com
|
||||
}); err != nil {
|
||||
return fmt.Errorf("Add master entry: %v", err)
|
||||
}
|
||||
if err := slaveMap.m.Visit(func(needleValue NeedleValue) error {
|
||||
if err := slaveMap.m.Visit(func(needleValue needle.NeedleValue) error {
|
||||
if needleValue.Key == 0 {
|
||||
return nil
|
||||
}
|
||||
@@ -137,8 +138,8 @@ func (v *Volume) trySynchronizing(volumeServer string, masterMap CompactMap, com
|
||||
return nil
|
||||
}
|
||||
|
||||
func fetchVolumeFileEntries(volumeServer string, vid VolumeId) (m CompactMap, lastOffset uint64, compactRevision uint16, err error) {
|
||||
m = NewCompactMap()
|
||||
func fetchVolumeFileEntries(volumeServer string, vid VolumeId) (m *needle.CompactMap, lastOffset uint64, compactRevision uint16, err error) {
|
||||
m = needle.NewCompactMap()
|
||||
|
||||
syncStatus, err := operation.GetVolumeSyncStatus(volumeServer, vid.String())
|
||||
if err != nil {
|
||||
@@ -148,10 +149,10 @@ func fetchVolumeFileEntries(volumeServer string, vid VolumeId) (m CompactMap, la
|
||||
total := 0
|
||||
err = operation.GetVolumeIdxEntries(volumeServer, vid.String(), func(key uint64, offset, size uint32) {
|
||||
// println("remote key", key, "offset", offset*NeedlePaddingSize, "size", size)
|
||||
if offset != 0 && size != 0 {
|
||||
m.Set(Key(key), offset, size)
|
||||
if offset > 0 && size != TombstoneFileSize {
|
||||
m.Set(needle.Key(key), offset, size)
|
||||
} else {
|
||||
m.Delete(Key(key))
|
||||
m.Delete(needle.Key(key))
|
||||
}
|
||||
total++
|
||||
})
|
||||
@@ -178,7 +179,7 @@ func (v *Volume) IndexFileContent() ([]byte, error) {
|
||||
}
|
||||
|
||||
// removeNeedle removes one needle by needle key
|
||||
func (v *Volume) removeNeedle(key Key) {
|
||||
func (v *Volume) removeNeedle(key needle.Key) {
|
||||
n := new(Needle)
|
||||
n.Id = uint64(key)
|
||||
v.deleteNeedle(n)
|
||||
@@ -188,7 +189,7 @@ func (v *Volume) removeNeedle(key Key) {
|
||||
// The compact revision is checked first in case the remote volume
|
||||
// is compacted and the offset is invalid any more.
|
||||
func (v *Volume) fetchNeedle(volumeDataContentHandlerUrl string,
|
||||
needleValue NeedleValue, compactRevision uint16) error {
|
||||
needleValue needle.NeedleValue, compactRevision uint16) error {
|
||||
// add master file entry to local data file
|
||||
values := make(url.Values)
|
||||
values.Add("revision", strconv.Itoa(int(compactRevision)))
|
||||
|
||||
@@ -24,7 +24,7 @@ func (v *Volume) Compact() error {
|
||||
v.lastCompactIndexOffset = v.nm.IndexFileSize()
|
||||
v.lastCompactRevision = v.SuperBlock.CompactRevision
|
||||
glog.V(3).Infof("creating copies for volume %d ,last offset %d...", v.Id, v.lastCompactIndexOffset)
|
||||
return v.copyDataAndGenerateIndexFile(filePath+".cpd", filePath+".cpx")
|
||||
return v.copyDataAndGenerateIndexFile(filePath+".cpd", filePath+".cpx", 0)
|
||||
}
|
||||
|
||||
func (v *Volume) Compact2() error {
|
||||
@@ -35,7 +35,7 @@ func (v *Volume) Compact2() error {
|
||||
}
|
||||
|
||||
func (v *Volume) commitCompact() error {
|
||||
glog.V(3).Infof("Committing vacuuming...")
|
||||
glog.V(0).Infof("Committing vacuuming...")
|
||||
v.dataFileAccessLock.Lock()
|
||||
defer v.dataFileAccessLock.Unlock()
|
||||
glog.V(3).Infof("Got Committing lock...")
|
||||
@@ -66,7 +66,7 @@ func (v *Volume) commitCompact() error {
|
||||
//glog.V(3).Infof("Pretending to be vacuuming...")
|
||||
//time.Sleep(20 * time.Second)
|
||||
glog.V(3).Infof("Loading Commit file...")
|
||||
if e = v.load(true, false, v.needleMapKind); e != nil {
|
||||
if e = v.load(true, false, v.needleMapKind, 0); e != nil {
|
||||
return e
|
||||
}
|
||||
return nil
|
||||
@@ -189,7 +189,7 @@ func (v *Volume) makeupDiff(newDatFileName, newIdxFileName, oldDatFileName, oldI
|
||||
fakeDelNeedle := new(Needle)
|
||||
fakeDelNeedle.Id = key
|
||||
fakeDelNeedle.Cookie = 0x12345678
|
||||
_, err = fakeDelNeedle.Append(dst, v.Version())
|
||||
_, _, err = fakeDelNeedle.Append(dst, v.Version())
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -207,11 +207,11 @@ func (v *Volume) makeupDiff(newDatFileName, newIdxFileName, oldDatFileName, oldI
|
||||
return nil
|
||||
}
|
||||
|
||||
func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err error) {
|
||||
func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string, preallocate int64) (err error) {
|
||||
var (
|
||||
dst, idx *os.File
|
||||
)
|
||||
if dst, err = os.OpenFile(dstName, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0644); err != nil {
|
||||
if dst, err = createVolumeFile(dstName, preallocate); err != nil {
|
||||
return
|
||||
}
|
||||
defer dst.Close()
|
||||
@@ -221,7 +221,7 @@ func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err erro
|
||||
}
|
||||
defer idx.Close()
|
||||
|
||||
nm := NewNeedleMap(idx)
|
||||
nm := NewBtreeNeedleMap(idx)
|
||||
new_offset := int64(SuperBlockSize)
|
||||
|
||||
now := uint64(time.Now().Unix())
|
||||
@@ -241,7 +241,7 @@ func (v *Volume) copyDataAndGenerateIndexFile(dstName, idxName string) (err erro
|
||||
if err = nm.Put(n.Id, uint32(new_offset/NeedlePaddingSize), n.Size); err != nil {
|
||||
return fmt.Errorf("cannot put needle: %s", err)
|
||||
}
|
||||
if _, err = n.Append(dst, v.Version()); err != nil {
|
||||
if _, _, err := n.Append(dst, v.Version()); err != nil {
|
||||
return fmt.Errorf("cannot append needle: %s", err)
|
||||
}
|
||||
new_offset += n.DiskSize()
|
||||
@@ -272,7 +272,7 @@ func (v *Volume) copyDataBasedOnIndexFile(dstName, idxName string) (err error) {
|
||||
}
|
||||
defer oldIndexFile.Close()
|
||||
|
||||
nm := NewNeedleMap(idx)
|
||||
nm := NewBtreeNeedleMap(idx)
|
||||
now := uint64(time.Now().Unix())
|
||||
|
||||
v.SuperBlock.CompactRevision++
|
||||
@@ -280,7 +280,7 @@ func (v *Volume) copyDataBasedOnIndexFile(dstName, idxName string) (err error) {
|
||||
new_offset := int64(SuperBlockSize)
|
||||
|
||||
WalkIndexFile(oldIndexFile, func(key uint64, offset, size uint32) error {
|
||||
if size <= 0 {
|
||||
if offset == 0 || size == TombstoneFileSize {
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -302,7 +302,7 @@ func (v *Volume) copyDataBasedOnIndexFile(dstName, idxName string) (err error) {
|
||||
if err = nm.Put(n.Id, uint32(new_offset/NeedlePaddingSize), n.Size); err != nil {
|
||||
return fmt.Errorf("cannot put needle: %s", err)
|
||||
}
|
||||
if _, err = n.Append(dst, v.Version()); err != nil {
|
||||
if _, _, err = n.Append(dst, v.Version()); err != nil {
|
||||
return fmt.Errorf("cannot append needle: %s", err)
|
||||
}
|
||||
new_offset += n.DiskSize()
|
||||
|
||||
@@ -20,6 +20,7 @@ func AllocateVolume(dn *DataNode, vid storage.VolumeId, option *VolumeGrowOption
|
||||
values.Add("collection", option.Collection)
|
||||
values.Add("replication", option.ReplicaPlacement.String())
|
||||
values.Add("ttl", option.Ttl.String())
|
||||
values.Add("preallocate", fmt.Sprintf("%d", option.Prealloacte))
|
||||
jsonBlob, err := util.Post("http://"+dn.Url()+"/admin/assign_volume", values)
|
||||
if err != nil {
|
||||
return err
|
||||
|
||||
@@ -25,20 +25,6 @@ type Configuration struct {
|
||||
ip2location map[string]loc
|
||||
}
|
||||
|
||||
func NewConfiguration(b []byte) (*Configuration, error) {
|
||||
c := &Configuration{}
|
||||
err := xml.Unmarshal(b, c)
|
||||
c.ip2location = make(map[string]loc)
|
||||
for _, dc := range c.Topo.DataCenters {
|
||||
for _, rack := range dc.Racks {
|
||||
for _, ip := range rack.Ips {
|
||||
c.ip2location[ip] = loc{dcName: dc.Name, rackName: rack.Name}
|
||||
}
|
||||
}
|
||||
}
|
||||
return c, err
|
||||
}
|
||||
|
||||
func (c *Configuration) String() string {
|
||||
if b, e := xml.MarshalIndent(c, " ", " "); e == nil {
|
||||
return string(b)
|
||||
|
||||
@@ -1,42 +0,0 @@
|
||||
package topology
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestLoadConfiguration(t *testing.T) {
|
||||
|
||||
confContent := `
|
||||
|
||||
<?xml version="1.0" encoding="UTF-8" ?>
|
||||
<Configuration>
|
||||
<Topology>
|
||||
<DataCenter name="dc1">
|
||||
<Rack name="rack1">
|
||||
<Ip>192.168.1.1</Ip>
|
||||
</Rack>
|
||||
</DataCenter>
|
||||
<DataCenter name="dc2">
|
||||
<Rack name="rack1">
|
||||
<Ip>192.168.1.2</Ip>
|
||||
</Rack>
|
||||
<Rack name="rack2">
|
||||
<Ip>192.168.1.3</Ip>
|
||||
<Ip>192.168.1.4</Ip>
|
||||
</Rack>
|
||||
</DataCenter>
|
||||
</Topology>
|
||||
</Configuration>
|
||||
`
|
||||
c, err := NewConfiguration([]byte(confContent))
|
||||
|
||||
fmt.Printf("%s\n", c)
|
||||
if err != nil {
|
||||
t.Fatalf("unmarshal error:%v", err)
|
||||
}
|
||||
|
||||
if len(c.Topo.DataCenters) <= 0 || c.Topo.DataCenters[0].Name != "dc1" {
|
||||
t.Fatalf("unmarshal error:%s", c)
|
||||
}
|
||||
}
|
||||
@@ -15,7 +15,6 @@ type DataNode struct {
|
||||
Port int
|
||||
PublicUrl string
|
||||
LastSeen int64 // unix time in seconds
|
||||
Dead bool
|
||||
}
|
||||
|
||||
func NewDataNode(id string) *DataNode {
|
||||
@@ -30,7 +29,7 @@ func NewDataNode(id string) *DataNode {
|
||||
func (dn *DataNode) String() string {
|
||||
dn.RLock()
|
||||
defer dn.RUnlock()
|
||||
return fmt.Sprintf("Node:%s, volumes:%v, Ip:%s, Port:%d, PublicUrl:%s, Dead:%v", dn.NodeImpl.String(), dn.volumes, dn.Ip, dn.Port, dn.PublicUrl, dn.Dead)
|
||||
return fmt.Sprintf("Node:%s, volumes:%v, Ip:%s, Port:%d, PublicUrl:%s", dn.NodeImpl.String(), dn.volumes, dn.Ip, dn.Port, dn.PublicUrl)
|
||||
}
|
||||
|
||||
func (dn *DataNode) AddOrUpdateVolume(v storage.VolumeInfo) {
|
||||
|
||||
@@ -234,7 +234,7 @@ func (n *NodeImpl) UnlinkChildNode(nodeId NodeId) {
|
||||
n.UpAdjustVolumeCountDelta(-node.GetVolumeCount())
|
||||
n.UpAdjustActiveVolumeCountDelta(-node.GetActiveVolumeCount())
|
||||
n.UpAdjustMaxVolumeCountDelta(-node.GetMaxVolumeCount())
|
||||
glog.V(0).Infoln(n, "removes", node, "volumeCount =", n.activeVolumeCount)
|
||||
glog.V(0).Infoln(n, "removes", node.Id())
|
||||
}
|
||||
}
|
||||
|
||||
@@ -242,12 +242,6 @@ func (n *NodeImpl) CollectDeadNodeAndFullVolumes(freshThreshHold int64, volumeSi
|
||||
if n.IsRack() {
|
||||
for _, c := range n.Children() {
|
||||
dn := c.(*DataNode) //can not cast n to DataNode
|
||||
if dn.LastSeen < freshThreshHold {
|
||||
if !dn.Dead {
|
||||
dn.Dead = true
|
||||
n.GetTopology().chanDeadDataNodes <- dn
|
||||
}
|
||||
}
|
||||
for _, v := range dn.GetVolumes() {
|
||||
if uint64(v.Size) >= volumeSizeLimit {
|
||||
//fmt.Println("volume",v.Id,"size",v.Size,">",volumeSizeLimit)
|
||||
|
||||
@@ -32,11 +32,6 @@ func (r *Rack) GetOrCreateDataNode(ip string, port int, publicUrl string, maxVol
|
||||
dn := c.(*DataNode)
|
||||
if dn.MatchLocation(ip, port) {
|
||||
dn.LastSeen = time.Now().Unix()
|
||||
if dn.Dead {
|
||||
dn.Dead = false
|
||||
r.GetTopology().chanRecoveredDataNodes <- dn
|
||||
dn.UpAdjustMaxVolumeCountDelta(maxVolumeCount - dn.maxVolumeCount)
|
||||
}
|
||||
return dn
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,14 +2,14 @@ package topology
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
"net/url"
|
||||
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/security"
|
||||
@@ -55,9 +55,22 @@ func ReplicatedWrite(masterNode string, s *storage.Store,
|
||||
q.Set("cm", "true")
|
||||
}
|
||||
u.RawQuery = q.Encode()
|
||||
|
||||
pairMap := make(map[string]string)
|
||||
if needle.HasPairs() {
|
||||
tmpMap := make(map[string]string)
|
||||
err := json.Unmarshal(needle.Pairs, &tmpMap)
|
||||
if err != nil {
|
||||
glog.V(0).Infoln("Unmarshal pairs error:", err)
|
||||
}
|
||||
for k, v := range tmpMap {
|
||||
pairMap[storage.PairNamePrefix+k] = v
|
||||
}
|
||||
}
|
||||
|
||||
_, err := operation.Upload(u.String(),
|
||||
string(needle.Name), bytes.NewReader(needle.Data), needle.IsGzipped(), string(needle.Mime),
|
||||
jwt)
|
||||
pairMap, jwt)
|
||||
return err
|
||||
}); err != nil {
|
||||
ret = 0
|
||||
|
||||
@@ -2,12 +2,10 @@ package topology
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"io/ioutil"
|
||||
"math/rand"
|
||||
|
||||
"github.com/chrislusf/raft"
|
||||
"github.com/chrislusf/seaweedfs/weed/glog"
|
||||
"github.com/chrislusf/seaweedfs/weed/operation"
|
||||
"github.com/chrislusf/seaweedfs/weed/sequence"
|
||||
"github.com/chrislusf/seaweedfs/weed/storage"
|
||||
"github.com/chrislusf/seaweedfs/weed/util"
|
||||
@@ -24,16 +22,14 @@ type Topology struct {
|
||||
|
||||
Sequence sequence.Sequencer
|
||||
|
||||
chanDeadDataNodes chan *DataNode
|
||||
chanRecoveredDataNodes chan *DataNode
|
||||
chanFullVolumes chan storage.VolumeInfo
|
||||
chanFullVolumes chan storage.VolumeInfo
|
||||
|
||||
configuration *Configuration
|
||||
Configuration *Configuration
|
||||
|
||||
RaftServer raft.Server
|
||||
}
|
||||
|
||||
func NewTopology(id string, confFile string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int) (*Topology, error) {
|
||||
func NewTopology(id string, seq sequence.Sequencer, volumeSizeLimit uint64, pulse int) *Topology {
|
||||
t := &Topology{}
|
||||
t.id = NodeId(id)
|
||||
t.nodeType = "Topology"
|
||||
@@ -45,13 +41,11 @@ func NewTopology(id string, confFile string, seq sequence.Sequencer, volumeSizeL
|
||||
|
||||
t.Sequence = seq
|
||||
|
||||
t.chanDeadDataNodes = make(chan *DataNode)
|
||||
t.chanRecoveredDataNodes = make(chan *DataNode)
|
||||
t.chanFullVolumes = make(chan storage.VolumeInfo)
|
||||
|
||||
err := t.loadConfiguration(confFile)
|
||||
t.Configuration = &Configuration{}
|
||||
|
||||
return t, err
|
||||
return t
|
||||
}
|
||||
|
||||
func (t *Topology) IsLeader() bool {
|
||||
@@ -77,16 +71,6 @@ func (t *Topology) Leader() (string, error) {
|
||||
return l, nil
|
||||
}
|
||||
|
||||
func (t *Topology) loadConfiguration(configurationFile string) error {
|
||||
b, e := ioutil.ReadFile(configurationFile)
|
||||
if e == nil {
|
||||
t.configuration, e = NewConfiguration(b)
|
||||
return e
|
||||
}
|
||||
glog.V(0).Infoln("Using default configurations.")
|
||||
return nil
|
||||
}
|
||||
|
||||
func (t *Topology) Lookup(collection string, vid storage.VolumeId) []*DataNode {
|
||||
//maybe an issue if lots of collections?
|
||||
if collection == "" {
|
||||
@@ -147,35 +131,6 @@ func (t *Topology) UnRegisterVolumeLayout(v storage.VolumeInfo, dn *DataNode) {
|
||||
t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl).UnRegisterVolume(&v, dn)
|
||||
}
|
||||
|
||||
func (t *Topology) ProcessJoinMessage(joinMessage *operation.JoinMessage) {
|
||||
t.Sequence.SetMax(*joinMessage.MaxFileKey)
|
||||
dcName, rackName := t.configuration.Locate(*joinMessage.Ip, *joinMessage.DataCenter, *joinMessage.Rack)
|
||||
dc := t.GetOrCreateDataCenter(dcName)
|
||||
rack := dc.GetOrCreateRack(rackName)
|
||||
dn := rack.FindDataNode(*joinMessage.Ip, int(*joinMessage.Port))
|
||||
if *joinMessage.IsInit && dn != nil {
|
||||
t.UnRegisterDataNode(dn)
|
||||
}
|
||||
dn = rack.GetOrCreateDataNode(*joinMessage.Ip,
|
||||
int(*joinMessage.Port), *joinMessage.PublicUrl,
|
||||
int(*joinMessage.MaxVolumeCount))
|
||||
var volumeInfos []storage.VolumeInfo
|
||||
for _, v := range joinMessage.Volumes {
|
||||
if vi, err := storage.NewVolumeInfo(v); err == nil {
|
||||
volumeInfos = append(volumeInfos, vi)
|
||||
} else {
|
||||
glog.V(0).Infoln("Fail to convert joined volume information:", err.Error())
|
||||
}
|
||||
}
|
||||
deletedVolumes := dn.UpdateVolumes(volumeInfos)
|
||||
for _, v := range volumeInfos {
|
||||
t.RegisterVolumeLayout(v, dn)
|
||||
}
|
||||
for _, v := range deletedVolumes {
|
||||
t.UnRegisterVolumeLayout(v, dn)
|
||||
}
|
||||
}
|
||||
|
||||
func (t *Topology) GetOrCreateDataCenter(dcName string) *DataCenter {
|
||||
for _, c := range t.Children() {
|
||||
dc := c.(*DataCenter)
|
||||
|
||||
@@ -31,12 +31,6 @@ func (t *Topology) StartRefreshWritableVolumes(garbageThreshold string) {
|
||||
select {
|
||||
case v := <-t.chanFullVolumes:
|
||||
t.SetVolumeCapacityFull(v)
|
||||
case dn := <-t.chanRecoveredDataNodes:
|
||||
t.RegisterRecoveredDataNode(dn)
|
||||
glog.V(0).Infoln("Recovered DataNode: %v", dn)
|
||||
case dn := <-t.chanDeadDataNodes:
|
||||
t.UnRegisterDataNode(dn)
|
||||
glog.V(0).Infof("Dead DataNode: %v", dn)
|
||||
}
|
||||
}
|
||||
}()
|
||||
@@ -55,7 +49,7 @@ func (t *Topology) SetVolumeCapacityFull(volumeInfo storage.VolumeInfo) bool {
|
||||
}
|
||||
func (t *Topology) UnRegisterDataNode(dn *DataNode) {
|
||||
for _, v := range dn.GetVolumes() {
|
||||
glog.V(0).Infoln("Removing Volume", v.Id, "from the dead volume server", dn)
|
||||
glog.V(0).Infoln("Removing Volume", v.Id, "from the dead volume server", dn.Id())
|
||||
vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl)
|
||||
vl.SetVolumeUnavailable(dn, v.Id)
|
||||
}
|
||||
@@ -64,11 +58,3 @@ func (t *Topology) UnRegisterDataNode(dn *DataNode) {
|
||||
dn.UpAdjustMaxVolumeCountDelta(-dn.GetMaxVolumeCount())
|
||||
dn.Parent().UnlinkChildNode(dn.Id())
|
||||
}
|
||||
func (t *Topology) RegisterRecoveredDataNode(dn *DataNode) {
|
||||
for _, v := range dn.GetVolumes() {
|
||||
vl := t.GetVolumeLayout(v.Collection, v.ReplicaPlacement, v.Ttl)
|
||||
if vl.isWritable(&v) {
|
||||
vl.SetVolumeAvailable(dn, v.Id)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -86,14 +86,16 @@ func (t *Topology) Vacuum(garbageThreshold string) int {
|
||||
for _, vl := range c.storageType2VolumeLayout.Items() {
|
||||
if vl != nil {
|
||||
volumeLayout := vl.(*VolumeLayout)
|
||||
writableSet := make(map[storage.VolumeId]bool)
|
||||
for _, id := range volumeLayout.writables {
|
||||
writableSet[id] = true
|
||||
}
|
||||
for vid, locationlist := range volumeLayout.vid2location {
|
||||
if _, isWritable := writableSet[vid]; !isWritable {
|
||||
|
||||
volumeLayout.accessLock.RLock()
|
||||
isReadOnly, hasValue := volumeLayout.readonlyVolumes[vid]
|
||||
volumeLayout.accessLock.RUnlock()
|
||||
|
||||
if hasValue && isReadOnly {
|
||||
continue
|
||||
}
|
||||
|
||||
glog.V(0).Infof("check vacuum on collection:%s volume:%d", c.Name, vid)
|
||||
if batchVacuumVolumeCheck(volumeLayout, vid, locationlist, garbageThreshold) {
|
||||
if batchVacuumVolumeCompact(volumeLayout, vid, locationlist) {
|
||||
|
||||
@@ -21,6 +21,7 @@ type VolumeGrowOption struct {
|
||||
Collection string
|
||||
ReplicaPlacement *storage.ReplicaPlacement
|
||||
Ttl *storage.TTL
|
||||
Prealloacte int64
|
||||
DataCenter string
|
||||
Rack string
|
||||
DataNode string
|
||||
|
||||
@@ -79,11 +79,7 @@ func setup(topologyLayout string) *Topology {
|
||||
fmt.Println("data:", data)
|
||||
|
||||
//need to connect all nodes first before server adding volumes
|
||||
topo, err := NewTopology("weedfs", "/etc/weedfs/weedfs.conf",
|
||||
sequence.NewMemorySequencer(), 32*1024, 5)
|
||||
if err != nil {
|
||||
panic("error: " + err.Error())
|
||||
}
|
||||
topo := NewTopology("weedfs", sequence.NewMemorySequencer(), 32*1024, 5)
|
||||
mTopology := data.(map[string]interface{})
|
||||
for dcKey, dcValue := range mTopology {
|
||||
dc := NewDataCenter(dcKey)
|
||||
|
||||
@@ -16,6 +16,7 @@ type VolumeLayout struct {
|
||||
ttl *storage.TTL
|
||||
vid2location map[storage.VolumeId]*VolumeLocationList
|
||||
writables []storage.VolumeId // transient array of writable volume id
|
||||
readonlyVolumes map[storage.VolumeId]bool // transient set of readonly volumes
|
||||
oversizedVolumes map[storage.VolumeId]bool // set of oversized volumes
|
||||
volumeSizeLimit uint64
|
||||
accessLock sync.RWMutex
|
||||
@@ -27,6 +28,7 @@ func NewVolumeLayout(rp *storage.ReplicaPlacement, ttl *storage.TTL, volumeSizeL
|
||||
ttl: ttl,
|
||||
vid2location: make(map[storage.VolumeId]*VolumeLocationList),
|
||||
writables: *new([]storage.VolumeId),
|
||||
readonlyVolumes: make(map[storage.VolumeId]bool),
|
||||
oversizedVolumes: make(map[storage.VolumeId]bool),
|
||||
volumeSizeLimit: volumeSizeLimit,
|
||||
}
|
||||
@@ -50,11 +52,15 @@ func (vl *VolumeLayout) RegisterVolume(v *storage.VolumeInfo, dn *DataNode) {
|
||||
if v_info.ReadOnly {
|
||||
glog.V(3).Infof("vid %d removed from writable", v.Id)
|
||||
vl.removeFromWritable(v.Id)
|
||||
vl.readonlyVolumes[v.Id] = true
|
||||
return
|
||||
} else {
|
||||
delete(vl.readonlyVolumes, v.Id)
|
||||
}
|
||||
} else {
|
||||
glog.V(3).Infof("vid %d removed from writable", v.Id)
|
||||
vl.removeFromWritable(v.Id)
|
||||
delete(vl.readonlyVolumes, v.Id)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
package util
|
||||
|
||||
const (
|
||||
VERSION = "0.72"
|
||||
VERSION = "0.76"
|
||||
)
|
||||
+14
-2
@@ -74,6 +74,17 @@ func Get(url string) ([]byte, error) {
|
||||
return b, nil
|
||||
}
|
||||
|
||||
func Head(url string) (http.Header, error) {
|
||||
r, err := client.Head(url)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if r.StatusCode >= 400 {
|
||||
return nil, fmt.Errorf("%s: %s", url, r.Status)
|
||||
}
|
||||
return r.Header, nil
|
||||
}
|
||||
|
||||
func Delete(url string, jwt security.EncodedJwt) error {
|
||||
req, err := http.NewRequest("DELETE", url, nil)
|
||||
if jwt != "" {
|
||||
@@ -148,8 +159,9 @@ func DownloadUrl(fileUrl string) (filename string, rc io.ReadCloser, e error) {
|
||||
}
|
||||
contentDisposition := response.Header["Content-Disposition"]
|
||||
if len(contentDisposition) > 0 {
|
||||
if strings.HasPrefix(contentDisposition[0], "filename=") {
|
||||
filename = contentDisposition[0][len("filename="):]
|
||||
idx := strings.Index(contentDisposition[0], "filename=")
|
||||
if idx != -1 {
|
||||
filename = contentDisposition[0][idx+len("filename="):]
|
||||
filename = strings.Trim(filename, "\"")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -38,9 +38,11 @@ type Conn struct {
|
||||
}
|
||||
|
||||
func (c *Conn) Read(b []byte) (count int, e error) {
|
||||
err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
if c.ReadTimeout != 0 {
|
||||
err := c.Conn.SetReadDeadline(time.Now().Add(c.ReadTimeout))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
count, e = c.Conn.Read(b)
|
||||
if e == nil {
|
||||
@@ -50,9 +52,11 @@ func (c *Conn) Read(b []byte) (count int, e error) {
|
||||
}
|
||||
|
||||
func (c *Conn) Write(b []byte) (count int, e error) {
|
||||
err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
if c.WriteTimeout != 0 {
|
||||
err := c.Conn.SetWriteDeadline(time.Now().Add(c.WriteTimeout))
|
||||
if err != nil {
|
||||
return 0, err
|
||||
}
|
||||
}
|
||||
count, e = c.Conn.Write(b)
|
||||
if e == nil {
|
||||
|
||||
Reference in new issue
Block a user