volume_grpc_copy.go 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math"
  7. "os"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  10. "github.com/seaweedfs/seaweedfs/weed/storage/backend"
  11. "github.com/seaweedfs/seaweedfs/weed/glog"
  12. "github.com/seaweedfs/seaweedfs/weed/operation"
  13. "github.com/seaweedfs/seaweedfs/weed/pb"
  14. "github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
  15. "github.com/seaweedfs/seaweedfs/weed/storage"
  16. "github.com/seaweedfs/seaweedfs/weed/storage/erasure_coding"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  18. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  19. "github.com/seaweedfs/seaweedfs/weed/util"
  20. )
  21. const BufferSizeLimit = 1024 * 1024 * 2
  22. // VolumeCopy copy the .idx .dat .vif files, and mount the volume
  23. func (vs *VolumeServer) VolumeCopy(req *volume_server_pb.VolumeCopyRequest, stream volume_server_pb.VolumeServer_VolumeCopyServer) error {
  24. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  25. if v != nil {
  26. glog.V(0).Infof("volume %d already exists. deleted before copying...", req.VolumeId)
  27. err := vs.store.DeleteVolume(needle.VolumeId(req.VolumeId))
  28. if err != nil {
  29. return fmt.Errorf("failed to delete existing volume %d: %v", req.VolumeId, err)
  30. }
  31. glog.V(0).Infof("deleted existing volume %d before copying.", req.VolumeId)
  32. }
  33. // the master will not start compaction for read-only volumes, so it is safe to just copy files directly
  34. // copy .dat and .idx files
  35. // read .idx .dat file size and timestamp
  36. // send .idx file
  37. // send .dat file
  38. // confirm size and timestamp
  39. var volFileInfoResp *volume_server_pb.ReadVolumeFileStatusResponse
  40. var dataBaseFileName, indexBaseFileName, idxFileName, datFileName string
  41. err := operation.WithVolumeServerClient(true, pb.ServerAddress(req.SourceDataNode), vs.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  42. var err error
  43. volFileInfoResp, err = client.ReadVolumeFileStatus(context.Background(),
  44. &volume_server_pb.ReadVolumeFileStatusRequest{
  45. VolumeId: req.VolumeId,
  46. })
  47. if nil != err {
  48. return fmt.Errorf("read volume file status failed, %v", err)
  49. }
  50. diskType := volFileInfoResp.DiskType
  51. if req.DiskType != "" {
  52. diskType = req.DiskType
  53. }
  54. location := vs.store.FindFreeLocation(types.ToDiskType(diskType))
  55. if location == nil {
  56. return fmt.Errorf("no space left for disk type %s", types.ToDiskType(diskType).ReadableString())
  57. }
  58. dataBaseFileName = storage.VolumeFileName(location.Directory, volFileInfoResp.Collection, int(req.VolumeId))
  59. indexBaseFileName = storage.VolumeFileName(location.IdxDirectory, volFileInfoResp.Collection, int(req.VolumeId))
  60. util.WriteFile(dataBaseFileName+".note", []byte(fmt.Sprintf("copying from %s", req.SourceDataNode)), 0755)
  61. defer func() {
  62. if err != nil {
  63. os.Remove(dataBaseFileName + ".dat")
  64. os.Remove(indexBaseFileName + ".idx")
  65. os.Remove(dataBaseFileName + ".vif")
  66. os.Remove(dataBaseFileName + ".note")
  67. }
  68. }()
  69. var preallocateSize int64
  70. if grpcErr := pb.WithMasterClient(false, vs.GetMaster(), vs.grpcDialOption, false, func(client master_pb.SeaweedClient) error {
  71. resp, err := client.GetMasterConfiguration(context.Background(), &master_pb.GetMasterConfigurationRequest{})
  72. if err != nil {
  73. return fmt.Errorf("get master %s configuration: %v", vs.GetMaster(), err)
  74. }
  75. if resp.VolumePreallocate {
  76. preallocateSize = int64(resp.VolumeSizeLimitMB) * (1 << 20)
  77. }
  78. return nil
  79. }); grpcErr != nil {
  80. glog.V(0).Infof("connect to %s: %v", vs.GetMaster(), grpcErr)
  81. }
  82. if preallocateSize > 0 {
  83. volumeFile := dataBaseFileName + ".dat"
  84. _, err := backend.CreateVolumeFile(volumeFile, preallocateSize, 0)
  85. if err != nil {
  86. return fmt.Errorf("create volume file %s: %v", volumeFile, err)
  87. }
  88. }
  89. // println("source:", volFileInfoResp.String())
  90. copyResponse := &volume_server_pb.VolumeCopyResponse{}
  91. reportInterval := int64(1024 * 1024 * 128)
  92. nextReportTarget := reportInterval
  93. var modifiedTsNs int64
  94. var sendErr error
  95. var ioBytePerSecond int64
  96. if req.IoBytePerSecond <= 0 {
  97. ioBytePerSecond = vs.compactionBytePerSecond
  98. } else {
  99. ioBytePerSecond = req.IoBytePerSecond
  100. }
  101. throttler := util.NewWriteThrottler(ioBytePerSecond)
  102. if modifiedTsNs, err = vs.doCopyFileWithThrottler(client, false, req.Collection, req.VolumeId, volFileInfoResp.CompactionRevision, volFileInfoResp.DatFileSize, dataBaseFileName, ".dat", false, true, func(processed int64) bool {
  103. if processed > nextReportTarget {
  104. copyResponse.ProcessedBytes = processed
  105. if sendErr = stream.Send(copyResponse); sendErr != nil {
  106. return false
  107. }
  108. nextReportTarget = processed + reportInterval
  109. }
  110. return true
  111. }, throttler); err != nil {
  112. return err
  113. }
  114. if sendErr != nil {
  115. return sendErr
  116. }
  117. if modifiedTsNs > 0 {
  118. os.Chtimes(dataBaseFileName+".dat", time.Unix(0, modifiedTsNs), time.Unix(0, modifiedTsNs))
  119. }
  120. if modifiedTsNs, err = vs.doCopyFileWithThrottler(client, false, req.Collection, req.VolumeId, volFileInfoResp.CompactionRevision, volFileInfoResp.IdxFileSize, indexBaseFileName, ".idx", false, false, nil, throttler); err != nil {
  121. return err
  122. }
  123. if modifiedTsNs > 0 {
  124. os.Chtimes(indexBaseFileName+".idx", time.Unix(0, modifiedTsNs), time.Unix(0, modifiedTsNs))
  125. }
  126. if modifiedTsNs, err = vs.doCopyFileWithThrottler(client, false, req.Collection, req.VolumeId, volFileInfoResp.CompactionRevision, volFileInfoResp.DatFileSize, dataBaseFileName, ".vif", false, true, nil, throttler); err != nil {
  127. return err
  128. }
  129. if modifiedTsNs > 0 {
  130. os.Chtimes(dataBaseFileName+".vif", time.Unix(0, modifiedTsNs), time.Unix(0, modifiedTsNs))
  131. }
  132. os.Remove(dataBaseFileName + ".note")
  133. return nil
  134. })
  135. if err != nil {
  136. return err
  137. }
  138. if dataBaseFileName == "" {
  139. return fmt.Errorf("not found volume %d file", req.VolumeId)
  140. }
  141. idxFileName = indexBaseFileName + ".idx"
  142. datFileName = dataBaseFileName + ".dat"
  143. defer func() {
  144. if err != nil && dataBaseFileName != "" {
  145. os.Remove(idxFileName)
  146. os.Remove(datFileName)
  147. os.Remove(dataBaseFileName + ".vif")
  148. }
  149. }()
  150. if err = checkCopyFiles(volFileInfoResp, idxFileName, datFileName); err != nil { // added by panyc16
  151. return err
  152. }
  153. // mount the volume
  154. err = vs.store.MountVolume(needle.VolumeId(req.VolumeId))
  155. if err != nil {
  156. return fmt.Errorf("failed to mount volume %d: %v", req.VolumeId, err)
  157. }
  158. if err = stream.Send(&volume_server_pb.VolumeCopyResponse{
  159. LastAppendAtNs: volFileInfoResp.DatFileTimestampSeconds * uint64(time.Second),
  160. }); err != nil {
  161. glog.Errorf("send response: %v", err)
  162. }
  163. return err
  164. }
  165. func (vs *VolumeServer) doCopyFile(client volume_server_pb.VolumeServerClient, isEcVolume bool, collection string, vid, compactRevision uint32, stopOffset uint64, baseFileName, ext string, isAppend, ignoreSourceFileNotFound bool, progressFn storage.ProgressFunc) (modifiedTsNs int64, err error) {
  166. return vs.doCopyFileWithThrottler(client, isEcVolume, collection, vid, compactRevision, stopOffset, baseFileName, ext, isAppend, ignoreSourceFileNotFound, progressFn, util.NewWriteThrottler(vs.compactionBytePerSecond))
  167. }
  168. func (vs *VolumeServer) doCopyFileWithThrottler(client volume_server_pb.VolumeServerClient, isEcVolume bool, collection string, vid, compactRevision uint32, stopOffset uint64, baseFileName, ext string, isAppend, ignoreSourceFileNotFound bool, progressFn storage.ProgressFunc, throttler *util.WriteThrottler) (modifiedTsNs int64, err error) {
  169. copyFileClient, err := client.CopyFile(context.Background(), &volume_server_pb.CopyFileRequest{
  170. VolumeId: vid,
  171. Ext: ext,
  172. CompactionRevision: compactRevision,
  173. StopOffset: stopOffset,
  174. Collection: collection,
  175. IsEcVolume: isEcVolume,
  176. IgnoreSourceFileNotFound: ignoreSourceFileNotFound,
  177. })
  178. if err != nil {
  179. return modifiedTsNs, fmt.Errorf("failed to start copying volume %d %s file: %v", vid, ext, err)
  180. }
  181. modifiedTsNs, err = writeToFile(copyFileClient, baseFileName+ext, throttler, isAppend, progressFn)
  182. if err != nil {
  183. return modifiedTsNs, fmt.Errorf("failed to copy %s file: %v", baseFileName+ext, err)
  184. }
  185. return modifiedTsNs, nil
  186. }
  187. /*
  188. *
  189. only check the the differ of the file size
  190. todo: maybe should check the received count and deleted count of the volume
  191. */
  192. func checkCopyFiles(originFileInf *volume_server_pb.ReadVolumeFileStatusResponse, idxFileName, datFileName string) error {
  193. stat, err := os.Stat(idxFileName)
  194. if err != nil {
  195. return fmt.Errorf("stat idx file %s failed: %v", idxFileName, err)
  196. }
  197. if originFileInf.IdxFileSize != uint64(stat.Size()) {
  198. return fmt.Errorf("idx file %s size [%v] is not same as origin file size [%v]",
  199. idxFileName, stat.Size(), originFileInf.IdxFileSize)
  200. }
  201. stat, err = os.Stat(datFileName)
  202. if err != nil {
  203. return fmt.Errorf("get dat file info failed, %v", err)
  204. }
  205. if originFileInf.DatFileSize != uint64(stat.Size()) {
  206. return fmt.Errorf("the dat file size [%v] is not same as origin file size [%v]",
  207. stat.Size(), originFileInf.DatFileSize)
  208. }
  209. return nil
  210. }
  211. func writeToFile(client volume_server_pb.VolumeServer_CopyFileClient, fileName string, wt *util.WriteThrottler, isAppend bool, progressFn storage.ProgressFunc) (modifiedTsNs int64, err error) {
  212. glog.V(4).Infof("writing to %s", fileName)
  213. flags := os.O_WRONLY | os.O_CREATE | os.O_TRUNC
  214. if isAppend {
  215. flags = os.O_WRONLY | os.O_CREATE
  216. }
  217. dst, err := os.OpenFile(fileName, flags, 0644)
  218. if err != nil {
  219. return modifiedTsNs, nil
  220. }
  221. defer dst.Close()
  222. var progressedBytes int64
  223. for {
  224. resp, receiveErr := client.Recv()
  225. if receiveErr == io.EOF {
  226. break
  227. }
  228. if resp != nil && resp.ModifiedTsNs != 0 {
  229. modifiedTsNs = resp.ModifiedTsNs
  230. }
  231. if receiveErr != nil {
  232. return modifiedTsNs, fmt.Errorf("receiving %s: %v", fileName, receiveErr)
  233. }
  234. dst.Write(resp.FileContent)
  235. progressedBytes += int64(len(resp.FileContent))
  236. if progressFn != nil {
  237. if !progressFn(progressedBytes) {
  238. return modifiedTsNs, fmt.Errorf("interrupted copy operation")
  239. }
  240. }
  241. wt.MaybeSlowdown(int64(len(resp.FileContent)))
  242. }
  243. return modifiedTsNs, nil
  244. }
  245. func (vs *VolumeServer) ReadVolumeFileStatus(ctx context.Context, req *volume_server_pb.ReadVolumeFileStatusRequest) (*volume_server_pb.ReadVolumeFileStatusResponse, error) {
  246. resp := &volume_server_pb.ReadVolumeFileStatusResponse{}
  247. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  248. if v == nil {
  249. return nil, fmt.Errorf("not found volume id %d", req.VolumeId)
  250. }
  251. resp.VolumeId = req.VolumeId
  252. datSize, idxSize, modTime := v.FileStat()
  253. resp.DatFileSize = datSize
  254. resp.IdxFileSize = idxSize
  255. resp.DatFileTimestampSeconds = uint64(modTime.Unix())
  256. resp.IdxFileTimestampSeconds = uint64(modTime.Unix())
  257. resp.FileCount = v.FileCount()
  258. resp.CompactionRevision = uint32(v.CompactionRevision)
  259. resp.Collection = v.Collection
  260. resp.DiskType = string(v.DiskType())
  261. return resp, nil
  262. }
  263. // CopyFile client pulls the volume related file from the source server.
  264. // if req.CompactionRevision != math.MaxUint32, it ensures the compact revision is as expected
  265. // The copying still stop at req.StopOffset, but you can set it to math.MaxUint64 in order to read all data.
  266. func (vs *VolumeServer) CopyFile(req *volume_server_pb.CopyFileRequest, stream volume_server_pb.VolumeServer_CopyFileServer) error {
  267. var fileName string
  268. if !req.IsEcVolume {
  269. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  270. if v == nil {
  271. return fmt.Errorf("not found volume id %d", req.VolumeId)
  272. }
  273. if uint32(v.CompactionRevision) != req.CompactionRevision && req.CompactionRevision != math.MaxUint32 {
  274. return fmt.Errorf("volume %d is compacted", req.VolumeId)
  275. }
  276. v.SyncToDisk()
  277. fileName = v.FileName(req.Ext)
  278. } else {
  279. baseFileName := erasure_coding.EcShardBaseFileName(req.Collection, int(req.VolumeId)) + req.Ext
  280. for _, location := range vs.store.Locations {
  281. tName := util.Join(location.Directory, baseFileName)
  282. if util.FileExists(tName) {
  283. fileName = tName
  284. }
  285. tName = util.Join(location.IdxDirectory, baseFileName)
  286. if util.FileExists(tName) {
  287. fileName = tName
  288. }
  289. }
  290. if fileName == "" {
  291. if req.IgnoreSourceFileNotFound {
  292. return nil
  293. }
  294. return fmt.Errorf("CopyFile not found ec volume id %d", req.VolumeId)
  295. }
  296. }
  297. bytesToRead := int64(req.StopOffset)
  298. file, err := os.Open(fileName)
  299. if err != nil {
  300. if req.IgnoreSourceFileNotFound && err == os.ErrNotExist {
  301. return nil
  302. }
  303. return err
  304. }
  305. defer file.Close()
  306. fileInfo, err := file.Stat()
  307. if err != nil {
  308. return err
  309. }
  310. fileModTsNs := fileInfo.ModTime().UnixNano()
  311. buffer := make([]byte, BufferSizeLimit)
  312. for bytesToRead > 0 {
  313. bytesread, err := file.Read(buffer)
  314. // println(fileName, "read", bytesread, "bytes, with target", bytesToRead)
  315. if err != nil {
  316. if err != io.EOF {
  317. return err
  318. }
  319. // println(fileName, "read", bytesread, "bytes, with target", bytesToRead, "err", err.Error())
  320. break
  321. }
  322. if int64(bytesread) > bytesToRead {
  323. bytesread = int(bytesToRead)
  324. }
  325. err = stream.Send(&volume_server_pb.CopyFileResponse{
  326. FileContent: buffer[:bytesread],
  327. ModifiedTsNs: fileModTsNs,
  328. })
  329. if err != nil {
  330. // println("sending", bytesread, "bytes err", err.Error())
  331. return err
  332. }
  333. fileModTsNs = 0 // only send once
  334. bytesToRead -= int64(bytesread)
  335. }
  336. return nil
  337. }