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.

476 lines
15 KiB

4 years ago
2 years ago
2 years ago
6 years ago
6 years ago
4 years ago
4 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "io"
  6. "math"
  7. "os"
  8. "path"
  9. "strings"
  10. "time"
  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/storage/volume_info"
  20. "github.com/seaweedfs/seaweedfs/weed/util"
  21. )
  22. /*
  23. Steps to apply erasure coding to .dat .idx files
  24. 0. ensure the volume is readonly
  25. 1. client call VolumeEcShardsGenerate to generate the .ecx and .ec00 ~ .ec13 files
  26. 2. client ask master for possible servers to hold the ec files
  27. 3. client call VolumeEcShardsCopy on above target servers to copy ec files from the source server
  28. 4. target servers report the new ec files to the master
  29. 5. master stores vid -> [14]*DataNode
  30. 6. client checks master. If all 14 slices are ready, delete the original .idx, .idx files
  31. */
  32. // VolumeEcShardsGenerate generates the .ecx and .ec00 ~ .ec13 files
  33. func (vs *VolumeServer) VolumeEcShardsGenerate(ctx context.Context, req *volume_server_pb.VolumeEcShardsGenerateRequest) (*volume_server_pb.VolumeEcShardsGenerateResponse, error) {
  34. glog.V(0).Infof("VolumeEcShardsGenerate: %v", req)
  35. v := vs.store.GetVolume(needle.VolumeId(req.VolumeId))
  36. if v == nil {
  37. return nil, fmt.Errorf("volume %d not found", req.VolumeId)
  38. }
  39. baseFileName := v.DataFileName()
  40. if v.Collection != req.Collection {
  41. return nil, fmt.Errorf("existing collection:%v unexpected input: %v", v.Collection, req.Collection)
  42. }
  43. shouldCleanup := true
  44. defer func() {
  45. if !shouldCleanup {
  46. return
  47. }
  48. for i := 0; i < erasure_coding.TotalShardsCount; i++ {
  49. os.Remove(fmt.Sprintf("%s.ec%2d", baseFileName, i))
  50. }
  51. os.Remove(v.IndexFileName() + ".ecx")
  52. }()
  53. // write .ec00 ~ .ec13 files
  54. if err := erasure_coding.WriteEcFiles(baseFileName); err != nil {
  55. return nil, fmt.Errorf("WriteEcFiles %s: %v", baseFileName, err)
  56. }
  57. // write .ecx file
  58. if err := erasure_coding.WriteSortedFileFromIdx(v.IndexFileName(), ".ecx"); err != nil {
  59. return nil, fmt.Errorf("WriteSortedFileFromIdx %s: %v", v.IndexFileName(), err)
  60. }
  61. // write .vif files
  62. var destroyTime uint64
  63. if v.Ttl != nil {
  64. ttlMills := v.Ttl.ToSeconds()
  65. if ttlMills > 0 {
  66. destroyTime = uint64(time.Now().Unix()) + v.Ttl.ToSeconds() //calculated destroy time from the ec volume was created
  67. }
  68. }
  69. volumeInfo := &volume_server_pb.VolumeInfo{Version: uint32(v.Version())}
  70. if destroyTime == 0 {
  71. glog.Warningf("gen ec volume,cal ec volume destory time fail,set time to 0,ttl:%v", v.Ttl)
  72. } else {
  73. volumeInfo.DestroyTime = destroyTime
  74. }
  75. datSize, _, _ := v.FileStat()
  76. volumeInfo.DatFileSize = int64(datSize)
  77. if err := volume_info.SaveVolumeInfo(baseFileName+".vif", volumeInfo); err != nil {
  78. return nil, fmt.Errorf("SaveVolumeInfo %s: %v", baseFileName, err)
  79. }
  80. shouldCleanup = false
  81. return &volume_server_pb.VolumeEcShardsGenerateResponse{}, nil
  82. }
  83. // VolumeEcShardsRebuild generates the any of the missing .ec00 ~ .ec13 files
  84. func (vs *VolumeServer) VolumeEcShardsRebuild(ctx context.Context, req *volume_server_pb.VolumeEcShardsRebuildRequest) (*volume_server_pb.VolumeEcShardsRebuildResponse, error) {
  85. glog.V(0).Infof("VolumeEcShardsRebuild: %v", req)
  86. baseFileName := erasure_coding.EcShardBaseFileName(req.Collection, int(req.VolumeId))
  87. var rebuiltShardIds []uint32
  88. for _, location := range vs.store.Locations {
  89. _, _, existingShardCount, err := checkEcVolumeStatus(baseFileName, location)
  90. if err != nil {
  91. return nil, err
  92. }
  93. if existingShardCount == 0 {
  94. continue
  95. }
  96. if util.FileExists(path.Join(location.IdxDirectory, baseFileName+".ecx")) {
  97. // write .ec00 ~ .ec13 files
  98. dataBaseFileName := path.Join(location.Directory, baseFileName)
  99. if generatedShardIds, err := erasure_coding.RebuildEcFiles(dataBaseFileName); err != nil {
  100. return nil, fmt.Errorf("RebuildEcFiles %s: %v", dataBaseFileName, err)
  101. } else {
  102. rebuiltShardIds = generatedShardIds
  103. }
  104. indexBaseFileName := path.Join(location.IdxDirectory, baseFileName)
  105. if err := erasure_coding.RebuildEcxFile(indexBaseFileName); err != nil {
  106. return nil, fmt.Errorf("RebuildEcxFile %s: %v", dataBaseFileName, err)
  107. }
  108. break
  109. }
  110. }
  111. return &volume_server_pb.VolumeEcShardsRebuildResponse{
  112. RebuiltShardIds: rebuiltShardIds,
  113. }, nil
  114. }
  115. // VolumeEcShardsCopy copy the .ecx and some ec data slices
  116. func (vs *VolumeServer) VolumeEcShardsCopy(ctx context.Context, req *volume_server_pb.VolumeEcShardsCopyRequest) (*volume_server_pb.VolumeEcShardsCopyResponse, error) {
  117. glog.V(0).Infof("VolumeEcShardsCopy: %v", req)
  118. var location *storage.DiskLocation
  119. if req.CopyEcxFile {
  120. location = vs.store.FindFreeLocation(func(location *storage.DiskLocation) bool {
  121. return location.DiskType == types.HardDriveType
  122. })
  123. } else {
  124. location = vs.store.FindFreeLocation(func(location *storage.DiskLocation) bool {
  125. _, found := location.FindEcVolume(needle.VolumeId(req.VolumeId))
  126. return found
  127. })
  128. }
  129. if location == nil {
  130. return nil, fmt.Errorf("no space left")
  131. }
  132. dataBaseFileName := storage.VolumeFileName(location.Directory, req.Collection, int(req.VolumeId))
  133. indexBaseFileName := storage.VolumeFileName(location.IdxDirectory, req.Collection, int(req.VolumeId))
  134. err := operation.WithVolumeServerClient(true, pb.ServerAddress(req.SourceDataNode), vs.grpcDialOption, func(client volume_server_pb.VolumeServerClient) error {
  135. // copy ec data slices
  136. for _, shardId := range req.ShardIds {
  137. if _, err := vs.doCopyFile(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, dataBaseFileName, erasure_coding.ToExt(int(shardId)), false, false, nil); err != nil {
  138. return err
  139. }
  140. }
  141. if req.CopyEcxFile {
  142. // copy ecx file
  143. if _, err := vs.doCopyFile(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, indexBaseFileName, ".ecx", false, false, nil); err != nil {
  144. return err
  145. }
  146. }
  147. if req.CopyEcjFile {
  148. // copy ecj file
  149. if _, err := vs.doCopyFile(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, indexBaseFileName, ".ecj", true, true, nil); err != nil {
  150. return err
  151. }
  152. }
  153. if req.CopyVifFile {
  154. // copy vif file
  155. if _, err := vs.doCopyFile(client, true, req.Collection, req.VolumeId, math.MaxUint32, math.MaxInt64, dataBaseFileName, ".vif", false, true, nil); err != nil {
  156. return err
  157. }
  158. }
  159. if req.CopyEcxFile { //when location no volume before copy
  160. glog.V(0).Infof("Re LoadNewVolumes: %v", req)
  161. vs.store.LoadNewVolumes()
  162. }
  163. return nil
  164. })
  165. if err != nil {
  166. return nil, fmt.Errorf("VolumeEcShardsCopy volume %d: %v", req.VolumeId, err)
  167. }
  168. return &volume_server_pb.VolumeEcShardsCopyResponse{}, nil
  169. }
  170. // VolumeEcShardsDelete local delete the .ecx and some ec data slices if not needed
  171. // the shard should not be mounted before calling this.
  172. func (vs *VolumeServer) VolumeEcShardsDelete(ctx context.Context, req *volume_server_pb.VolumeEcShardsDeleteRequest) (*volume_server_pb.VolumeEcShardsDeleteResponse, error) {
  173. bName := erasure_coding.EcShardBaseFileName(req.Collection, int(req.VolumeId))
  174. glog.V(0).Infof("ec volume %s shard delete %v", bName, req.ShardIds)
  175. for _, location := range vs.store.Locations {
  176. if err := deleteEcShardIdsForEachLocation(bName, location, req.ShardIds); err != nil {
  177. glog.Errorf("deleteEcShards from %s %s.%v: %v", location.Directory, bName, req.ShardIds, err)
  178. return nil, err
  179. }
  180. }
  181. return &volume_server_pb.VolumeEcShardsDeleteResponse{}, nil
  182. }
  183. func deleteEcShardIdsForEachLocation(bName string, location *storage.DiskLocation, shardIds []uint32) error {
  184. found := false
  185. indexBaseFilename := path.Join(location.IdxDirectory, bName)
  186. dataBaseFilename := path.Join(location.Directory, bName)
  187. if util.FileExists(path.Join(location.IdxDirectory, bName+".ecx")) {
  188. for _, shardId := range shardIds {
  189. shardFileName := dataBaseFilename + erasure_coding.ToExt(int(shardId))
  190. if util.FileExists(shardFileName) {
  191. found = true
  192. os.Remove(shardFileName)
  193. }
  194. }
  195. }
  196. if !found {
  197. return nil
  198. }
  199. hasEcxFile, hasIdxFile, existingShardCount, err := checkEcVolumeStatus(bName, location)
  200. if err != nil {
  201. return err
  202. }
  203. if hasEcxFile && existingShardCount == 0 {
  204. if err := os.Remove(indexBaseFilename + ".ecx"); err != nil {
  205. return err
  206. }
  207. os.Remove(indexBaseFilename + ".ecj")
  208. if !hasIdxFile {
  209. // .vif is used for ec volumes and normal volumes
  210. os.Remove(dataBaseFilename + ".vif")
  211. }
  212. }
  213. return nil
  214. }
  215. func checkEcVolumeStatus(bName string, location *storage.DiskLocation) (hasEcxFile bool, hasIdxFile bool, existingShardCount int, err error) {
  216. // check whether to delete the .ecx and .ecj file also
  217. fileInfos, err := os.ReadDir(location.Directory)
  218. if err != nil {
  219. return false, false, 0, err
  220. }
  221. if location.IdxDirectory != location.Directory {
  222. idxFileInfos, err := os.ReadDir(location.IdxDirectory)
  223. if err != nil {
  224. return false, false, 0, err
  225. }
  226. fileInfos = append(fileInfos, idxFileInfos...)
  227. }
  228. for _, fileInfo := range fileInfos {
  229. if fileInfo.Name() == bName+".ecx" || fileInfo.Name() == bName+".ecj" {
  230. hasEcxFile = true
  231. continue
  232. }
  233. if fileInfo.Name() == bName+".idx" {
  234. hasIdxFile = true
  235. continue
  236. }
  237. if strings.HasPrefix(fileInfo.Name(), bName+".ec") {
  238. existingShardCount++
  239. }
  240. }
  241. return hasEcxFile, hasIdxFile, existingShardCount, nil
  242. }
  243. func (vs *VolumeServer) VolumeEcShardsMount(ctx context.Context, req *volume_server_pb.VolumeEcShardsMountRequest) (*volume_server_pb.VolumeEcShardsMountResponse, error) {
  244. glog.V(0).Infof("VolumeEcShardsMount: %v", req)
  245. for _, shardId := range req.ShardIds {
  246. err := vs.store.MountEcShards(req.Collection, needle.VolumeId(req.VolumeId), erasure_coding.ShardId(shardId))
  247. if err != nil {
  248. glog.Errorf("ec shard mount %v: %v", req, err)
  249. } else {
  250. glog.V(2).Infof("ec shard mount %v", req)
  251. }
  252. if err != nil {
  253. return nil, fmt.Errorf("mount %d.%d: %v", req.VolumeId, shardId, err)
  254. }
  255. }
  256. return &volume_server_pb.VolumeEcShardsMountResponse{}, nil
  257. }
  258. func (vs *VolumeServer) VolumeEcShardsUnmount(ctx context.Context, req *volume_server_pb.VolumeEcShardsUnmountRequest) (*volume_server_pb.VolumeEcShardsUnmountResponse, error) {
  259. glog.V(0).Infof("VolumeEcShardsUnmount: %v", req)
  260. for _, shardId := range req.ShardIds {
  261. err := vs.store.UnmountEcShards(needle.VolumeId(req.VolumeId), erasure_coding.ShardId(shardId))
  262. if err != nil {
  263. glog.Errorf("ec shard unmount %v: %v", req, err)
  264. } else {
  265. glog.V(2).Infof("ec shard unmount %v", req)
  266. }
  267. if err != nil {
  268. return nil, fmt.Errorf("unmount %d.%d: %v", req.VolumeId, shardId, err)
  269. }
  270. }
  271. return &volume_server_pb.VolumeEcShardsUnmountResponse{}, nil
  272. }
  273. func (vs *VolumeServer) VolumeEcShardRead(req *volume_server_pb.VolumeEcShardReadRequest, stream volume_server_pb.VolumeServer_VolumeEcShardReadServer) error {
  274. ecVolume, found := vs.store.FindEcVolume(needle.VolumeId(req.VolumeId))
  275. if !found {
  276. return fmt.Errorf("VolumeEcShardRead not found ec volume id %d", req.VolumeId)
  277. }
  278. ecShard, found := ecVolume.FindEcVolumeShard(erasure_coding.ShardId(req.ShardId))
  279. if !found {
  280. return fmt.Errorf("not found ec shard %d.%d", req.VolumeId, req.ShardId)
  281. }
  282. if req.FileKey != 0 {
  283. _, size, _ := ecVolume.FindNeedleFromEcx(types.Uint64ToNeedleId(req.FileKey))
  284. if size.IsDeleted() {
  285. return stream.Send(&volume_server_pb.VolumeEcShardReadResponse{
  286. IsDeleted: true,
  287. })
  288. }
  289. }
  290. bufSize := req.Size
  291. if bufSize > BufferSizeLimit {
  292. bufSize = BufferSizeLimit
  293. }
  294. buffer := make([]byte, bufSize)
  295. startOffset, bytesToRead := req.Offset, req.Size
  296. for bytesToRead > 0 {
  297. // min of bytesToRead and bufSize
  298. bufferSize := bufSize
  299. if bufferSize > bytesToRead {
  300. bufferSize = bytesToRead
  301. }
  302. bytesread, err := ecShard.ReadAt(buffer[0:bufferSize], startOffset)
  303. // println("read", ecShard.FileName(), "startOffset", startOffset, bytesread, "bytes, with target", bufferSize)
  304. if bytesread > 0 {
  305. if int64(bytesread) > bytesToRead {
  306. bytesread = int(bytesToRead)
  307. }
  308. err = stream.Send(&volume_server_pb.VolumeEcShardReadResponse{
  309. Data: buffer[:bytesread],
  310. })
  311. if err != nil {
  312. // println("sending", bytesread, "bytes err", err.Error())
  313. return err
  314. }
  315. startOffset += int64(bytesread)
  316. bytesToRead -= int64(bytesread)
  317. }
  318. if err != nil {
  319. if err != io.EOF {
  320. return err
  321. }
  322. return nil
  323. }
  324. }
  325. return nil
  326. }
  327. func (vs *VolumeServer) VolumeEcBlobDelete(ctx context.Context, req *volume_server_pb.VolumeEcBlobDeleteRequest) (*volume_server_pb.VolumeEcBlobDeleteResponse, error) {
  328. glog.V(0).Infof("VolumeEcBlobDelete: %v", req)
  329. resp := &volume_server_pb.VolumeEcBlobDeleteResponse{}
  330. for _, location := range vs.store.Locations {
  331. if localEcVolume, found := location.FindEcVolume(needle.VolumeId(req.VolumeId)); found {
  332. _, size, _, err := localEcVolume.LocateEcShardNeedle(types.NeedleId(req.FileKey), needle.Version(req.Version))
  333. if err != nil {
  334. return nil, fmt.Errorf("locate in local ec volume: %v", err)
  335. }
  336. if size.IsDeleted() {
  337. return resp, nil
  338. }
  339. err = localEcVolume.DeleteNeedleFromEcx(types.NeedleId(req.FileKey))
  340. if err != nil {
  341. return nil, err
  342. }
  343. break
  344. }
  345. }
  346. return resp, nil
  347. }
  348. // VolumeEcShardsToVolume generates the .idx, .dat files from .ecx, .ecj and .ec01 ~ .ec14 files
  349. func (vs *VolumeServer) VolumeEcShardsToVolume(ctx context.Context, req *volume_server_pb.VolumeEcShardsToVolumeRequest) (*volume_server_pb.VolumeEcShardsToVolumeResponse, error) {
  350. glog.V(0).Infof("VolumeEcShardsToVolume: %v", req)
  351. // collect .ec00 ~ .ec09 files
  352. shardFileNames := make([]string, erasure_coding.DataShardsCount)
  353. v, found := vs.store.CollectEcShards(needle.VolumeId(req.VolumeId), shardFileNames)
  354. if !found {
  355. return nil, fmt.Errorf("ec volume %d not found", req.VolumeId)
  356. }
  357. if v.Collection != req.Collection {
  358. return nil, fmt.Errorf("existing collection:%v unexpected input: %v", v.Collection, req.Collection)
  359. }
  360. for shardId := 0; shardId < erasure_coding.DataShardsCount; shardId++ {
  361. if shardFileNames[shardId] == "" {
  362. return nil, fmt.Errorf("ec volume %d missing shard %d", req.VolumeId, shardId)
  363. }
  364. }
  365. dataBaseFileName, indexBaseFileName := v.DataBaseFileName(), v.IndexBaseFileName()
  366. // calculate .dat file size
  367. datFileSize, err := erasure_coding.FindDatFileSize(dataBaseFileName, indexBaseFileName)
  368. if err != nil {
  369. return nil, fmt.Errorf("FindDatFileSize %s: %v", dataBaseFileName, err)
  370. }
  371. // write .dat file from .ec00 ~ .ec09 files
  372. if err := erasure_coding.WriteDatFile(dataBaseFileName, datFileSize, shardFileNames); err != nil {
  373. return nil, fmt.Errorf("WriteDatFile %s: %v", dataBaseFileName, err)
  374. }
  375. // write .idx file from .ecx and .ecj files
  376. if err := erasure_coding.WriteIdxFileFromEcIndex(indexBaseFileName); err != nil {
  377. return nil, fmt.Errorf("WriteIdxFileFromEcIndex %s: %v", v.IndexBaseFileName(), err)
  378. }
  379. return &volume_server_pb.VolumeEcShardsToVolumeResponse{}, nil
  380. }