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.

305 lines
9.6 KiB

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