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.

512 lines
15 KiB

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