filer_grpc_server.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  1. package weed_server
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "time"
  9. "github.com/chrislusf/seaweedfs/weed/filer"
  10. "github.com/chrislusf/seaweedfs/weed/glog"
  11. "github.com/chrislusf/seaweedfs/weed/operation"
  12. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  13. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  14. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. )
  17. func (fs *FilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
  18. glog.V(4).Infof("LookupDirectoryEntry %s", filepath.Join(req.Directory, req.Name))
  19. entry, err := fs.filer.FindEntry(ctx, util.JoinPath(req.Directory, req.Name))
  20. if err == filer_pb.ErrNotFound {
  21. return &filer_pb.LookupDirectoryEntryResponse{}, err
  22. }
  23. if err != nil {
  24. glog.V(3).Infof("LookupDirectoryEntry %s: %+v, ", filepath.Join(req.Directory, req.Name), err)
  25. return nil, err
  26. }
  27. return &filer_pb.LookupDirectoryEntryResponse{
  28. Entry: &filer_pb.Entry{
  29. Name: req.Name,
  30. IsDirectory: entry.IsDirectory(),
  31. Attributes: filer.EntryAttributeToPb(entry),
  32. Chunks: entry.Chunks,
  33. Extended: entry.Extended,
  34. HardLinkId: entry.HardLinkId,
  35. HardLinkCounter: entry.HardLinkCounter,
  36. Content: entry.Content,
  37. },
  38. }, nil
  39. }
  40. func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) (err error) {
  41. glog.V(4).Infof("ListEntries %v", req)
  42. limit := int(req.Limit)
  43. if limit == 0 {
  44. limit = fs.option.DirListingLimit
  45. }
  46. paginationLimit := filer.PaginationSize
  47. if limit < paginationLimit {
  48. paginationLimit = limit
  49. }
  50. lastFileName := req.StartFromFileName
  51. includeLastFile := req.InclusiveStartFrom
  52. var listErr error
  53. for limit > 0 {
  54. var hasEntries bool
  55. lastFileName, listErr = fs.filer.StreamListDirectoryEntries(stream.Context(), util.FullPath(req.Directory), lastFileName, includeLastFile, int64(paginationLimit), req.Prefix, "", func(entry *filer.Entry) bool {
  56. hasEntries = true
  57. if err = stream.Send(&filer_pb.ListEntriesResponse{
  58. Entry: &filer_pb.Entry{
  59. Name: entry.Name(),
  60. IsDirectory: entry.IsDirectory(),
  61. Chunks: entry.Chunks,
  62. Attributes: filer.EntryAttributeToPb(entry),
  63. Extended: entry.Extended,
  64. HardLinkId: entry.HardLinkId,
  65. HardLinkCounter: entry.HardLinkCounter,
  66. Content: entry.Content,
  67. },
  68. }); err != nil {
  69. return false
  70. }
  71. limit--
  72. if limit == 0 {
  73. return false
  74. }
  75. return true
  76. })
  77. if listErr != nil {
  78. return listErr
  79. }
  80. if err != nil {
  81. return err
  82. }
  83. if !hasEntries {
  84. return nil
  85. }
  86. includeLastFile = false
  87. }
  88. return nil
  89. }
  90. func (fs *FilerServer) LookupVolume(ctx context.Context, req *filer_pb.LookupVolumeRequest) (*filer_pb.LookupVolumeResponse, error) {
  91. resp := &filer_pb.LookupVolumeResponse{
  92. LocationsMap: make(map[string]*filer_pb.Locations),
  93. }
  94. for _, vidString := range req.VolumeIds {
  95. vid, err := strconv.Atoi(vidString)
  96. if err != nil {
  97. glog.V(1).Infof("Unknown volume id %d", vid)
  98. return nil, err
  99. }
  100. var locs []*filer_pb.Location
  101. locations, found := fs.filer.MasterClient.GetLocations(uint32(vid))
  102. if !found {
  103. continue
  104. }
  105. for _, loc := range locations {
  106. locs = append(locs, &filer_pb.Location{
  107. Url: loc.Url,
  108. PublicUrl: loc.PublicUrl,
  109. })
  110. }
  111. resp.LocationsMap[vidString] = &filer_pb.Locations{
  112. Locations: locs,
  113. }
  114. }
  115. return resp, nil
  116. }
  117. func (fs *FilerServer) lookupFileId(fileId string) (targetUrls []string, err error) {
  118. fid, err := needle.ParseFileIdFromString(fileId)
  119. if err != nil {
  120. return nil, err
  121. }
  122. locations, found := fs.filer.MasterClient.GetLocations(uint32(fid.VolumeId))
  123. if !found || len(locations) == 0 {
  124. return nil, fmt.Errorf("not found volume %d in %s", fid.VolumeId, fileId)
  125. }
  126. for _, loc := range locations {
  127. targetUrls = append(targetUrls, fmt.Sprintf("http://%s/%s", loc.Url, fileId))
  128. }
  129. return
  130. }
  131. func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (resp *filer_pb.CreateEntryResponse, err error) {
  132. glog.V(4).Infof("CreateEntry %v/%v", req.Directory, req.Entry.Name)
  133. resp = &filer_pb.CreateEntryResponse{}
  134. chunks, garbage, err2 := fs.cleanupChunks(util.Join(req.Directory, req.Entry.Name), nil, req.Entry)
  135. if err2 != nil {
  136. return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry cleanupChunks %s %s: %v", req.Directory, req.Entry.Name, err2)
  137. }
  138. createErr := fs.filer.CreateEntry(ctx, &filer.Entry{
  139. FullPath: util.JoinPath(req.Directory, req.Entry.Name),
  140. Attr: filer.PbToEntryAttribute(req.Entry.Attributes),
  141. Chunks: chunks,
  142. Extended: req.Entry.Extended,
  143. HardLinkId: filer.HardLinkId(req.Entry.HardLinkId),
  144. HardLinkCounter: req.Entry.HardLinkCounter,
  145. Content: req.Entry.Content,
  146. }, req.OExcl, req.IsFromOtherCluster, req.Signatures)
  147. if createErr == nil {
  148. fs.filer.DeleteChunks(garbage)
  149. } else {
  150. glog.V(3).Infof("CreateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), createErr)
  151. resp.Error = createErr.Error()
  152. }
  153. return
  154. }
  155. func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
  156. glog.V(4).Infof("UpdateEntry %v", req)
  157. fullpath := util.Join(req.Directory, req.Entry.Name)
  158. entry, err := fs.filer.FindEntry(ctx, util.FullPath(fullpath))
  159. if err != nil {
  160. return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("not found %s: %v", fullpath, err)
  161. }
  162. chunks, garbage, err2 := fs.cleanupChunks(fullpath, entry, req.Entry)
  163. if err2 != nil {
  164. return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("UpdateEntry cleanupChunks %s: %v", fullpath, err2)
  165. }
  166. newEntry := &filer.Entry{
  167. FullPath: util.JoinPath(req.Directory, req.Entry.Name),
  168. Attr: entry.Attr,
  169. Extended: req.Entry.Extended,
  170. Chunks: chunks,
  171. HardLinkId: filer.HardLinkId(req.Entry.HardLinkId),
  172. HardLinkCounter: req.Entry.HardLinkCounter,
  173. Content: req.Entry.Content,
  174. }
  175. glog.V(3).Infof("updating %s: %+v, chunks %d: %v => %+v, chunks %d: %v, extended: %v => %v",
  176. fullpath, entry.Attr, len(entry.Chunks), entry.Chunks,
  177. req.Entry.Attributes, len(req.Entry.Chunks), req.Entry.Chunks,
  178. entry.Extended, req.Entry.Extended)
  179. if req.Entry.Attributes != nil {
  180. if req.Entry.Attributes.Mtime != 0 {
  181. newEntry.Attr.Mtime = time.Unix(req.Entry.Attributes.Mtime, 0)
  182. }
  183. if req.Entry.Attributes.FileMode != 0 {
  184. newEntry.Attr.Mode = os.FileMode(req.Entry.Attributes.FileMode)
  185. }
  186. newEntry.Attr.Uid = req.Entry.Attributes.Uid
  187. newEntry.Attr.Gid = req.Entry.Attributes.Gid
  188. newEntry.Attr.Mime = req.Entry.Attributes.Mime
  189. newEntry.Attr.UserName = req.Entry.Attributes.UserName
  190. newEntry.Attr.GroupNames = req.Entry.Attributes.GroupName
  191. }
  192. if filer.EqualEntry(entry, newEntry) {
  193. return &filer_pb.UpdateEntryResponse{}, err
  194. }
  195. if err = fs.filer.UpdateEntry(ctx, entry, newEntry); err == nil {
  196. fs.filer.DeleteChunks(garbage)
  197. fs.filer.NotifyUpdateEvent(ctx, entry, newEntry, true, req.IsFromOtherCluster, req.Signatures)
  198. } else {
  199. glog.V(3).Infof("UpdateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), err)
  200. }
  201. return &filer_pb.UpdateEntryResponse{}, err
  202. }
  203. func (fs *FilerServer) cleanupChunks(fullpath string, existingEntry *filer.Entry, newEntry *filer_pb.Entry) (chunks, garbage []*filer_pb.FileChunk, err error) {
  204. // remove old chunks if not included in the new ones
  205. if existingEntry != nil {
  206. garbage, err = filer.MinusChunks(fs.lookupFileId, existingEntry.Chunks, newEntry.Chunks)
  207. if err != nil {
  208. return newEntry.Chunks, nil, fmt.Errorf("MinusChunks: %v", err)
  209. }
  210. }
  211. // files with manifest chunks are usually large and append only, skip calculating covered chunks
  212. manifestChunks, nonManifestChunks := filer.SeparateManifestChunks(newEntry.Chunks)
  213. chunks, coveredChunks := filer.CompactFileChunks(fs.lookupFileId, nonManifestChunks)
  214. garbage = append(garbage, coveredChunks...)
  215. if newEntry.Attributes != nil {
  216. so := fs.detectStorageOption(fullpath,
  217. newEntry.Attributes.Collection,
  218. newEntry.Attributes.Replication,
  219. newEntry.Attributes.TtlSec,
  220. "",
  221. "",
  222. )
  223. chunks, err = filer.MaybeManifestize(fs.saveAsChunk(so), chunks)
  224. if err != nil {
  225. // not good, but should be ok
  226. glog.V(0).Infof("MaybeManifestize: %v", err)
  227. }
  228. }
  229. chunks = append(chunks, manifestChunks...)
  230. return
  231. }
  232. func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendToEntryRequest) (*filer_pb.AppendToEntryResponse, error) {
  233. glog.V(4).Infof("AppendToEntry %v", req)
  234. fullpath := util.NewFullPath(req.Directory, req.EntryName)
  235. var offset int64 = 0
  236. entry, err := fs.filer.FindEntry(ctx, fullpath)
  237. if err == filer_pb.ErrNotFound {
  238. entry = &filer.Entry{
  239. FullPath: fullpath,
  240. Attr: filer.Attr{
  241. Crtime: time.Now(),
  242. Mtime: time.Now(),
  243. Mode: os.FileMode(0644),
  244. Uid: OS_UID,
  245. Gid: OS_GID,
  246. },
  247. }
  248. } else {
  249. offset = int64(filer.TotalSize(entry.Chunks))
  250. }
  251. for _, chunk := range req.Chunks {
  252. chunk.Offset = offset
  253. offset += int64(chunk.Size)
  254. }
  255. entry.Chunks = append(entry.Chunks, req.Chunks...)
  256. so := fs.detectStorageOption(string(fullpath), entry.Collection, entry.Replication, entry.TtlSec, "", "")
  257. entry.Chunks, err = filer.MaybeManifestize(fs.saveAsChunk(so), entry.Chunks)
  258. if err != nil {
  259. // not good, but should be ok
  260. glog.V(0).Infof("MaybeManifestize: %v", err)
  261. }
  262. err = fs.filer.CreateEntry(context.Background(), entry, false, false, nil)
  263. return &filer_pb.AppendToEntryResponse{}, err
  264. }
  265. func (fs *FilerServer) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest) (resp *filer_pb.DeleteEntryResponse, err error) {
  266. glog.V(4).Infof("DeleteEntry %v", req)
  267. err = fs.filer.DeleteEntryMetaAndData(ctx, util.JoinPath(req.Directory, req.Name), req.IsRecursive, req.IgnoreRecursiveError, req.IsDeleteData, req.IsFromOtherCluster, req.Signatures)
  268. resp = &filer_pb.DeleteEntryResponse{}
  269. if err != nil && err != filer_pb.ErrNotFound {
  270. resp.Error = err.Error()
  271. }
  272. return resp, nil
  273. }
  274. func (fs *FilerServer) AssignVolume(ctx context.Context, req *filer_pb.AssignVolumeRequest) (resp *filer_pb.AssignVolumeResponse, err error) {
  275. so := fs.detectStorageOption(req.Path, req.Collection, req.Replication, req.TtlSec, req.DataCenter, req.Rack)
  276. assignRequest, altRequest := so.ToAssignRequests(int(req.Count))
  277. assignResult, err := operation.Assign(fs.filer.GetMaster(), fs.grpcDialOption, assignRequest, altRequest)
  278. if err != nil {
  279. glog.V(3).Infof("AssignVolume: %v", err)
  280. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume: %v", err)}, nil
  281. }
  282. if assignResult.Error != "" {
  283. glog.V(3).Infof("AssignVolume error: %v", assignResult.Error)
  284. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume result: %v", assignResult.Error)}, nil
  285. }
  286. return &filer_pb.AssignVolumeResponse{
  287. FileId: assignResult.Fid,
  288. Count: int32(assignResult.Count),
  289. Url: assignResult.Url,
  290. PublicUrl: assignResult.PublicUrl,
  291. Auth: string(assignResult.Auth),
  292. Collection: so.Collection,
  293. Replication: so.Replication,
  294. }, nil
  295. }
  296. func (fs *FilerServer) CollectionList(ctx context.Context, req *filer_pb.CollectionListRequest) (resp *filer_pb.CollectionListResponse, err error) {
  297. glog.V(4).Infof("CollectionList %v", req)
  298. resp = &filer_pb.CollectionListResponse{}
  299. err = fs.filer.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  300. masterResp, err := client.CollectionList(context.Background(), &master_pb.CollectionListRequest{
  301. IncludeNormalVolumes: req.IncludeNormalVolumes,
  302. IncludeEcVolumes: req.IncludeEcVolumes,
  303. })
  304. if err != nil {
  305. return err
  306. }
  307. for _, c := range masterResp.Collections {
  308. resp.Collections = append(resp.Collections, &filer_pb.Collection{Name: c.Name})
  309. }
  310. return nil
  311. })
  312. return
  313. }
  314. func (fs *FilerServer) DeleteCollection(ctx context.Context, req *filer_pb.DeleteCollectionRequest) (resp *filer_pb.DeleteCollectionResponse, err error) {
  315. glog.V(4).Infof("DeleteCollection %v", req)
  316. err = fs.filer.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  317. _, err := client.CollectionDelete(context.Background(), &master_pb.CollectionDeleteRequest{
  318. Name: req.GetCollection(),
  319. })
  320. return err
  321. })
  322. return &filer_pb.DeleteCollectionResponse{}, err
  323. }
  324. func (fs *FilerServer) Statistics(ctx context.Context, req *filer_pb.StatisticsRequest) (resp *filer_pb.StatisticsResponse, err error) {
  325. var output *master_pb.StatisticsResponse
  326. err = fs.filer.MasterClient.WithClient(func(masterClient master_pb.SeaweedClient) error {
  327. grpcResponse, grpcErr := masterClient.Statistics(context.Background(), &master_pb.StatisticsRequest{
  328. Replication: req.Replication,
  329. Collection: req.Collection,
  330. Ttl: req.Ttl,
  331. })
  332. if grpcErr != nil {
  333. return grpcErr
  334. }
  335. output = grpcResponse
  336. return nil
  337. })
  338. if err != nil {
  339. return nil, err
  340. }
  341. return &filer_pb.StatisticsResponse{
  342. TotalSize: output.TotalSize,
  343. UsedSize: output.UsedSize,
  344. FileCount: output.FileCount,
  345. }, nil
  346. }
  347. func (fs *FilerServer) GetFilerConfiguration(ctx context.Context, req *filer_pb.GetFilerConfigurationRequest) (resp *filer_pb.GetFilerConfigurationResponse, err error) {
  348. t := &filer_pb.GetFilerConfigurationResponse{
  349. Masters: fs.option.Masters,
  350. Collection: fs.option.Collection,
  351. Replication: fs.option.DefaultReplication,
  352. MaxMb: uint32(fs.option.MaxMB),
  353. DirBuckets: fs.filer.DirBucketsPath,
  354. Cipher: fs.filer.Cipher,
  355. Signature: fs.filer.Signature,
  356. MetricsAddress: fs.metricsAddress,
  357. MetricsIntervalSec: int32(fs.metricsIntervalSec),
  358. }
  359. glog.V(4).Infof("GetFilerConfiguration: %v", t)
  360. return t, nil
  361. }
  362. func (fs *FilerServer) KeepConnected(stream filer_pb.SeaweedFiler_KeepConnectedServer) error {
  363. req, err := stream.Recv()
  364. if err != nil {
  365. return err
  366. }
  367. clientName := fmt.Sprintf("%s:%d", req.Name, req.GrpcPort)
  368. m := make(map[string]bool)
  369. for _, tp := range req.Resources {
  370. m[tp] = true
  371. }
  372. fs.brokersLock.Lock()
  373. fs.brokers[clientName] = m
  374. glog.V(0).Infof("+ broker %v", clientName)
  375. fs.brokersLock.Unlock()
  376. defer func() {
  377. fs.brokersLock.Lock()
  378. delete(fs.brokers, clientName)
  379. glog.V(0).Infof("- broker %v: %v", clientName, err)
  380. fs.brokersLock.Unlock()
  381. }()
  382. for {
  383. if err := stream.Send(&filer_pb.KeepConnectedResponse{}); err != nil {
  384. glog.V(0).Infof("send broker %v: %+v", clientName, err)
  385. return err
  386. }
  387. // println("replied")
  388. if _, err := stream.Recv(); err != nil {
  389. glog.V(0).Infof("recv broker %v: %v", clientName, err)
  390. return err
  391. }
  392. // println("received")
  393. }
  394. }
  395. func (fs *FilerServer) LocateBroker(ctx context.Context, req *filer_pb.LocateBrokerRequest) (resp *filer_pb.LocateBrokerResponse, err error) {
  396. resp = &filer_pb.LocateBrokerResponse{}
  397. fs.brokersLock.Lock()
  398. defer fs.brokersLock.Unlock()
  399. var localBrokers []*filer_pb.LocateBrokerResponse_Resource
  400. for b, m := range fs.brokers {
  401. if _, found := m[req.Resource]; found {
  402. resp.Found = true
  403. resp.Resources = []*filer_pb.LocateBrokerResponse_Resource{
  404. {
  405. GrpcAddresses: b,
  406. ResourceCount: int32(len(m)),
  407. },
  408. }
  409. return
  410. }
  411. localBrokers = append(localBrokers, &filer_pb.LocateBrokerResponse_Resource{
  412. GrpcAddresses: b,
  413. ResourceCount: int32(len(m)),
  414. })
  415. }
  416. resp.Resources = localBrokers
  417. return resp, nil
  418. }