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.

290 lines
9.2 KiB

6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
6 years ago
5 years ago
6 years ago
5 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "io/ioutil"
  7. "math"
  8. "os"
  9. "time"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/operation"
  12. "github.com/chrislusf/seaweedfs/weed/pb/volume_server_pb"
  13. "github.com/chrislusf/seaweedfs/weed/storage"
  14. "github.com/chrislusf/seaweedfs/weed/storage/erasure_coding"
  15. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  16. "github.com/chrislusf/seaweedfs/weed/util"
  17. )
  18. const BufferSizeLimit = 1024 * 1024 * 2
  19. // VolumeCopy copy the .idx .dat .vif files, and mount the volume
  20. func (vs *VolumeServer) VolumeCopy(ctx context.Context, req *volume_server_pb.VolumeCopyRequest) (*volume_server_pb.VolumeCopyResponse, error) {
  21. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  22. if v != nil {
  23. glog.V(0).Infof("volume %d already exists. deleted before copying...", req.VolumeId)
  24. err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId))
  25. if err != nil {
  26. return nil, fmt.Errorf("failed to delete existing volume %d: %v", req.VolumeId, err)
  27. }
  28. glog.V(0).Infof("deleted existing volume %d before copying.", req.VolumeId)
  29. }
  30. location := vs.store.FindFreeLocation()
  31. if location == nil {
  32. return nil, fmt.Errorf("no space left")
  33. }
  34. // the master will not start compaction for read-only volumes, so it is safe to just copy files directly
  35. // copy .dat and .idx files
  36. // read .idx .dat file size and timestamp
  37. // send .idx file
  38. // send .dat file
  39. // confirm size and timestamp
  40. var volFileInfoResp *volume_server_pb.ReadVolumeFileStatusResponse
  41. var dataBaseFileName, indexBaseFileName, idxFileName, datFileName string
  42. err := operation.WithVolumeServerClient(req.SourceDataNode, vs.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  43. var err error
  44. volFileInfoResp, err = client.ReadVolumeFileStatus(context.Background(),
  45. &volume_server_pb.ReadVolumeFileStatusRequest{
  46. VolumeId: req.VolumeId,
  47. })
  48. if nil != err {
  49. return fmt.Errorf("read volume file status failed, %v", err)
  50. }
  51. dataBaseFileName = storage.VolumeFileName(location.Directory, volFileInfoResp.Collection, int(req.VolumeId))
  52. indexBaseFileName = storage.VolumeFileName(location.IdxDirectory, volFileInfoResp.Collection, int(req.VolumeId))
  53. ioutil.WriteFile(dataBaseFileName+".note", []byte(fmt.Sprintf("copying from %s", req.SourceDataNode)), 0755)
  54. // println("source:", volFileInfoResp.String())
  55. if err := vs.doCopyFile(client, false, req.Collection, req.VolumeId, volFileInfoResp.CompactionRevision, volFileInfoResp.DatFileSize, dataBaseFileName, ".dat", false, true); err != nil {
  56. return err
  57. }
  58. if err := vs.doCopyFile(client, false, req.Collection, req.VolumeId, volFileInfoResp.CompactionRevision, volFileInfoResp.IdxFileSize, indexBaseFileName, ".idx", false, false); err != nil {
  59. return err
  60. }
  61. if err := vs.doCopyFile(client, false, req.Collection, req.VolumeId, volFileInfoResp.CompactionRevision, volFileInfoResp.DatFileSize, dataBaseFileName, ".vif", false, true); err != nil {
  62. return err
  63. }
  64. os.Remove(dataBaseFileName + ".note")
  65. return nil
  66. })
  67. if err != nil {
  68. return nil, err
  69. }
  70. if dataBaseFileName == "" {
  71. return nil, fmt.Errorf("not found volume %d file", req.VolumeId)
  72. }
  73. idxFileName = indexBaseFileName + ".idx"
  74. datFileName = dataBaseFileName + ".dat"
  75. defer func() {
  76. if err != nil && dataBaseFileName != "" {
  77. os.Remove(idxFileName)
  78. os.Remove(datFileName)
  79. os.Remove(dataBaseFileName + ".vif")
  80. }
  81. }()
  82. if err = checkCopyFiles(volFileInfoResp, idxFileName, datFileName); err != nil { // added by panyc16
  83. return nil, err
  84. }
  85. // mount the volume
  86. err = vs.store.MountVolume(needle.VolumeId(req.VolumeId))
  87. if err != nil {
  88. return nil, fmt.Errorf("failed to mount volume %d: %v", req.VolumeId, err)
  89. }
  90. return &volume_server_pb.VolumeCopyResponse{
  91. LastAppendAtNs: volFileInfoResp.DatFileTimestampSeconds * uint64(time.Second),
  92. }, err
  93. }
  94. func (vs *VolumeServer) doCopyFile(client volume_server_pb.VolumeServerClient, isEcVolume bool, collection string, vid, compactRevision uint32, stopOffset uint64, baseFileName, ext string, isAppend, ignoreSourceFileNotFound bool) error {
  95. copyFileClient, err := client.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  96. VolumeId: vid,
  97. Ext: ext,
  98. CompactionRevision: compactRevision,
  99. StopOffset: stopOffset,
  100. Collection: collection,
  101. IsEcVolume: isEcVolume,
  102. IgnoreSourceFileNotFound: ignoreSourceFileNotFound,
  103. })
  104. if err != nil {
  105. return fmt.Errorf("failed to start copying volume %d %s file: %v", vid, ext, err)
  106. }
  107. err = writeToFile(copyFileClient, baseFileName+ext, util.NewWriteThrottler(vs.compactionBytePerSecond), isAppend)
  108. if err != nil {
  109. return fmt.Errorf("failed to copy %s file: %v", baseFileName+ext, err)
  110. }
  111. return nil
  112. }
  113. /**
  114. only check the the differ of the file size
  115. todo: maybe should check the received count and deleted count of the volume
  116. */
  117. func checkCopyFiles(originFileInf *volume_server_pb.ReadVolumeFileStatusResponse, idxFileName, datFileName string) error {
  118. stat, err := os.Stat(idxFileName)
  119. if err != nil {
  120. return fmt.Errorf("stat idx file %s failed, %v", idxFileName, err)
  121. }
  122. if originFileInf.IdxFileSize != uint64(stat.Size()) {
  123. return fmt.Errorf("idx file %s size [%v] is not same as origin file size [%v]",
  124. idxFileName, stat.Size(), originFileInf.IdxFileSize)
  125. }
  126. stat, err = os.Stat(datFileName)
  127. if err != nil {
  128. return fmt.Errorf("get dat file info failed, %v", err)
  129. }
  130. if originFileInf.DatFileSize != uint64(stat.Size()) {
  131. return fmt.Errorf("the dat file size [%v] is not same as origin file size [%v]",
  132. stat.Size(), originFileInf.DatFileSize)
  133. }
  134. return nil
  135. }
  136. func writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string, wt *util.WriteThrottler, isAppend bool) error {
  137. glog.V(4).Infof("writing to %s", fileName)
  138. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  139. if isAppend {
  140. flags = os.O_WRONLY | os.O_CREATE
  141. }
  142. dst, err := os.OpenFile(fileName, flags, 0644)
  143. if err != nil {
  144. return nil
  145. }
  146. defer dst.Close()
  147. for {
  148. resp, receiveErr := client.Recv()
  149. if receiveErr == io.EOF {
  150. break
  151. }
  152. if receiveErr != nil {
  153. return fmt.Errorf("receiving %s: %v", fileName, receiveErr)
  154. }
  155. dst.Write(resp.FileContent)
  156. wt.MaybeSlowdown(int64(len(resp.FileContent)))
  157. }
  158. return nil
  159. }
  160. func (vs *VolumeServer) ReadVolumeFileStatus(ctx context.Context, req *volume_server_pb.ReadVolumeFileStatusRequest) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
  161. resp := &volume_server_pb.ReadVolumeFileStatusResponse{}
  162. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  163. if v == nil {
  164. return nil, fmt.Errorf("not found volume id %d", req.VolumeId)
  165. }
  166. resp.VolumeId = req.VolumeId
  167. datSize, idxSize, modTime := v.FileStat()
  168. resp.DatFileSize = datSize
  169. resp.IdxFileSize = idxSize
  170. resp.DatFileTimestampSeconds = uint64(modTime.Unix())
  171. resp.IdxFileTimestampSeconds = uint64(modTime.Unix())
  172. resp.FileCount = v.FileCount()
  173. resp.CompactionRevision = uint32(v.CompactionRevision)
  174. resp.Collection = v.Collection
  175. return resp, nil
  176. }
  177. // CopyFile client pulls the volume related file from the source server.
  178. // if req.CompactionRevision != math.MaxUint32, it ensures the compact revision is as expected
  179. // The copying still stop at req.StopOffset, but you can set it to math.MaxUint64 in order to read all data.
  180. func (vs *VolumeServer) CopyFile(req *volume_server_pb.CopyFileRequest, stream volume_server_pb.VolumeServer_CopyFileServer) error {
  181. var fileName string
  182. if !req.IsEcVolume {
  183. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  184. if v == nil {
  185. return fmt.Errorf("not found volume id %d", req.VolumeId)
  186. }
  187. if uint32(v.CompactionRevision) != req.CompactionRevision && req.CompactionRevision != math.MaxUint32 {
  188. return fmt.Errorf("volume %d is compacted", req.VolumeId)
  189. }
  190. fileName = v.FileName(req.Ext)
  191. } else {
  192. baseFileName := erasure_coding.EcShardBaseFileName(req.Collection, int(req.VolumeId)) + req.Ext
  193. for _, location := range vs.store.Locations {
  194. tName := util.Join(location.Directory, baseFileName)
  195. if util.FileExists(tName) {
  196. fileName = tName
  197. }
  198. tName = util.Join(location.IdxDirectory, baseFileName)
  199. if util.FileExists(tName) {
  200. fileName = tName
  201. }
  202. }
  203. if fileName == "" {
  204. if req.IgnoreSourceFileNotFound {
  205. return nil
  206. }
  207. return fmt.Errorf("CopyFile not found ec volume id %d", req.VolumeId)
  208. }
  209. }
  210. bytesToRead := int64(req.StopOffset)
  211. file, err := os.Open(fileName)
  212. if err != nil {
  213. if req.IgnoreSourceFileNotFound && err == os.ErrNotExist {
  214. return nil
  215. }
  216. return err
  217. }
  218. defer file.Close()
  219. buffer := make([]byte, BufferSizeLimit)
  220. for bytesToRead > 0 {
  221. bytesread, err := file.Read(buffer)
  222. // println(fileName, "read", bytesread, "bytes, with target", bytesToRead)
  223. if err != nil {
  224. if err != io.EOF {
  225. return err
  226. }
  227. // println(fileName, "read", bytesread, "bytes, with target", bytesToRead, "err", err.Error())
  228. break
  229. }
  230. if int64(bytesread) > bytesToRead {
  231. bytesread = int(bytesToRead)
  232. }
  233. err = stream.Send(&volume_server_pb.CopyFileResponse{
  234. FileContent: buffer[:bytesread],
  235. })
  236. if err != nil {
  237. // println("sending", bytesread, "bytes err", err.Error())
  238. return err
  239. }
  240. bytesToRead -= int64(bytesread)
  241. }
  242. return nil
  243. }