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.

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