filer_server_handlers_write.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554
  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. "path"
  16. "strconv"
  17. "strings"
  18. "github.com/chrislusf/seaweedfs/weed/filer"
  19. "github.com/chrislusf/seaweedfs/weed/glog"
  20. "github.com/chrislusf/seaweedfs/weed/operation"
  21. "github.com/chrislusf/seaweedfs/weed/storage"
  22. "github.com/chrislusf/seaweedfs/weed/util"
  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 != filer.ErrNotFound {
  66. glog.V(0).Infoln("failing to find path in filer store", path, err.Error())
  67. writeJsonError(w, r, http.StatusInternalServerError, err)
  68. } else if fileId != "" && err == nil {
  69. urlLocation, err = operation.LookupFileId(fs.getMasterNode(), fileId)
  70. if err != nil {
  71. glog.V(1).Infof("operation LookupFileId %s failed, err:%s", fileId, err)
  72. w.WriteHeader(http.StatusNotFound)
  73. }
  74. } else if fileId == "" && err == filer.ErrNotFound {
  75. w.WriteHeader(http.StatusNotFound)
  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).Infof("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. } else if err != nil && err != filer.ErrNotFound {
  287. glog.V(0).Infof("error %v occur when finding %s in filer store", err, path)
  288. }
  289. }
  290. glog.V(4).Infoln("saving", path, "=>", fileId)
  291. if db_err := fs.filer.CreateFile(path, fileId); db_err != nil {
  292. operation.DeleteFile(fs.getMasterNode(), fileId, fs.jwt(fileId)) //clean up
  293. glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
  294. writeJsonError(w, r, http.StatusInternalServerError, db_err)
  295. return
  296. }
  297. reply := FilerPostResult{
  298. Name: ret.Name,
  299. Size: ret.Size,
  300. Error: ret.Error,
  301. Fid: fileId,
  302. Url: urlLocation,
  303. }
  304. writeJsonQuiet(w, r, http.StatusCreated, reply)
  305. }
  306. func (fs *FilerServer) autoChunk(w http.ResponseWriter, r *http.Request, replication string, collection string) bool {
  307. if r.Method != "POST" {
  308. glog.V(4).Infoln("AutoChunking not supported for method", r.Method)
  309. return false
  310. }
  311. // autoChunking can be set at the command-line level or as a query param. Query param overrides command-line
  312. query := r.URL.Query()
  313. parsedMaxMB, _ := strconv.ParseInt(query.Get("maxMB"), 10, 32)
  314. maxMB := int32(parsedMaxMB)
  315. if maxMB <= 0 && fs.maxMB > 0 {
  316. maxMB = int32(fs.maxMB)
  317. }
  318. if maxMB <= 0 {
  319. glog.V(4).Infoln("AutoChunking not enabled")
  320. return false
  321. }
  322. glog.V(4).Infoln("AutoChunking level set to", maxMB, "(MB)")
  323. chunkSize := 1024 * 1024 * maxMB
  324. contentLength := int64(0)
  325. if contentLengthHeader := r.Header["Content-Length"]; len(contentLengthHeader) == 1 {
  326. contentLength, _ = strconv.ParseInt(contentLengthHeader[0], 10, 64)
  327. if contentLength <= int64(chunkSize) {
  328. glog.V(4).Infoln("Content-Length of", contentLength, "is less than the chunk size of", chunkSize, "so autoChunking will be skipped.")
  329. return false
  330. }
  331. }
  332. if contentLength <= 0 {
  333. glog.V(4).Infoln("Content-Length value is missing or unexpected so autoChunking will be skipped.")
  334. return false
  335. }
  336. reply, err := fs.doAutoChunk(w, r, contentLength, chunkSize, replication, collection)
  337. if err != nil {
  338. writeJsonError(w, r, http.StatusInternalServerError, err)
  339. } else if reply != nil {
  340. writeJsonQuiet(w, r, http.StatusCreated, reply)
  341. }
  342. return true
  343. }
  344. func (fs *FilerServer) doAutoChunk(w http.ResponseWriter, r *http.Request, contentLength int64, chunkSize int32, replication string, collection string) (filerResult *FilerPostResult, replyerr error) {
  345. multipartReader, multipartReaderErr := r.MultipartReader()
  346. if multipartReaderErr != nil {
  347. return nil, multipartReaderErr
  348. }
  349. part1, part1Err := multipartReader.NextPart()
  350. if part1Err != nil {
  351. return nil, part1Err
  352. }
  353. fileName := part1.FileName()
  354. if fileName != "" {
  355. fileName = path.Base(fileName)
  356. }
  357. chunks := (int64(contentLength) / int64(chunkSize)) + 1
  358. cm := operation.ChunkManifest{
  359. Name: fileName,
  360. Size: 0, // don't know yet
  361. Mime: "application/octet-stream",
  362. Chunks: make([]*operation.ChunkInfo, 0, chunks),
  363. }
  364. totalBytesRead := int64(0)
  365. tmpBufferSize := int32(1024 * 1024)
  366. tmpBuffer := bytes.NewBuffer(make([]byte, 0, tmpBufferSize))
  367. chunkBuf := make([]byte, chunkSize+tmpBufferSize, chunkSize+tmpBufferSize) // chunk size plus a little overflow
  368. chunkBufOffset := int32(0)
  369. chunkOffset := int64(0)
  370. writtenChunks := 0
  371. filerResult = &FilerPostResult{
  372. Name: fileName,
  373. }
  374. for totalBytesRead < contentLength {
  375. tmpBuffer.Reset()
  376. bytesRead, readErr := io.CopyN(tmpBuffer, part1, int64(tmpBufferSize))
  377. readFully := readErr != nil && readErr == io.EOF
  378. tmpBuf := tmpBuffer.Bytes()
  379. bytesToCopy := tmpBuf[0:int(bytesRead)]
  380. copy(chunkBuf[chunkBufOffset:chunkBufOffset+int32(bytesRead)], bytesToCopy)
  381. chunkBufOffset = chunkBufOffset + int32(bytesRead)
  382. if chunkBufOffset >= chunkSize || readFully || (chunkBufOffset > 0 && bytesRead == 0) {
  383. writtenChunks = writtenChunks + 1
  384. fileId, urlLocation, assignErr := fs.assignNewFileInfo(w, r, replication, collection)
  385. if assignErr != nil {
  386. return nil, assignErr
  387. }
  388. // upload the chunk to the volume server
  389. chunkName := fileName + "_chunk_" + strconv.FormatInt(int64(cm.Chunks.Len()+1), 10)
  390. uploadErr := fs.doUpload(urlLocation, w, r, chunkBuf[0:chunkBufOffset], chunkName, "application/octet-stream", fileId)
  391. if uploadErr != nil {
  392. return nil, uploadErr
  393. }
  394. // Save to chunk manifest structure
  395. cm.Chunks = append(cm.Chunks,
  396. &operation.ChunkInfo{
  397. Offset: chunkOffset,
  398. Size: int64(chunkBufOffset),
  399. Fid: fileId,
  400. },
  401. )
  402. // reset variables for the next chunk
  403. chunkBufOffset = 0
  404. chunkOffset = totalBytesRead + int64(bytesRead)
  405. }
  406. totalBytesRead = totalBytesRead + int64(bytesRead)
  407. if bytesRead == 0 || readFully {
  408. break
  409. }
  410. if readErr != nil {
  411. return nil, readErr
  412. }
  413. }
  414. cm.Size = totalBytesRead
  415. manifestBuf, marshalErr := cm.Marshal()
  416. if marshalErr != nil {
  417. return nil, marshalErr
  418. }
  419. manifestStr := string(manifestBuf)
  420. glog.V(4).Infoln("Generated chunk manifest: ", manifestStr)
  421. manifestFileId, manifestUrlLocation, manifestAssignmentErr := fs.assignNewFileInfo(w, r, replication, collection)
  422. if manifestAssignmentErr != nil {
  423. return nil, manifestAssignmentErr
  424. }
  425. glog.V(4).Infoln("Manifest uploaded to:", manifestUrlLocation, "Fid:", manifestFileId)
  426. filerResult.Fid = manifestFileId
  427. u, _ := url.Parse(manifestUrlLocation)
  428. q := u.Query()
  429. q.Set("cm", "true")
  430. u.RawQuery = q.Encode()
  431. manifestUploadErr := fs.doUpload(u.String(), w, r, manifestBuf, fileName+"_manifest", "application/json", manifestFileId)
  432. if manifestUploadErr != nil {
  433. return nil, manifestUploadErr
  434. }
  435. path := r.URL.Path
  436. // also delete the old fid unless PUT operation
  437. if r.Method != "PUT" {
  438. if oldFid, err := fs.filer.FindFile(path); err == nil {
  439. operation.DeleteFile(fs.getMasterNode(), oldFid, fs.jwt(oldFid))
  440. } else if err != nil && err != filer.ErrNotFound {
  441. glog.V(0).Infof("error %v occur when finding %s in filer store", err, path)
  442. }
  443. }
  444. glog.V(4).Infoln("saving", path, "=>", manifestFileId)
  445. if db_err := fs.filer.CreateFile(path, manifestFileId); db_err != nil {
  446. replyerr = db_err
  447. filerResult.Error = db_err.Error()
  448. operation.DeleteFile(fs.getMasterNode(), manifestFileId, fs.jwt(manifestFileId)) //clean up
  449. glog.V(0).Infof("failing to write %s to filer server : %v", path, db_err)
  450. return
  451. }
  452. return
  453. }
  454. func (fs *FilerServer) doUpload(urlLocation string, w http.ResponseWriter, r *http.Request, chunkBuf []byte, fileName string, contentType string, fileId string) (err error) {
  455. err = nil
  456. ioReader := ioutil.NopCloser(bytes.NewBuffer(chunkBuf))
  457. uploadResult, uploadError := operation.Upload(urlLocation, fileName, ioReader, false, contentType, nil, fs.jwt(fileId))
  458. if uploadResult != nil {
  459. glog.V(0).Infoln("Chunk upload result. Name:", uploadResult.Name, "Fid:", fileId, "Size:", uploadResult.Size)
  460. }
  461. if uploadError != nil {
  462. err = uploadError
  463. }
  464. return
  465. }
  466. // curl -X DELETE http://localhost:8888/path/to
  467. // curl -X DELETE http://localhost:8888/path/to/?recursive=true
  468. func (fs *FilerServer) DeleteHandler(w http.ResponseWriter, r *http.Request) {
  469. var err error
  470. var fid string
  471. if strings.HasSuffix(r.URL.Path, "/") {
  472. isRecursive := r.FormValue("recursive") == "true"
  473. err = fs.filer.DeleteDirectory(r.URL.Path, isRecursive)
  474. } else {
  475. fid, err = fs.filer.DeleteFile(r.URL.Path)
  476. if err == nil && fid != "" {
  477. err = operation.DeleteFile(fs.getMasterNode(), fid, fs.jwt(fid))
  478. }
  479. }
  480. if err == nil {
  481. writeJsonQuiet(w, r, http.StatusAccepted, map[string]string{"error": ""})
  482. } else {
  483. glog.V(4).Infoln("deleting", r.URL.Path, ":", err.Error())
  484. writeJsonError(w, r, http.StatusInternalServerError, err)
  485. }
  486. }