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.

403 lines
14 KiB

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