seaweedfs/go/weed/volume.go

373 lines
11 KiB
Go
Raw Normal View History

package main
import (
2013-02-27 06:54:22 +00:00
"code.google.com/p/weed-fs/go/operation"
"code.google.com/p/weed-fs/go/replication"
2013-02-27 06:54:22 +00:00
"code.google.com/p/weed-fs/go/storage"
2012-08-24 05:46:54 +00:00
"log"
"math/rand"
"mime"
"net/http"
"os"
2013-07-13 22:57:44 +00:00
"path/filepath"
"runtime"
2012-08-24 05:46:54 +00:00
"strconv"
"strings"
"time"
)
func init() {
2012-08-24 05:46:54 +00:00
cmdVolume.Run = runVolume // break init cycle
2013-01-20 03:49:57 +00:00
cmdVolume.IsDebug = cmdVolume.Flag.Bool("debug", false, "enable debug mode")
}
var cmdVolume = &Command{
2012-09-26 08:55:56 +00:00
UsageLine: "volume -port=8080 -dir=/tmp -max=5 -ip=server_name -mserver=localhost:9333",
2012-08-24 05:46:54 +00:00
Short: "start a volume server",
Long: `start a volume server to provide storage spaces
`,
}
var (
vport = cmdVolume.Flag.Int("port", 8080, "http listen port")
volumeFolders = cmdVolume.Flag.String("dir", "/tmp", "directories to store data files. dir[,dir]...")
maxVolumeCounts = cmdVolume.Flag.String("max", "7", "maximum numbers of volumes, count[,count]...")
ip = cmdVolume.Flag.String("ip", "localhost", "ip or server name")
publicUrl = cmdVolume.Flag.String("publicUrl", "", "Publicly accessible <ip|server_name>:<port>")
masterNode = cmdVolume.Flag.String("mserver", "localhost:9333", "master server location")
vpulse = cmdVolume.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats, must be smaller than the master's setting")
vReadTimeout = cmdVolume.Flag.Int("readTimeout", 3, "connection read timeout in seconds")
vMaxCpu = cmdVolume.Flag.Int("maxCpu", 0, "maximum number of CPUs. 0 means all available CPUs")
dataCenter = cmdVolume.Flag.String("dataCenter", "", "current volume server's data center name")
rack = cmdVolume.Flag.String("rack", "", "current volume server's rack name")
2012-08-24 05:46:54 +00:00
store *storage.Store
)
2013-01-17 08:56:56 +00:00
var fileNameEscaper = strings.NewReplacer("\\", "\\\\", "\"", "\\\"")
func statusHandler(w http.ResponseWriter, r *http.Request) {
m := make(map[string]interface{})
m["Version"] = VERSION
m["Volumes"] = store.Status()
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, m)
}
2012-09-11 00:08:52 +00:00
func assignVolumeHandler(w http.ResponseWriter, r *http.Request) {
err := store.AddVolume(r.FormValue("volume"), r.FormValue("replicationType"))
if err == nil {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]string{"error": ""})
2012-09-11 00:08:52 +00:00
} else {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
2012-09-11 00:08:52 +00:00
}
2012-11-07 09:51:43 +00:00
debug("assign volume =", r.FormValue("volume"), ", replicationType =", r.FormValue("replicationType"), ", error =", err)
}
2012-11-24 01:03:27 +00:00
func vacuumVolumeCheckHandler(w http.ResponseWriter, r *http.Request) {
2012-11-26 21:12:21 +00:00
err, ret := store.CheckCompactVolume(r.FormValue("volume"), r.FormValue("garbageThreshold"))
if err == nil {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]interface{}{"error": "", "result": ret})
2012-11-26 21:12:21 +00:00
} else {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]interface{}{"error": err.Error(), "result": false})
2012-11-26 21:12:21 +00:00
}
debug("checked compacting volume =", r.FormValue("volume"), "garbageThreshold =", r.FormValue("garbageThreshold"), "vacuum =", ret)
2012-11-24 01:03:27 +00:00
}
2012-11-07 09:51:43 +00:00
func vacuumVolumeCompactHandler(w http.ResponseWriter, r *http.Request) {
err := store.CompactVolume(r.FormValue("volume"))
if err == nil {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]string{"error": ""})
2012-11-07 09:51:43 +00:00
} else {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
2012-11-07 09:51:43 +00:00
}
debug("compacted volume =", r.FormValue("volume"), ", error =", err)
}
func vacuumVolumeCommitHandler(w http.ResponseWriter, r *http.Request) {
2012-11-24 01:03:27 +00:00
err := store.CommitCompactVolume(r.FormValue("volume"))
if err == nil {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]interface{}{"error": ""})
} else {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
}
debug("commit compact volume =", r.FormValue("volume"), ", error =", err)
2012-09-11 00:08:52 +00:00
}
func freezeVolumeHandler(w http.ResponseWriter, r *http.Request) {
//TODO: notify master that this volume will be read-only
err := store.FreezeVolume(r.FormValue("volume"))
if err == nil {
writeJsonQuiet(w, r, map[string]interface{}{"error": ""})
} else {
writeJsonQuiet(w, r, map[string]string{"error": err.Error()})
}
debug("freeze volume =", r.FormValue("volume"), ", error =", err)
}
func storeHandler(w http.ResponseWriter, r *http.Request) {
2012-08-24 05:46:54 +00:00
switch r.Method {
case "GET":
2013-03-21 05:57:41 +00:00
GetOrHeadHandler(w, r, true)
case "HEAD":
GetOrHeadHandler(w, r, false)
2012-08-24 05:46:54 +00:00
case "DELETE":
DeleteHandler(w, r)
case "POST":
PostHandler(w, r)
}
}
2013-03-21 05:57:41 +00:00
func GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
2012-08-24 05:46:54 +00:00
n := new(storage.Needle)
vid, fid, filename, ext := parseURLPath(r.URL.Path)
2012-09-25 23:05:31 +00:00
volumeId, err := storage.NewVolumeId(vid)
if err != nil {
2012-09-27 19:17:27 +00:00
debug("parsing error:", err, r.URL.Path)
2012-09-25 23:05:31 +00:00
return
}
2012-08-24 05:46:54 +00:00
n.ParsePath(fid)
2012-09-27 19:17:27 +00:00
debug("volume", volumeId, "reading", n)
if !store.HasVolume(volumeId) {
2012-09-25 23:05:31 +00:00
lookupResult, err := operation.Lookup(*masterNode, volumeId)
2012-09-27 19:17:27 +00:00
debug("volume", volumeId, "found on", lookupResult, "error", err)
if err == nil {
http.Redirect(w, r, "http://"+lookupResult.Locations[0].PublicUrl+r.URL.Path, http.StatusMovedPermanently)
} else {
2012-09-27 19:17:27 +00:00
debug("lookup error:", err, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
}
return
}
2012-08-24 05:46:54 +00:00
cookie := n.Cookie
count, e := store.Read(volumeId, n)
2012-09-27 19:17:27 +00:00
debug("read bytes", count, "error", e)
if e != nil || count <= 0 {
2012-09-27 19:17:27 +00:00
debug("read error:", e, r.URL.Path)
w.WriteHeader(http.StatusNotFound)
return
2012-08-24 05:46:54 +00:00
}
if n.Cookie != cookie {
log.Println("request with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
w.WriteHeader(http.StatusNotFound)
2012-08-24 05:46:54 +00:00
return
}
if n.LastModified != 0 {
w.Header().Set("Last-Modified", time.Unix(int64(n.LastModified), 0).UTC().Format(http.TimeFormat))
if r.Header.Get("If-Modified-Since") != "" {
if t, parseError := time.Parse(http.TimeFormat, r.Header.Get("If-Modified-Since")); parseError == nil {
if t.Unix() >= int64(n.LastModified) {
w.WriteHeader(http.StatusNotModified)
return
}
}
}
}
if n.NameSize > 0 && filename == "" {
filename := string(n.Name)
dotIndex := strings.LastIndex(filename, ".")
if dotIndex > 0 {
ext = filename[dotIndex:]
}
}
mtype := ""
2012-08-24 05:46:54 +00:00
if ext != "" {
mtype = mime.TypeByExtension(ext)
}
if n.MimeSize > 0 {
mtype = string(n.Mime)
}
if mtype != "" {
2012-08-24 05:46:54 +00:00
w.Header().Set("Content-Type", mtype)
}
if filename != "" {
w.Header().Set("Content-Disposition", "filename="+fileNameEscaper.Replace(filename))
}
if ext != ".gz" {
if n.IsGzipped() {
2012-08-24 05:46:54 +00:00
if strings.Contains(r.Header.Get("Accept-Encoding"), "gzip") {
w.Header().Set("Content-Encoding", "gzip")
} else {
2013-01-17 08:56:56 +00:00
if n.Data, err = storage.UnGzipData(n.Data); err != nil {
debug("lookup error:", err, r.URL.Path)
}
2012-08-24 05:46:54 +00:00
}
}
}
w.Header().Set("Content-Length", strconv.Itoa(len(n.Data)))
2013-03-21 05:57:41 +00:00
if isGetMethod {
if _, e = w.Write(n.Data); e != nil {
debug("response write error:", e)
}
2013-02-27 06:54:22 +00:00
}
}
func PostHandler(w http.ResponseWriter, r *http.Request) {
2013-02-27 06:54:22 +00:00
if e := r.ParseForm(); e != nil {
debug("form parse error:", e)
writeJsonQuiet(w, r, e)
return
}
vid, _, _, _ := parseURLPath(r.URL.Path)
2012-09-04 03:40:38 +00:00
volumeId, e := storage.NewVolumeId(vid)
2012-08-24 05:46:54 +00:00
if e != nil {
2013-02-27 06:54:22 +00:00
debug("NewVolumeId error:", e)
writeJsonQuiet(w, r, e)
return
}
if e != nil {
writeJsonQuiet(w, r, e)
2012-08-24 05:46:54 +00:00
} else {
needle, ne := storage.NewNeedle(r)
2012-08-24 05:46:54 +00:00
if ne != nil {
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, ne)
2012-08-24 05:46:54 +00:00
} else {
ret, errorStatus := replication.ReplicatedWrite(*masterNode, store, volumeId, needle, r)
2012-09-26 21:28:46 +00:00
m := make(map[string]interface{})
if errorStatus == "" {
w.WriteHeader(http.StatusCreated)
} else {
w.WriteHeader(http.StatusInternalServerError)
m["error"] = errorStatus
}
2012-08-24 05:46:54 +00:00
m["size"] = ret
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, m)
2012-08-24 05:46:54 +00:00
}
}
}
func DeleteHandler(w http.ResponseWriter, r *http.Request) {
2012-08-24 05:46:54 +00:00
n := new(storage.Needle)
vid, fid, _, _ := parseURLPath(r.URL.Path)
2012-09-04 03:40:38 +00:00
volumeId, _ := storage.NewVolumeId(vid)
2012-08-24 05:46:54 +00:00
n.ParsePath(fid)
2012-09-27 19:17:27 +00:00
debug("deleting", n)
2012-08-24 05:46:54 +00:00
cookie := n.Cookie
count, ok := store.Read(volumeId, n)
if ok != nil {
m := make(map[string]uint32)
m["size"] = 0
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, m)
2012-08-24 05:46:54 +00:00
return
}
if n.Cookie != cookie {
log.Println("delete with unmaching cookie from ", r.RemoteAddr, "agent", r.UserAgent())
return
}
n.Size = 0
ret := replication.ReplicatedDelete(*masterNode, store, volumeId, n, r)
if ret != 0 {
w.WriteHeader(http.StatusAccepted)
2012-09-26 20:38:45 +00:00
} else {
w.WriteHeader(http.StatusInternalServerError)
2012-09-26 10:27:10 +00:00
}
2012-08-24 05:46:54 +00:00
m := make(map[string]uint32)
m["size"] = uint32(count)
2013-02-27 06:54:22 +00:00
writeJsonQuiet(w, r, m)
}
2012-09-27 19:17:27 +00:00
func parseURLPath(path string) (vid, fid, filename, ext string) {
if strings.Count(path, "/") == 3 {
parts := strings.Split(path, "/")
vid, fid, filename = parts[1], parts[2], parts[3]
2013-07-13 22:57:44 +00:00
ext = filepath.Ext(filename)
} else {
sepIndex := strings.LastIndex(path, "/")
commaIndex := strings.LastIndex(path[sepIndex:], ",")
if commaIndex <= 0 {
if "favicon.ico" != path[sepIndex+1:] {
log.Println("unknown file id", path[sepIndex+1:])
}
return
}
dotIndex := strings.LastIndex(path[sepIndex:], ".")
vid = path[sepIndex+1 : commaIndex]
fid = path[commaIndex+1:]
ext = ""
if dotIndex > 0 {
fid = path[commaIndex+1 : dotIndex]
ext = path[dotIndex:]
2012-08-24 05:46:54 +00:00
}
}
return
}
func runVolume(cmd *Command, args []string) bool {
2012-11-07 09:51:43 +00:00
if *vMaxCpu < 1 {
*vMaxCpu = runtime.NumCPU()
}
runtime.GOMAXPROCS(*vMaxCpu)
folders := strings.Split(*volumeFolders, ",")
maxCountStrings := strings.Split(*maxVolumeCounts, ",")
maxCounts := make([]int, 0)
for _, maxString := range maxCountStrings {
if max, e := strconv.Atoi(maxString); e == nil {
maxCounts = append(maxCounts, max)
} else {
log.Fatalf("The max specified in -max not a valid number %s", max)
}
}
if len(folders) != len(maxCounts) {
log.Fatalf("%d directories by -dir, but only %d max is set by -max", len(folders), len(maxCounts))
}
for _, folder := range folders {
fileInfo, err := os.Stat(folder)
if err != nil {
log.Fatalf("No Existing Folder:%s", folder)
}
if !fileInfo.IsDir() {
log.Fatalf("Volume Folder should not be a file:%s", folder)
}
perm := fileInfo.Mode().Perm()
2013-07-13 22:57:44 +00:00
log.Println("Volume Folder", folder)
log.Println("Permission:", perm)
}
2012-09-26 10:27:10 +00:00
2012-09-26 09:29:16 +00:00
if *publicUrl == "" {
2012-09-26 10:27:10 +00:00
*publicUrl = *ip + ":" + strconv.Itoa(*vport)
2012-09-26 09:29:16 +00:00
}
store = storage.NewStore(*vport, *ip, *publicUrl, folders, maxCounts)
2012-08-24 05:46:54 +00:00
defer store.Close()
http.HandleFunc("/", storeHandler)
http.HandleFunc("/status", statusHandler)
2012-09-11 00:08:52 +00:00
http.HandleFunc("/admin/assign_volume", assignVolumeHandler)
2012-11-26 21:12:21 +00:00
http.HandleFunc("/admin/vacuum_volume_check", vacuumVolumeCheckHandler)
2012-11-07 09:51:43 +00:00
http.HandleFunc("/admin/vacuum_volume_compact", vacuumVolumeCompactHandler)
http.HandleFunc("/admin/vacuum_volume_commit", vacuumVolumeCommitHandler)
http.HandleFunc("/admin/freeze_volume", freezeVolumeHandler)
2012-08-24 05:46:54 +00:00
go func() {
2012-11-26 21:12:21 +00:00
connected := true
store.SetMaster(*masterNode)
store.SetDataCenter(*dataCenter)
store.SetRack(*rack)
2012-08-24 05:46:54 +00:00
for {
err := store.Join()
2012-11-26 21:12:21 +00:00
if err == nil {
if !connected {
connected = true
log.Println("Reconnected with master")
}
} else {
if connected {
connected = false
}
}
2012-09-04 03:40:38 +00:00
time.Sleep(time.Duration(float32(*vpulse*1e3)*(1+rand.Float32())) * time.Millisecond)
2012-08-24 05:46:54 +00:00
}
}()
2012-09-08 23:25:44 +00:00
log.Println("store joined at", *masterNode)
2012-08-24 05:46:54 +00:00
2012-09-28 16:13:17 +00:00
log.Println("Start Weed volume server", VERSION, "at http://"+*ip+":"+strconv.Itoa(*vport))
srv := &http.Server{
2012-09-28 17:21:06 +00:00
Addr: ":" + strconv.Itoa(*vport),
Handler: http.DefaultServeMux,
ReadTimeout: (time.Duration(*vReadTimeout) * time.Second),
}
2012-09-28 16:13:17 +00:00
e := srv.ListenAndServe()
2012-08-24 05:46:54 +00:00
if e != nil {
2012-09-26 06:28:16 +00:00
log.Fatalf("Fail to start:%s", e.Error())
2012-08-24 05:46:54 +00:00
}
return true
}