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.

377 lines
12 KiB

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