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.

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