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.

356 lines
10 KiB

9 months ago
4 months ago
6 years ago
6 years ago
3 years ago
6 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "math/rand/v2"
  6. "strings"
  7. "sync"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/stats"
  10. "github.com/seaweedfs/seaweedfs/weed/topology"
  11. "github.com/seaweedfs/raft"
  12. "github.com/seaweedfs/seaweedfs/weed/glog"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/security"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  16. "github.com/seaweedfs/seaweedfs/weed/storage/super_block"
  17. "github.com/seaweedfs/seaweedfs/weed/storage/types"
  18. )
  19. const (
  20. volumeGrowStepCount = 2
  21. )
  22. func (ms *MasterServer) DoAutomaticVolumeGrow(req *topology.VolumeGrowRequest) {
  23. glog.V(1).Infoln("starting automatic volume grow")
  24. start := time.Now()
  25. newVidLocations, err := ms.vg.AutomaticGrowByType(req.Option, ms.grpcDialOption, ms.Topo, req.Count)
  26. glog.V(1).Infoln("finished automatic volume grow, cost ", time.Now().Sub(start))
  27. if err != nil {
  28. glog.V(1).Infof("automatic volume grow failed: %+v", err)
  29. return
  30. }
  31. for _, newVidLocation := range newVidLocations {
  32. ms.broadcastToClients(&master_pb.KeepConnectedResponse{VolumeLocation: newVidLocation})
  33. }
  34. }
  35. func (ms *MasterServer) ProcessGrowRequest() {
  36. go func() {
  37. ctx := context.Background()
  38. firstRun := true
  39. for {
  40. if firstRun {
  41. firstRun = false
  42. } else {
  43. time.Sleep(5*time.Minute + time.Duration(30*rand.Float32())*time.Second)
  44. }
  45. if !ms.Topo.IsLeader() {
  46. continue
  47. }
  48. dcs := ms.Topo.ListDataCenters()
  49. var err error
  50. for _, vlc := range ms.Topo.ListVolumeLayoutCollections() {
  51. vl := vlc.VolumeLayout
  52. lastGrowCount := vl.GetLastGrowCount()
  53. if vl.HasGrowRequest() {
  54. continue
  55. }
  56. writable, crowded := vl.GetWritableVolumeCount()
  57. mustGrow := int(lastGrowCount) - writable
  58. vgr := vlc.ToVolumeGrowRequest()
  59. stats.MasterVolumeLayoutWritable.WithLabelValues(vlc.Collection, vgr.DiskType, vgr.Replication, vgr.Ttl).Set(float64(writable))
  60. stats.MasterVolumeLayoutCrowded.WithLabelValues(vlc.Collection, vgr.DiskType, vgr.Replication, vgr.Ttl).Set(float64(crowded))
  61. switch {
  62. case mustGrow > 0:
  63. vgr.WritableVolumeCount = uint32(mustGrow)
  64. _, err = ms.VolumeGrow(ctx, vgr)
  65. default:
  66. for _, dc := range dcs {
  67. if vl.ShouldGrowVolumesByDataNode("DataCenter", dc) {
  68. vgr.DataCenter = dc
  69. if lastGrowCount > 0 {
  70. vgr.WritableVolumeCount = uint32(int(lastGrowCount) / len(dcs))
  71. } else {
  72. vgr.WritableVolumeCount = volumeGrowStepCount
  73. }
  74. _, err = ms.VolumeGrow(ctx, vgr)
  75. }
  76. }
  77. }
  78. if err != nil {
  79. glog.V(0).Infof("volume grow request failed: %+v", err)
  80. }
  81. }
  82. }
  83. }()
  84. go func() {
  85. filter := sync.Map{}
  86. for {
  87. req, ok := <-ms.volumeGrowthRequestChan
  88. if !ok {
  89. break
  90. }
  91. option := req.Option
  92. vl := ms.Topo.GetVolumeLayout(option.Collection, option.ReplicaPlacement, option.Ttl, option.DiskType)
  93. if !ms.Topo.IsLeader() {
  94. //discard buffered requests
  95. time.Sleep(time.Second * 1)
  96. vl.DoneGrowRequest()
  97. continue
  98. }
  99. // filter out identical requests being processed
  100. found := false
  101. filter.Range(func(k, v interface{}) bool {
  102. existingReq := k.(*topology.VolumeGrowRequest)
  103. if existingReq.Equals(req) {
  104. found = true
  105. }
  106. return !found
  107. })
  108. // not atomic but it's okay
  109. if found || (!req.Force && !vl.ShouldGrowVolumes()) {
  110. glog.V(4).Infoln("discard volume grow request")
  111. time.Sleep(time.Millisecond * 211)
  112. vl.DoneGrowRequest()
  113. continue
  114. }
  115. filter.Store(req, nil)
  116. // we have lock called inside vg
  117. glog.V(0).Infof("volume grow %+v", req)
  118. go func(req *topology.VolumeGrowRequest, vl *topology.VolumeLayout) {
  119. ms.DoAutomaticVolumeGrow(req)
  120. vl.DoneGrowRequest()
  121. filter.Delete(req)
  122. }(req, vl)
  123. }
  124. }()
  125. }
  126. func (ms *MasterServer) LookupVolume(ctx context.Context, req *master_pb.LookupVolumeRequest) (*master_pb.LookupVolumeResponse, error) {
  127. resp := &master_pb.LookupVolumeResponse{}
  128. volumeLocations := ms.lookupVolumeId(req.VolumeOrFileIds, req.Collection)
  129. for _, volumeOrFileId := range req.VolumeOrFileIds {
  130. vid := volumeOrFileId
  131. commaSep := strings.Index(vid, ",")
  132. if commaSep > 0 {
  133. vid = vid[0:commaSep]
  134. }
  135. if result, found := volumeLocations[vid]; found {
  136. var locations []*master_pb.Location
  137. for _, loc := range result.Locations {
  138. locations = append(locations, &master_pb.Location{
  139. Url: loc.Url,
  140. PublicUrl: loc.PublicUrl,
  141. DataCenter: loc.DataCenter,
  142. GrpcPort: uint32(loc.GrpcPort),
  143. })
  144. }
  145. var auth string
  146. if commaSep > 0 { // this is a file id
  147. auth = string(security.GenJwtForVolumeServer(ms.guard.SigningKey, ms.guard.ExpiresAfterSec, result.VolumeOrFileId))
  148. }
  149. resp.VolumeIdLocations = append(resp.VolumeIdLocations, &master_pb.LookupVolumeResponse_VolumeIdLocation{
  150. VolumeOrFileId: result.VolumeOrFileId,
  151. Locations: locations,
  152. Error: result.Error,
  153. Auth: auth,
  154. })
  155. }
  156. }
  157. return resp, nil
  158. }
  159. func (ms *MasterServer) Statistics(ctx context.Context, req *master_pb.StatisticsRequest) (*master_pb.StatisticsResponse, error) {
  160. if !ms.Topo.IsLeader() {
  161. return nil, raft.NotLeaderError
  162. }
  163. if req.Replication == "" {
  164. req.Replication = ms.option.DefaultReplicaPlacement
  165. }
  166. replicaPlacement, err := super_block.NewReplicaPlacementFromString(req.Replication)
  167. if err != nil {
  168. return nil, err
  169. }
  170. ttl, err := needle.ReadTTL(req.Ttl)
  171. if err != nil {
  172. return nil, err
  173. }
  174. volumeLayout := ms.Topo.GetVolumeLayout(req.Collection, replicaPlacement, ttl, types.ToDiskType(req.DiskType))
  175. stats := volumeLayout.Stats()
  176. totalSize := ms.Topo.GetDiskUsages().GetMaxVolumeCount() * int64(ms.option.VolumeSizeLimitMB) * 1024 * 1024
  177. resp := &master_pb.StatisticsResponse{
  178. TotalSize: uint64(totalSize),
  179. UsedSize: stats.UsedSize,
  180. FileCount: stats.FileCount,
  181. }
  182. return resp, nil
  183. }
  184. func (ms *MasterServer) VolumeList(ctx context.Context, req *master_pb.VolumeListRequest) (*master_pb.VolumeListResponse, error) {
  185. if !ms.Topo.IsLeader() {
  186. return nil, raft.NotLeaderError
  187. }
  188. resp := &master_pb.VolumeListResponse{
  189. TopologyInfo: ms.Topo.ToTopologyInfo(),
  190. VolumeSizeLimitMb: uint64(ms.option.VolumeSizeLimitMB),
  191. }
  192. return resp, nil
  193. }
  194. func (ms *MasterServer) LookupEcVolume(ctx context.Context, req *master_pb.LookupEcVolumeRequest) (*master_pb.LookupEcVolumeResponse, error) {
  195. if !ms.Topo.IsLeader() {
  196. return nil, raft.NotLeaderError
  197. }
  198. resp := &master_pb.LookupEcVolumeResponse{}
  199. ecLocations, found := ms.Topo.LookupEcShards(needle.VolumeId(req.VolumeId))
  200. if !found {
  201. return resp, fmt.Errorf("ec volume %d not found", req.VolumeId)
  202. }
  203. resp.VolumeId = req.VolumeId
  204. for shardId, shardLocations := range ecLocations.Locations {
  205. var locations []*master_pb.Location
  206. for _, dn := range shardLocations {
  207. locations = append(locations, &master_pb.Location{
  208. Url: string(dn.Id()),
  209. PublicUrl: dn.PublicUrl,
  210. DataCenter: dn.GetDataCenterId(),
  211. })
  212. }
  213. resp.ShardIdLocations = append(resp.ShardIdLocations, &master_pb.LookupEcVolumeResponse_EcShardIdLocation{
  214. ShardId: uint32(shardId),
  215. Locations: locations,
  216. })
  217. }
  218. return resp, nil
  219. }
  220. func (ms *MasterServer) VacuumVolume(ctx context.Context, req *master_pb.VacuumVolumeRequest) (*master_pb.VacuumVolumeResponse, error) {
  221. if !ms.Topo.IsLeader() {
  222. return nil, raft.NotLeaderError
  223. }
  224. resp := &master_pb.VacuumVolumeResponse{}
  225. ms.Topo.Vacuum(ms.grpcDialOption, float64(req.GarbageThreshold), ms.option.MaxParallelVacuumPerServer, req.VolumeId, req.Collection, ms.preallocateSize)
  226. return resp, nil
  227. }
  228. func (ms *MasterServer) DisableVacuum(ctx context.Context, req *master_pb.DisableVacuumRequest) (*master_pb.DisableVacuumResponse, error) {
  229. ms.Topo.DisableVacuum()
  230. resp := &master_pb.DisableVacuumResponse{}
  231. return resp, nil
  232. }
  233. func (ms *MasterServer) EnableVacuum(ctx context.Context, req *master_pb.EnableVacuumRequest) (*master_pb.EnableVacuumResponse, error) {
  234. ms.Topo.EnableVacuum()
  235. resp := &master_pb.EnableVacuumResponse{}
  236. return resp, nil
  237. }
  238. func (ms *MasterServer) VolumeMarkReadonly(ctx context.Context, req *master_pb.VolumeMarkReadonlyRequest) (*master_pb.VolumeMarkReadonlyResponse, error) {
  239. if !ms.Topo.IsLeader() {
  240. return nil, raft.NotLeaderError
  241. }
  242. resp := &master_pb.VolumeMarkReadonlyResponse{}
  243. replicaPlacement, _ := super_block.NewReplicaPlacementFromByte(byte(req.ReplicaPlacement))
  244. vl := ms.Topo.GetVolumeLayout(req.Collection, replicaPlacement, needle.LoadTTLFromUint32(req.Ttl), types.ToDiskType(req.DiskType))
  245. dataNodes := ms.Topo.Lookup(req.Collection, needle.VolumeId(req.VolumeId))
  246. for _, dn := range dataNodes {
  247. if dn.Ip == req.Ip && dn.Port == int(req.Port) {
  248. if req.IsReadonly {
  249. vl.SetVolumeReadOnly(dn, needle.VolumeId(req.VolumeId))
  250. } else {
  251. vl.SetVolumeWritable(dn, needle.VolumeId(req.VolumeId))
  252. }
  253. }
  254. }
  255. return resp, nil
  256. }
  257. func (ms *MasterServer) VolumeGrow(ctx context.Context, req *master_pb.VolumeGrowRequest) (*master_pb.VolumeGrowResponse, error) {
  258. if !ms.Topo.IsLeader() {
  259. return nil, raft.NotLeaderError
  260. }
  261. if req.Replication == "" {
  262. req.Replication = ms.option.DefaultReplicaPlacement
  263. }
  264. replicaPlacement, err := super_block.NewReplicaPlacementFromString(req.Replication)
  265. if err != nil {
  266. return nil, err
  267. }
  268. ttl, err := needle.ReadTTL(req.Ttl)
  269. if err != nil {
  270. return nil, err
  271. }
  272. if req.DataCenter != "" && !ms.Topo.DataCenterExists(req.DataCenter) {
  273. return nil, fmt.Errorf("data center not exists")
  274. }
  275. volumeGrowOption := topology.VolumeGrowOption{
  276. Collection: req.Collection,
  277. ReplicaPlacement: replicaPlacement,
  278. Ttl: ttl,
  279. DiskType: types.ToDiskType(req.DiskType),
  280. Preallocate: ms.preallocateSize,
  281. DataCenter: req.DataCenter,
  282. Rack: req.Rack,
  283. DataNode: req.DataNode,
  284. MemoryMapMaxSizeMb: req.MemoryMapMaxSizeMb,
  285. }
  286. volumeGrowRequest := topology.VolumeGrowRequest{
  287. Option: &volumeGrowOption,
  288. Count: req.WritableVolumeCount,
  289. Force: true,
  290. Reason: "grpc volume grow",
  291. }
  292. replicaCount := int64(req.WritableVolumeCount * uint32(replicaPlacement.GetCopyCount()))
  293. if ms.Topo.AvailableSpaceFor(&volumeGrowOption) < replicaCount {
  294. return nil, fmt.Errorf("only %d volumes left, not enough for %d", ms.Topo.AvailableSpaceFor(&volumeGrowOption), replicaCount)
  295. }
  296. if !ms.Topo.DataCenterExists(volumeGrowOption.DataCenter) {
  297. err = fmt.Errorf("data center %v not found in topology", volumeGrowOption.DataCenter)
  298. }
  299. ms.DoAutomaticVolumeGrow(&volumeGrowRequest)
  300. return &master_pb.VolumeGrowResponse{}, nil
  301. }