You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

550 lines
17 KiB

9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
9 years ago
  1. package weed_server
  2. import (
  3. "bytes"
  4. "crypto/md5"
  5. "encoding/base64"
  6. "encoding/json"
  7. "errors"
  8. "fmt"
  9. "io"
  10. "io/ioutil"
  11. "mime/multipart"
  12. "net/http"
  13. "net/textproto"
  14. "net/url"
  15. "strings"
  16. "github.com/chrislusf/seaweedfs/weed/glog"
  17. "github.com/chrislusf/seaweedfs/weed/operation"
  18. "github.com/chrislusf/seaweedfs/weed/storage"
  19. "github.com/chrislusf/seaweedfs/weed/util"
  20. "github.com/syndtr/goleveldb/leveldb"
  21. "path"
  22. "strconv"
  23. )
  24. type FilerPostResult struct {
  25. Name string `json:"name,omitempty"`
  26. Size uint32 `json:"size,omitempty"`
  27. Error string `json:"error,omitempty"`
  28. Fid string `json:"fid,omitempty"`
  29. Url string `json:"url,omitempty"`
  30. }
  31. var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"")
  32. func escapeQuotes(s string) string {
  33. return quoteEscaper.Replace(s)
  34. }
  35. func createFormFile(writer *multipart.Writer, fieldname, filename, mime string) (io.Writer, error) {
  36. h := make(textproto.MIMEHeader)
  37. h.Set("Content-Disposition",
  38. fmt.Sprintf(`form-data; name="%s"; filename="%s"`,
  39. escapeQuotes(fieldname), escapeQuotes(filename)))
  40. if len(mime) == 0 {
  41. mime = "application/octet-stream"
  42. }
  43. h.Set("Content-Type", mime)
  44. return writer.CreatePart(h)
  45. }
  46. func makeFormData(filename, mimeType string, content io.Reader) (formData io.Reader, contentType string, err error) {
  47. buf := new(bytes.Buffer)
  48. writer := multipart.NewWriter(buf)
  49. defer writer.Close()
  50. part, err := createFormFile(writer, "file", filename, mimeType)
  51. if err != nil {
  52. glog.V(0).Infoln(err)
  53. return
  54. }
  55. _, err = io.Copy(part, content)
  56. if err != nil {
  57. glog.V(0).Infoln(err)
  58. return
  59. }
  60. formData = buf
  61. contentType = writer.FormDataContentType()
  62. return
  63. }
  64. func (fs *FilerServer) queryFileInfoByPath(w http.ResponseWriter, r *http.Request, path string) (fileId, urlLocation string, err error) {
  65. if fileId, err = fs.filer.FindFile(path); err != nil && err != leveldb.ErrNotFound {
  66. glog.V(0).Infoln("failing to find path in filer store", path, err.Error())
  67. writeJsonError(w, r, http.StatusInternalServerError, err)
  68. return
  69. } else if fileId != "" && err == nil {
  70. urlLocation, err = operation.LookupFileId(fs.getMasterNode(), fileId)
  71. if err != nil {
  72. glog.V(1).Infoln("operation LookupFileId %s failed, err is %s", fileId, err.Error())
  73. w.WriteHeader(http.StatusNotFound)
  74. return
  75. }
  76. }
  77. return
  78. }
  79. func (fs *FilerServer) assignNewFileInfo(w http.ResponseWriter, r *http.Request, replication, collection string) (fileId, urlLocation string, err error) {
  80. ar := &operation.VolumeAssignRequest{
  81. Count: 1,
  82. Replication: replication,
  83. Collection: collection,
  84. Ttl: r.URL.Query().Get("ttl"),
  85. }
  86. assignResult, ae := operation.Assign(fs.getMasterNode(), ar)
  87. if ae != nil {
  88. glog.V(0).Infoln("failing to assign a file id", ae.Error())
  89. writeJsonError(w, r, http.StatusInternalServerError, ae)
  90. err = ae
  91. return
  92. }
  93. fileId = assignResult.Fid
  94. urlLocation = "http://" + assignResult.Url + "/" + assignResult.Fid
  95. return
  96. }
  97. func (fs *FilerServer) multipartUploadAnalyzer(w http.ResponseWriter, r *http.Request, replication, collection string) (fileId, urlLocation string, err error) {
  98. //Default handle way for http multipart
  99. if r.Method == "PUT" {
  100. buf, _ := ioutil.ReadAll(r.Body)
  101. r.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
  102. fileName, _, _, _, _, _, _, pe := storage.ParseUpload(r)
  103. if pe != nil {
  104. glog.V(0).Infoln("failing to parse post body", pe.Error())
  105. writeJsonError(w, r, http.StatusInternalServerError, pe)
  106. err = pe
  107. return
  108. }
  109. //reconstruct http request body for following new request to volume server
  110. r.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
  111. path := r.URL.Path
  112. if strings.HasSuffix(path, "/") {
  113. if fileName != "" {
  114. path += fileName
  115. }
  116. }
  117. fileId, urlLocation, err = fs.queryFileInfoByPath(w, r, path)
  118. } else {
  119. fileId, urlLocation, err = fs.assignNewFileInfo(w, r, replication, collection)
  120. }
  121. return
  122. }
  123. func multipartHttpBodyBuilder(w http.ResponseWriter, r *http.Request, fileName string) (err error) {
  124. body, contentType, te := makeFormData(fileName, r.Header.Get("Content-Type"), r.Body)
  125. if te != nil {
  126. glog.V(0).Infoln("S3 protocol to raw seaweed protocol failed", te.Error())
  127. writeJsonError(w, r, http.StatusInternalServerError, te)
  128. err = te
  129. return
  130. }
  131. if body != nil {
  132. switch v := body.(type) {
  133. case *bytes.Buffer:
  134. r.ContentLength = int64(v.Len())
  135. case *bytes.Reader:
  136. r.ContentLength = int64(v.Len())
  137. case *strings.Reader:
  138. r.ContentLength = int64(v.Len())
  139. }
  140. }
  141. r.Header.Set("Content-Type", contentType)
  142. rc, ok := body.(io.ReadCloser)
  143. if !ok && body != nil {
  144. rc = ioutil.NopCloser(body)
  145. }
  146. r.Body = rc
  147. return
  148. }
  149. func checkContentMD5(w http.ResponseWriter, r *http.Request) (err error) {
  150. if contentMD5 := r.Header.Get("Content-MD5"); contentMD5 != "" {
  151. buf, _ := ioutil.ReadAll(r.Body)
  152. //checkMD5
  153. sum := md5.Sum(buf)
  154. fileDataMD5 := base64.StdEncoding.EncodeToString(sum[0:len(sum)])
  155. if strings.ToLower(fileDataMD5) != strings.ToLower(contentMD5) {
  156. glog.V(0).Infof("fileDataMD5 [%s] is not equal to Content-MD5 [%s]", fileDataMD5, contentMD5)
  157. err = fmt.Errorf("MD5 check failed")
  158. writeJsonError(w, r, http.StatusNotAcceptable, err)
  159. return
  160. }
  161. //reconstruct http request body for following new request to volume server
  162. r.Body = ioutil.NopCloser(bytes.NewBuffer(buf))
  163. }
  164. return
  165. }
  166. func (fs *FilerServer) monolithicUploadAnalyzer(w http.ResponseWriter, r *http.Request, replication, collection string) (fileId, urlLocation string, err error) {
  167. /*
  168. Amazon S3 ref link:[http://docs.aws.amazon.com/AmazonS3/latest/API/Welcome.html]
  169. There is a long way to provide a completely compatibility against all Amazon S3 API, I just made
  170. a simple data stream adapter between S3 PUT API and seaweedfs's volume storage Write API
  171. 1. The request url format should be http://$host:$port/$bucketName/$objectName
  172. 2. bucketName will be mapped to seaweedfs's collection name
  173. 3. You could customize and make your enhancement.
  174. */
  175. lastPos := strings.LastIndex(r.URL.Path, "/")
  176. if lastPos == -1 || lastPos == 0 || lastPos == len(r.URL.Path)-1 {
  177. glog.V(0).Infoln("URL Path [%s] is invalid, could not retrieve file name", r.URL.Path)
  178. err = fmt.Errorf("URL Path is invalid")
  179. writeJsonError(w, r, http.StatusInternalServerError, err)
  180. return
  181. }
  182. if err = checkContentMD5(w, r); err != nil {
  183. return
  184. }
  185. fileName := r.URL.Path[lastPos+1:]
  186. if err = multipartHttpBodyBuilder(w, r, fileName); err != nil {
  187. return
  188. }
  189. secondPos := strings.Index(r.URL.Path[1:], "/") + 1
  190. collection = r.URL.Path[1:secondPos]
  191. path := r.URL.Path
  192. if fileId, urlLocation, err = fs.queryFileInfoByPath(w, r, path); err == nil && fileId == "" {
  193. fileId, urlLocation, err = fs.assignNewFileInfo(w, r, replication, collection)
  194. }
  195. return
  196. }
  197. func (fs *FilerServer) PostHandler(w http.ResponseWriter, r *http.Request) {
  198. query := r.URL.Query()
  199. replication := query.Get("replication")
  200. if replication == "" {
  201. replication = fs.defaultReplication
  202. }
  203. collection := query.Get("collection")
  204. if collection == "" {
  205. collection = fs.collection
  206. }
  207. if autoChunked := fs.autoChunk(w, r, replication, collection); autoChunked {
  208. return
  209. }
  210. var fileId, urlLocation string
  211. var err error
  212. if strings.HasPrefix(r.Header.Get("Content-Type"), "multipart/form-data; boundary=") {
  213. fileId, urlLocation, err = fs.multipartUploadAnalyzer(w, r, replication, collection)
  214. if err != nil {
  215. return
  216. }
  217. } else {
  218. fileId, urlLocation, err = fs.monolithicUploadAnalyzer(w, r, replication, collection)
  219. if err != nil {
  220. return
  221. }
  222. }
  223. u, _ := url.Parse(urlLocation)
  224. // This allows a client to generate a chunk manifest and submit it to the filer -- it is a little off
  225. // because they need to provide FIDs instead of file paths...
  226. cm, _ := strconv.ParseBool(query.Get("cm"))
  227. if cm {
  228. q := u.Query()
  229. q.Set("cm", "true")
  230. u.RawQuery = q.Encode()
  231. }
  232. glog.V(4).Infoln("post to", u)
  233. request := &http.Request{
  234. Method: r.Method,
  235. URL: u,
  236. Proto: r.Proto,
  237. ProtoMajor: r.ProtoMajor,
  238. ProtoMinor: r.ProtoMinor,
  239. Header: r.Header,
  240. Body: r.Body,
  241. Host: r.Host,
  242. ContentLength: r.ContentLength,
  243. }
  244. resp, do_err := util.Do(request)
  245. if do_err != nil {
  246. glog.V(0).Infoln("failing to connect to volume server", r.RequestURI, do_err.Error())
  247. writeJsonError(w, r, http.StatusInternalServerError, do_err)
  248. return
  249. }
  250. defer resp.Body.Close()
  251. resp_body, ra_err := ioutil.ReadAll(resp.Body)
  252. if ra_err != nil {
  253. glog.V(0).Infoln("failing to upload to volume server", r.RequestURI, ra_err.Error())
  254. writeJsonError(w, r, http.StatusInternalServerError, ra_err)
  255. return
  256. }
  257. glog.V(4).Infoln("post result", string(resp_body))
  258. var ret operation.UploadResult
  259. unmarshal_err := json.Unmarshal(resp_body, &ret)
  260. if unmarshal_err != nil {
  261. glog.V(0).Infoln("failing to read upload resonse", r.RequestURI, string(resp_body))
  262. writeJsonError(w, r, http.StatusInternalServerError, unmarshal_err)
  263. return
  264. }
  265. if ret.Error != "" {
  266. glog.V(0).Infoln("failing to post to volume server", r.RequestURI, ret.Error)
  267. writeJsonError(w, r, http.StatusInternalServerError, errors.New(ret.Error))
  268. return
  269. }
  270. path := r.URL.Path
  271. if strings.HasSuffix(path, "/") {
  272. if ret.Name != "" {
  273. path += ret.Name
  274. } else {
  275. operation.DeleteFile(fs.getMasterNode(), fileId, fs.jwt(fileId)) //clean up
  276. glog.V(0).Infoln("Can not to write to folder", path, "without a file name!")
  277. writeJsonError(w, r, http.StatusInternalServerError,
  278. errors.New("Can not to write to folder "+path+" without a file name"))
  279. return
  280. }
  281. }
  282. // also delete the old fid unless PUT operation
  283. if r.Method != "PUT" {
  284. if oldFid, err := fs.filer.FindFile(path); err == nil {
  285. operation.DeleteFile(fs.getMasterNode(), oldFid, fs.jwt(oldFid))
  286. }
  287. }
  288. glog.V(4).Infoln("saving", path, "=>", fileId)
  289. if db_err := fs.filer.CreateFile(path, fileId); db_err != nil {
  290. operation.DeleteFile(fs.getMasterNode(), fileId, fs.jwt(fileId)) //clean up
  291. glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
  292. writeJsonError(w, r, http.StatusInternalServerError, db_err)
  293. return
  294. }
  295. reply := FilerPostResult{
  296. Name: ret.Name,
  297. Size: ret.Size,
  298. Error: ret.Error,
  299. Fid: fileId,
  300. Url: urlLocation,
  301. }
  302. writeJsonQuiet(w, r, http.StatusCreated, reply)
  303. }
  304. func (fs *FilerServer) autoChunk(w http.ResponseWriter, r *http.Request, replication string, collection string) bool {
  305. if r.Method != "POST" {
  306. glog.V(4).Infoln("AutoChunking not supported for method", r.Method)
  307. return false
  308. }
  309. // autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
  310. query := r.URL.Query()
  311. parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
  312. maxMB := int32(parsedMaxMB)
  313. if maxMB <= 0 && fs.maxMB > 0 {
  314. maxMB = int32(fs.maxMB)
  315. }
  316. if maxMB <= 0 {
  317. glog.V(4).Infoln("AutoChunking not enabled")
  318. return false
  319. }
  320. glog.V(4).Infoln("AutoChunking level set to", maxMB, "(MB)")
  321. chunkSize := 1024 * 1024 * maxMB
  322. contentLength := int64(0)
  323. if contentLengthHeader := r.Header["Content-Length"]; len(contentLengthHeader) == 1 {
  324. contentLength, _ = strconv.ParseInt(contentLengthHeader[0], 10, 64)
  325. if contentLength <= int64(chunkSize) {
  326. glog.V(4).Infoln("Content-Length of", contentLength, "is less than the chunk size of", chunkSize, "so autoChunking will be skipped.")
  327. return false
  328. }
  329. }
  330. if contentLength <= 0 {
  331. glog.V(4).Infoln("Content-Length value is missing or unexpected so autoChunking will be skipped.")
  332. return false
  333. }
  334. reply, err := fs.doAutoChunk(w, r, contentLength, chunkSize, replication, collection)
  335. if err != nil {
  336. writeJsonError(w, r, http.StatusInternalServerError, err)
  337. } else if reply != nil {
  338. writeJsonQuiet(w, r, http.StatusCreated, reply)
  339. }
  340. return true
  341. }
  342. func (fs *FilerServer) doAutoChunk(w http.ResponseWriter, r *http.Request, contentLength int64, chunkSize int32, replication string, collection string) (filerResult *FilerPostResult, replyerr error) {
  343. multipartReader, multipartReaderErr := r.MultipartReader()
  344. if multipartReaderErr != nil {
  345. return nil, multipartReaderErr
  346. }
  347. part1, part1Err := multipartReader.NextPart()
  348. if part1Err != nil {
  349. return nil, part1Err
  350. }
  351. fileName := part1.FileName()
  352. if fileName != "" {
  353. fileName = path.Base(fileName)
  354. }
  355. chunks := (int64(contentLength) / int64(chunkSize)) + 1
  356. cm := operation.ChunkManifest{
  357. Name: fileName,
  358. Size: 0, // don't know yet
  359. Mime: "application/octet-stream",
  360. Chunks: make([]*operation.ChunkInfo, 0, chunks),
  361. }
  362. totalBytesRead := int64(0)
  363. tmpBufferSize := int32(1024 * 1024)
  364. tmpBuffer := bytes.NewBuffer(make([]byte, 0, tmpBufferSize))
  365. chunkBuf := make([]byte, chunkSize+tmpBufferSize, chunkSize+tmpBufferSize) // chunk size plus a little overflow
  366. chunkBufOffset := int32(0)
  367. chunkOffset := int64(0)
  368. writtenChunks := 0
  369. filerResult = &FilerPostResult{
  370. Name: fileName,
  371. }
  372. for totalBytesRead < contentLength {
  373. tmpBuffer.Reset()
  374. bytesRead, readErr := io.CopyN(tmpBuffer, part1, int64(tmpBufferSize))
  375. readFully := readErr != nil && readErr == io.EOF
  376. tmpBuf := tmpBuffer.Bytes()
  377. bytesToCopy := tmpBuf[0:int(bytesRead)]
  378. copy(chunkBuf[chunkBufOffset:chunkBufOffset+int32(bytesRead)], bytesToCopy)
  379. chunkBufOffset = chunkBufOffset + int32(bytesRead)
  380. if chunkBufOffset >= chunkSize || readFully || (chunkBufOffset > 0 && bytesRead == 0) {
  381. writtenChunks = writtenChunks + 1
  382. fileId, urlLocation, assignErr := fs.assignNewFileInfo(w, r, replication, collection)
  383. if assignErr != nil {
  384. return nil, assignErr
  385. }
  386. // upload the chunk to the volume server
  387. chunkName := fileName + "_chunk_" + strconv.FormatInt(int64(cm.Chunks.Len()+1), 10)
  388. uploadErr := fs.doUpload(urlLocation, w, r, chunkBuf[0:chunkBufOffset], chunkName, "application/octet-stream", fileId)
  389. if uploadErr != nil {
  390. return nil, uploadErr
  391. }
  392. // Save to chunk manifest structure
  393. cm.Chunks = append(cm.Chunks,
  394. &operation.ChunkInfo{
  395. Offset: chunkOffset,
  396. Size: int64(chunkBufOffset),
  397. Fid: fileId,
  398. },
  399. )
  400. // reset variables for the next chunk
  401. chunkBufOffset = 0
  402. chunkOffset = totalBytesRead + int64(bytesRead)
  403. }
  404. totalBytesRead = totalBytesRead + int64(bytesRead)
  405. if bytesRead == 0 || readFully {
  406. break
  407. }
  408. if readErr != nil {
  409. return nil, readErr
  410. }
  411. }
  412. cm.Size = totalBytesRead
  413. manifestBuf, marshalErr := cm.Marshal()
  414. if marshalErr != nil {
  415. return nil, marshalErr
  416. }
  417. manifestStr := string(manifestBuf)
  418. glog.V(4).Infoln("Generated chunk manifest: ", manifestStr)
  419. manifestFileId, manifestUrlLocation, manifestAssignmentErr := fs.assignNewFileInfo(w, r, replication, collection)
  420. if manifestAssignmentErr != nil {
  421. return nil, manifestAssignmentErr
  422. }
  423. glog.V(4).Infoln("Manifest uploaded to:", manifestUrlLocation, "Fid:", manifestFileId)
  424. filerResult.Fid = manifestFileId
  425. u, _ := url.Parse(manifestUrlLocation)
  426. q := u.Query()
  427. q.Set("cm", "true")
  428. u.RawQuery = q.Encode()
  429. manifestUploadErr := fs.doUpload(u.String(), w, r, manifestBuf, fileName+"_manifest", "application/json", manifestFileId)
  430. if manifestUploadErr != nil {
  431. return nil, manifestUploadErr
  432. }
  433. path := r.URL.Path
  434. // also delete the old fid unless PUT operation
  435. if r.Method != "PUT" {
  436. if oldFid, err := fs.filer.FindFile(path); err == nil {
  437. operation.DeleteFile(fs.getMasterNode(), oldFid, fs.jwt(oldFid))
  438. }
  439. }
  440. glog.V(4).Infoln("saving", path, "=>", manifestFileId)
  441. if db_err := fs.filer.CreateFile(path, manifestFileId); db_err != nil {
  442. replyerr = db_err
  443. filerResult.Error = db_err.Error()
  444. operation.DeleteFile(fs.getMasterNode(), manifestFileId, fs.jwt(manifestFileId)) //clean up
  445. glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
  446. return
  447. }
  448. return
  449. }
  450. func (fs *FilerServer) doUpload(urlLocation string, w http.ResponseWriter, r *http.Request, chunkBuf []byte, fileName string, contentType string, fileId string) (err error) {
  451. err = nil
  452. ioReader := ioutil.NopCloser(bytes.NewBuffer(chunkBuf))
  453. uploadResult, uploadError := operation.Upload(urlLocation, fileName, ioReader, false, contentType, fs.jwt(fileId))
  454. if uploadResult != nil {
  455. glog.V(0).Infoln("Chunk upload result. Name:", uploadResult.Name, "Fid:", fileId, "Size:", uploadResult.Size)
  456. }
  457. if uploadError != nil {
  458. err = uploadError
  459. }
  460. return
  461. }
  462. // curl -X DELETE http://localhost:8888/path/to
  463. // curl -X DELETE http://localhost:8888/path/to?recursive=true
  464. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  465. var err error
  466. var fid string
  467. if strings.HasSuffix(r.URL.Path, "/") {
  468. isRecursive := r.FormValue("recursive") == "true"
  469. err = fs.filer.DeleteDirectory(r.URL.Path, isRecursive)
  470. } else {
  471. fid, err = fs.filer.DeleteFile(r.URL.Path)
  472. if err == nil && fid != "" {
  473. err = operation.DeleteFile(fs.getMasterNode(), fid, fs.jwt(fid))
  474. }
  475. }
  476. if err == nil {
  477. writeJsonQuiet(w, r, http.StatusAccepted, map[string]string{"error": ""})
  478. } else {
  479. glog.V(4).Infoln("deleting", r.URL.Path, ":", err.Error())
  480. writeJsonError(w, r, http.StatusInternalServerError, err)
  481. }
  482. }