Exemplo n.º 1
0
func (fs *FilerServer) GetOrHeadHandler(w http.ResponseWriter, r *http.Request, isGetMethod bool) {
	if strings.HasSuffix(r.URL.Path, "/") {
		if fs.disableDirListing {
			w.WriteHeader(http.StatusMethodNotAllowed)
			return
		}
		fs.listDirectoryHandler(w, r)
		return
	}

	fileId, err := fs.filer.FindFile(r.URL.Path)
	if err == leveldb.ErrNotFound {
		glog.V(3).Infoln("Not found in db", r.URL.Path)
		w.WriteHeader(http.StatusNotFound)
		return
	}
	query := r.URL.Query()
	collection := query.Get("collection")
	if collection == "" {
		collection = fs.collection
	}
	urlString, err := operation.LookupFileId(fs.master, fileId, collection, true)
	if err != nil {
		glog.V(1).Infoln("operation LookupFileId %s failed, err is %s", fileId, err.Error())
		w.WriteHeader(http.StatusNotFound)
		return
	}

	if fs.redirectOnRead {
		http.Redirect(w, r, urlString, http.StatusFound)
		return
	}
	u, _ := url.Parse(urlString)
	request := &http.Request{
		Method:        r.Method,
		URL:           u,
		Proto:         r.Proto,
		ProtoMajor:    r.ProtoMajor,
		ProtoMinor:    r.ProtoMinor,
		Header:        r.Header,
		Body:          r.Body,
		Host:          r.Host,
		ContentLength: r.ContentLength,
	}
	glog.V(3).Infoln("retrieving from", u)
	resp, do_err := util.HttpDo(request)
	if do_err != nil {
		glog.V(0).Infoln("failing to connect to volume server", do_err.Error())
		writeJsonError(w, r, http.StatusInternalServerError, do_err)
		return
	}
	defer resp.Body.Close()
	for k, v := range resp.Header {
		w.Header()[k] = v
	}
	w.WriteHeader(resp.StatusCode)
	io.Copy(w, resp.Body)
}
Exemplo n.º 2
0
func (cf *ChunkedFileReader) readRemoteChunkNeedle(fid string, w io.Writer, offset int64) (written int64, e error) {
	// stream data
	fileUrl, lookupError := operation.LookupFileId(cf.Master, fid, cf.Collection, true)
	if lookupError != nil {
		return 0, lookupError
	}

	req, err := http.NewRequest("GET", fileUrl, nil)
	if err != nil {
		return written, err
	}
	if offset > 0 {
		req.Header.Set("Range", fmt.Sprintf("bytes=%d-", offset))
	}

	resp, err := util.HttpDo(req)
	if err != nil {
		return written, err
	}
	defer resp.Body.Close()

	switch resp.StatusCode {
	case http.StatusRequestedRangeNotSatisfiable:
		return written, ErrInvalidRange
	case http.StatusOK:
		if offset > 0 {
			return written, ErrRangeRequestsNotSupported
		}
	case http.StatusPartialContent:
		break
	default:
		return written, fmt.Errorf("Read chunk needle error: [%d] %s", resp.StatusCode, fileUrl)

	}
	return io.Copy(w, resp.Body)
}
Exemplo n.º 3
0
func (s *Store) ReadRemoteNeedle(fid *FileId, collection string) (*Needle, error) {
	cacheKey := fid.String()
	if cn, cacheHit := s.needleCache.Get(cacheKey); cacheHit {
		glog.V(2).Infoln("Remote needle cache hit:", fid)
		return cn.(*Needle), nil
	}
	glog.V(2).Infoln("Remote needle cache miss:", fid)

	vid := fid.VolumeId.String()
	lookupResult, err := operation.Lookup(s.GetMaster(), vid, collection)
	glog.V(2).Infoln("volume", vid, "found on", lookupResult, "error", err)
	if err != nil || len(lookupResult.Locations) == 0 {
		return nil, errors.New("lookup error:" + err.Error())
	}
	u, _ := url.Parse(util.NormalizeUrl(lookupResult.Locations.PickForRead().Url))
	u.Path = "/admin/sync/needle"
	args := url.Values{
		"volume": {vid},
		"nid":    {fid.Nid()},
	}
	u.RawQuery = args.Encode()
	req, _ := http.NewRequest("GET", u.String(), nil)
	resp, err := util.HttpDo(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var buf []byte
	if buf, err = ioutil.ReadAll(resp.Body); err != nil {
		return nil, err
	}
	if resp.StatusCode != http.StatusOK {
		errMsg := strconv.Itoa(resp.StatusCode)
		m := map[string]string{}
		if e := json.Unmarshal(buf, &m); e == nil {
			if s, ok := m["error"]; ok {
				errMsg += ", " + s
			}
		}
		return nil, errors.New(errMsg)
	}
	n := &Needle{
		Cookie: fid.Cookie,
		Id:     fid.Key,
	}
	n.Data = buf
	n.DataSize = uint32(len(n.Data))
	if h := resp.Header.Get("Seaweed-Flags"); h != "" {
		if i, err := strconv.ParseInt(h, 16, 64); err == nil {
			n.Flags = byte(i)
		}
	}
	if h := resp.Header.Get("Seaweed-Checksum"); h != "" {
		if i, err := strconv.ParseInt(h, 16, 64); err == nil {
			n.Checksum = CRC(i)
			newChecksum := NewCRC(n.Data)
			if n.Checksum != newChecksum {
				return nil, fmt.Errorf("CRC error! Read remote data corrupted (%x!=%x), fid=%v",
					n.Checksum, newChecksum, fid.String())
			}
		}
	}

	if h := resp.Header.Get("Seaweed-LastModified"); h != "" {
		if i, err := strconv.ParseUint(h, 16, 64); err == nil {
			n.LastModified = i
			n.SetHasLastModifiedDate()
		}
	}
	if h := resp.Header.Get("Seaweed-Name"); h != "" {
		n.Name = []byte(h)
		n.SetHasName()
	}
	if h := resp.Header.Get("Seaweed-Mime"); h != "" {
		n.Mime = []byte(h)
		n.SetHasMime()
	}
	s.needleCache.Add(cacheKey, n)
	return n, nil
}
Exemplo n.º 4
0
func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request) {
	query := r.URL.Query()
	replication := query.Get("replication")
	if replication == "" {
		replication = fs.defaultReplication
	}
	collection := query.Get("collection")
	if collection == "" {
		collection = fs.collection
	}

	var fileId string
	var err error
	var urlLocation string
	if r.Method == "PUT" {
		buf, _ := ioutil.ReadAll(r.Body)
		r.Body = analogueReader{bytes.NewBuffer(buf)}
		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)
			return
		}
		//reconstruct http request body for following new request to volume server
		r.Body = analogueReader{bytes.NewBuffer(buf)}

		path := r.URL.Path
		if strings.HasSuffix(path, "/") {
			if fileName != "" {
				path += fileName
			}
		}

		if fileId, err = fs.filer.FindFile(path); err != nil && err != leveldb.ErrNotFound {
			glog.V(0).Infoln("failing to find path in filer store", path, err.Error())
			writeJsonError(w, r, http.StatusInternalServerError, err)
			return
		} else if fileId != "" && err == nil {
			var le error
			urlLocation, le = operation.LookupFileId(fs.master, fileId, collection, false)
			if le != nil {
				glog.V(1).Infoln("operation LookupFileId %s failed, err is %s", fileId, le.Error())
				w.WriteHeader(http.StatusNotFound)
				return
			}
		}
	} else {
		assignResult, ae := operation.Assign(fs.master, 1, replication, collection, query.Get("ttl"))
		if ae != nil {
			glog.V(0).Infoln("failing to assign a file id", ae.Error())
			writeJsonError(w, r, http.StatusInternalServerError, ae)
			return
		}
		fileId = assignResult.Fid
		urlLocation = "http://" + assignResult.Url + "/" + assignResult.Fid
	}

	u, _ := url.Parse(urlLocation)
	glog.V(4).Infoln("post to", u)
	request := &http.Request{
		Method:        r.Method,
		URL:           u,
		Proto:         r.Proto,
		ProtoMajor:    r.ProtoMajor,
		ProtoMinor:    r.ProtoMinor,
		Header:        r.Header,
		Body:          r.Body,
		Host:          r.Host,
		ContentLength: r.ContentLength,
	}
	resp, do_err := util.HttpDo(request)
	if do_err != nil {
		glog.V(0).Infoln("failing to connect to volume server", r.RequestURI, do_err.Error())
		writeJsonError(w, r, http.StatusInternalServerError, do_err)
		return
	}
	defer resp.Body.Close()
	resp_body, ra_err := ioutil.ReadAll(resp.Body)
	if ra_err != nil {
		glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, ra_err.Error())
		writeJsonError(w, r, http.StatusInternalServerError, ra_err)
		return
	}
	glog.V(4).Infoln("post result", string(resp_body))
	var ret operation.UploadResult
	unmarshal_err := json.Unmarshal(resp_body, &ret)
	if unmarshal_err != nil {
		glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(resp_body))
		writeJsonError(w, r, http.StatusInternalServerError, unmarshal_err)
		return
	}
	if ret.Error != "" {
		glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
		writeJsonError(w, r, http.StatusInternalServerError, errors.New(ret.Error))
		return
	}
	path := r.URL.Path
	if strings.HasSuffix(path, "/") {
		if ret.Name != "" {
			path += ret.Name
		} else {
			operation.DeleteFile(fs.master, fileId, collection, fs.jwt(fileId)) //clean up
			glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
			writeJsonError(w, r, http.StatusInternalServerError,
				errors.New("Can not to write to folder "+path+" without a file name"))
			return
		}
	}
	glog.V(4).Infoln("saving", path, "=>", fileId)
	if db_err := fs.filer.CreateFile(path, fileId); db_err != nil {
		operation.DeleteFile(fs.master, fileId, collection, fs.jwt(fileId)) //clean up
		glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
		writeJsonError(w, r, http.StatusInternalServerError, db_err)
		return
	}
	w.WriteHeader(http.StatusCreated)
	w.Write(resp_body)
}