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.

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