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.

378 lines
12 KiB

7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
5 years ago
8 months ago
8 months ago
8 months ago
4 years ago
5 years ago
5 years ago
5 years ago
4 years ago
5 years ago
4 years ago
4 years ago
4 years ago
4 years ago
1 year ago
4 years ago
4 years ago
4 years ago
6 years ago
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/cluster"
  10. "github.com/seaweedfs/seaweedfs/weed/filer"
  11. "github.com/seaweedfs/seaweedfs/weed/glog"
  12. "github.com/seaweedfs/seaweedfs/weed/operation"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  14. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  15. "github.com/seaweedfs/seaweedfs/weed/storage/needle"
  16. "github.com/seaweedfs/seaweedfs/weed/util"
  17. )
  18. func (fs *FilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
  19. glog.V(4).Infof("LookupDirectoryEntry %s", filepath.Join(req.Directory, req.Name))
  20. entry, err := fs.filer.FindEntry(ctx, util.JoinPath(req.Directory, req.Name))
  21. if err == filer_pb.ErrNotFound {
  22. return &filer_pb.LookupDirectoryEntryResponse{}, err
  23. }
  24. if err != nil {
  25. glog.V(3).Infof("LookupDirectoryEntry %s: %+v, ", filepath.Join(req.Directory, req.Name), err)
  26. return nil, err
  27. }
  28. return &filer_pb.LookupDirectoryEntryResponse{
  29. Entry: entry.ToProtoEntry(),
  30. }, nil
  31. }
  32. func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) (err error) {
  33. glog.V(0).Infof("ListEntries %v", req)
  34. limit := int(req.Limit)
  35. if limit == 0 {
  36. limit = fs.option.DirListingLimit
  37. }
  38. paginationLimit := filer.PaginationSize
  39. // Todo test_bucket_listv2_delimiter_prefix move start from prefix to SQL because in extreme cases, where there are more keys that need to be skipped than the limit
  40. if paginationLimit > limit && !(req.Recursive && req.Delimiter && len(req.StartFromFileName) > 0) {
  41. paginationLimit = limit
  42. if req.Recursive {
  43. paginationLimit *= 2
  44. }
  45. }
  46. lastFileName := req.StartFromFileName
  47. includeLastFile := req.InclusiveStartFrom
  48. var listErr error
  49. for limit > 0 {
  50. var hasEntries bool
  51. //glog.V(0).Infof("StreamListDirectoryEntries req %+v", req)
  52. lastFileName, listErr = fs.filer.StreamListDirectoryEntries(stream.Context(), util.FullPath(req.Directory), lastFileName, includeLastFile, req.Recursive, req.Delimiter, int64(paginationLimit), req.Prefix, "", "", func(entry *filer.Entry) bool {
  53. hasEntries = true
  54. if err = stream.Send(&filer_pb.ListEntriesResponse{
  55. Entry: entry.ToProtoEntry(),
  56. Path: string(entry.FullPath),
  57. }); err != nil {
  58. return false
  59. }
  60. limit--
  61. if limit == 0 {
  62. return false
  63. }
  64. return true
  65. })
  66. if listErr != nil {
  67. return listErr
  68. }
  69. if err != nil {
  70. return err
  71. }
  72. if !hasEntries {
  73. return nil
  74. }
  75. includeLastFile = false
  76. }
  77. return nil
  78. }
  79. func (fs *FilerServer) LookupVolume(ctx context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
  80. resp := &filer_pb.LookupVolumeResponse{
  81. LocationsMap: make(map[string]*filer_pb.Locations),
  82. }
  83. for _, vidString := range req.VolumeIds {
  84. vid, err := strconv.Atoi(vidString)
  85. if err != nil {
  86. glog.V(1).Infof("Unknown volume id %d", vid)
  87. return nil, err
  88. }
  89. var locs []*filer_pb.Location
  90. locations, found := fs.filer.MasterClient.GetLocations(uint32(vid))
  91. if !found {
  92. continue
  93. }
  94. for _, loc := range locations {
  95. locs = append(locs, &filer_pb.Location{
  96. Url: loc.Url,
  97. PublicUrl: loc.PublicUrl,
  98. GrpcPort: uint32(loc.GrpcPort),
  99. DataCenter: loc.DataCenter,
  100. })
  101. }
  102. resp.LocationsMap[vidString] = &filer_pb.Locations{
  103. Locations: locs,
  104. }
  105. }
  106. return resp, nil
  107. }
  108. func (fs *FilerServer) lookupFileId(fileId string) (targetUrls []string, err error) {
  109. fid, err := needle.ParseFileIdFromString(fileId)
  110. if err != nil {
  111. return nil, err
  112. }
  113. locations, found := fs.filer.MasterClient.GetLocations(uint32(fid.VolumeId))
  114. if !found || len(locations) == 0 {
  115. return nil, fmt.Errorf("not found volume %d in %s", fid.VolumeId, fileId)
  116. }
  117. for _, loc := range locations {
  118. targetUrls = append(targetUrls, fmt.Sprintf("http://%s/%s", loc.Url, fileId))
  119. }
  120. return
  121. }
  122. func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (resp *filer_pb.CreateEntryResponse, err error) {
  123. glog.V(4).Infof("CreateEntry %v/%v", req.Directory, req.Entry.Name)
  124. resp = &filer_pb.CreateEntryResponse{}
  125. chunks, garbage, err2 := fs.cleanupChunks(util.Join(req.Directory, req.Entry.Name), nil, req.Entry)
  126. if err2 != nil {
  127. return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry cleanupChunks %s %s: %v", req.Directory, req.Entry.Name, err2)
  128. }
  129. so, err := fs.detectStorageOption(string(util.NewFullPath(req.Directory, req.Entry.Name)), "", "", 0, "", "", "", "")
  130. if err != nil {
  131. return nil, err
  132. }
  133. newEntry := filer.FromPbEntry(req.Directory, req.Entry)
  134. newEntry.Chunks = chunks
  135. newEntry.TtlSec = so.TtlSeconds
  136. createErr := fs.filer.CreateEntry(ctx, newEntry, req.OExcl, req.IsFromOtherCluster, req.Signatures, req.SkipCheckParentDirectory, so.MaxFileNameLength)
  137. if createErr == nil {
  138. fs.filer.DeleteChunksNotRecursive(garbage)
  139. } else {
  140. glog.V(3).Infof("CreateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), createErr)
  141. resp.Error = createErr.Error()
  142. }
  143. return
  144. }
  145. func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
  146. glog.V(4).Infof("UpdateEntry %v", req)
  147. fullpath := util.Join(req.Directory, req.Entry.Name)
  148. entry, err := fs.filer.FindEntry(ctx, util.FullPath(fullpath))
  149. if err != nil {
  150. return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("not found %s: %v", fullpath, err)
  151. }
  152. chunks, garbage, err2 := fs.cleanupChunks(fullpath, entry, req.Entry)
  153. if err2 != nil {
  154. return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("UpdateEntry cleanupChunks %s: %v", fullpath, err2)
  155. }
  156. newEntry := filer.FromPbEntry(req.Directory, req.Entry)
  157. newEntry.Chunks = chunks
  158. if filer.EqualEntry(entry, newEntry) {
  159. return &filer_pb.UpdateEntryResponse{}, err
  160. }
  161. if err = fs.filer.UpdateEntry(ctx, entry, newEntry); err == nil {
  162. fs.filer.DeleteChunksNotRecursive(garbage)
  163. fs.filer.NotifyUpdateEvent(ctx, entry, newEntry, true, req.IsFromOtherCluster, req.Signatures)
  164. } else {
  165. glog.V(3).Infof("UpdateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), err)
  166. }
  167. return &filer_pb.UpdateEntryResponse{}, err
  168. }
  169. func (fs *FilerServer) cleanupChunks(fullpath string, existingEntry *filer.Entry, newEntry *filer_pb.Entry) (chunks, garbage []*filer_pb.FileChunk, err error) {
  170. // remove old chunks if not included in the new ones
  171. if existingEntry != nil {
  172. garbage, err = filer.MinusChunks(fs.lookupFileId, existingEntry.GetChunks(), newEntry.GetChunks())
  173. if err != nil {
  174. return newEntry.GetChunks(), nil, fmt.Errorf("MinusChunks: %v", err)
  175. }
  176. }
  177. // files with manifest chunks are usually large and append only, skip calculating covered chunks
  178. manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(newEntry.GetChunks())
  179. chunks, coveredChunks := filer.CompactFileChunks(fs.lookupFileId, nonManifestChunks)
  180. garbage = append(garbage, coveredChunks...)
  181. if newEntry.Attributes != nil {
  182. so, _ := fs.detectStorageOption(fullpath,
  183. "",
  184. "",
  185. newEntry.Attributes.TtlSec,
  186. "",
  187. "",
  188. "",
  189. "",
  190. ) // ignore readonly error for capacity needed to manifestize
  191. chunks, err = filer.MaybeManifestize(fs.saveAsChunk(so), chunks)
  192. if err != nil {
  193. // not good, but should be ok
  194. glog.V(0).Infof("MaybeManifestize: %v", err)
  195. }
  196. }
  197. chunks = append(manifestChunks, chunks...)
  198. return
  199. }
  200. func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendToEntryRequest) (*filer_pb.AppendToEntryResponse, error) {
  201. glog.V(4).Infof("AppendToEntry %v", req)
  202. fullpath := util.NewFullPath(req.Directory, req.EntryName)
  203. lockClient := cluster.NewLockClient(fs.grpcDialOption, fs.option.Host)
  204. lock := lockClient.NewShortLivedLock(string(fullpath), string(fs.option.Host))
  205. defer lock.StopShortLivedLock()
  206. var offset int64 = 0
  207. entry, err := fs.filer.FindEntry(ctx, fullpath)
  208. if err == filer_pb.ErrNotFound {
  209. entry = &filer.Entry{
  210. FullPath: fullpath,
  211. Attr: filer.Attr{
  212. Crtime: time.Now(),
  213. Mtime: time.Now(),
  214. Mode: os.FileMode(0644),
  215. Uid: OS_UID,
  216. Gid: OS_GID,
  217. },
  218. }
  219. } else {
  220. offset = int64(filer.TotalSize(entry.GetChunks()))
  221. }
  222. for _, chunk := range req.Chunks {
  223. chunk.Offset = offset
  224. offset += int64(chunk.Size)
  225. }
  226. entry.Chunks = append(entry.GetChunks(), req.Chunks...)
  227. so, err := fs.detectStorageOption(string(fullpath), "", "", entry.TtlSec, "", "", "", "")
  228. if err != nil {
  229. glog.Warningf("detectStorageOption: %v", err)
  230. return &filer_pb.AppendToEntryResponse{}, err
  231. }
  232. entry.Chunks, err = filer.MaybeManifestize(fs.saveAsChunk(so), entry.GetChunks())
  233. if err != nil {
  234. // not good, but should be ok
  235. glog.V(0).Infof("MaybeManifestize: %v", err)
  236. }
  237. err = fs.filer.CreateEntry(context.Background(), entry, false, false, nil, false, fs.filer.MaxFilenameLength)
  238. return &filer_pb.AppendToEntryResponse{}, err
  239. }
  240. func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest) (resp *filer_pb.DeleteEntryResponse, err error) {
  241. glog.V(4).Infof("DeleteEntry %v", req)
  242. err = fs.filer.DeleteEntryMetaAndData(ctx, util.JoinPath(req.Directory, req.Name), req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures)
  243. resp = &filer_pb.DeleteEntryResponse{}
  244. if err != nil && err != filer_pb.ErrNotFound {
  245. resp.Error = err.Error()
  246. }
  247. return resp, nil
  248. }
  249. func (fs *FilerServer) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (resp *filer_pb.AssignVolumeResponse, err error) {
  250. if req.DiskType == "" {
  251. req.DiskType = fs.option.DiskType
  252. }
  253. so, err := fs.detectStorageOption(req.Path, req.Collection, req.Replication, req.TtlSec, req.DiskType, req.DataCenter, req.Rack, req.DataNode)
  254. if err != nil {
  255. glog.V(3).Infof("AssignVolume: %v", err)
  256. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume: %v", err)}, nil
  257. }
  258. assignRequest, altRequest := so.ToAssignRequests(int(req.Count))
  259. assignResult, err := operation.Assign(fs.filer.GetMaster, fs.grpcDialOption, assignRequest, altRequest)
  260. if err != nil {
  261. glog.V(3).Infof("AssignVolume: %v", err)
  262. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume: %v", err)}, nil
  263. }
  264. if assignResult.Error != "" {
  265. glog.V(3).Infof("AssignVolume error: %v", assignResult.Error)
  266. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume result: %v", assignResult.Error)}, nil
  267. }
  268. return &filer_pb.AssignVolumeResponse{
  269. FileId: assignResult.Fid,
  270. Count: int32(assignResult.Count),
  271. Location: &filer_pb.Location{
  272. Url: assignResult.Url,
  273. PublicUrl: assignResult.PublicUrl,
  274. GrpcPort: uint32(assignResult.GrpcPort),
  275. },
  276. Auth: string(assignResult.Auth),
  277. Collection: so.Collection,
  278. Replication: so.Replication,
  279. }, nil
  280. }
  281. func (fs *FilerServer) CollectionList(ctx context.Context, req *filer_pb.CollectionListRequest) (resp *filer_pb.CollectionListResponse, err error) {
  282. glog.V(4).Infof("CollectionList %v", req)
  283. resp = &filer_pb.CollectionListResponse{}
  284. err = fs.filer.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
  285. masterResp, err := client.CollectionList(context.Background(), &master_pb.CollectionListRequest{
  286. IncludeNormalVolumes: req.IncludeNormalVolumes,
  287. IncludeEcVolumes: req.IncludeEcVolumes,
  288. })
  289. if err != nil {
  290. return err
  291. }
  292. for _, c := range masterResp.Collections {
  293. resp.Collections = append(resp.Collections, &filer_pb.Collection{Name: c.Name})
  294. }
  295. return nil
  296. })
  297. return
  298. }
  299. func (fs *FilerServer) DeleteCollection(ctx context.Context, req *filer_pb.DeleteCollectionRequest) (resp *filer_pb.DeleteCollectionResponse, err error) {
  300. glog.V(4).Infof("DeleteCollection %v", req)
  301. err = fs.filer.MasterClient.WithClient(false, func(client master_pb.SeaweedClient) error {
  302. _, err := client.CollectionDelete(context.Background(), &master_pb.CollectionDeleteRequest{
  303. Name: req.GetCollection(),
  304. })
  305. return err
  306. })
  307. return &filer_pb.DeleteCollectionResponse{}, err
  308. }