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.

540 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
5 years ago
5 years ago
5 years ago
4 years ago
5 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", req)
  129. resp = &filer_pb.CreateEntryResponse{}
  130. chunks, garbage, err2 := fs.cleanupChunks(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(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(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. chunks, err = filer.MaybeManifestize(fs.saveAsChunk(
  211. newEntry.Attributes.Replication,
  212. newEntry.Attributes.Collection,
  213. "",
  214. needle.SecondsToTTL(newEntry.Attributes.TtlSec),
  215. false), chunks)
  216. if err != nil {
  217. // not good, but should be ok
  218. glog.V(0).Infof("MaybeManifestize: %v", err)
  219. }
  220. }
  221. chunks = append(chunks, manifestChunks...)
  222. return
  223. }
  224. func (fs *FilerServer) AppendToEntry(ctx context.Context, req *filer_pb.AppendToEntryRequest) (*filer_pb.AppendToEntryResponse, error) {
  225. glog.V(4).Infof("AppendToEntry %v", req)
  226. fullpath := util.NewFullPath(req.Directory, req.EntryName)
  227. var offset int64 = 0
  228. entry, err := fs.filer.FindEntry(ctx, util.FullPath(fullpath))
  229. if err == filer_pb.ErrNotFound {
  230. entry = &filer.Entry{
  231. FullPath: fullpath,
  232. Attr: filer.Attr{
  233. Crtime: time.Now(),
  234. Mtime: time.Now(),
  235. Mode: os.FileMode(0644),
  236. Uid: OS_UID,
  237. Gid: OS_GID,
  238. },
  239. }
  240. } else {
  241. offset = int64(filer.TotalSize(entry.Chunks))
  242. }
  243. for _, chunk := range req.Chunks {
  244. chunk.Offset = offset
  245. offset += int64(chunk.Size)
  246. }
  247. entry.Chunks = append(entry.Chunks, req.Chunks...)
  248. entry.Chunks, err = filer.MaybeManifestize(fs.saveAsChunk(
  249. entry.Replication,
  250. entry.Collection,
  251. "",
  252. needle.SecondsToTTL(entry.TtlSec),
  253. false), 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. ttlStr := ""
  272. if req.TtlSec > 0 {
  273. ttlStr = strconv.Itoa(int(req.TtlSec))
  274. }
  275. collection, replication, _ := fs.detectCollection(req.ParentPath, req.Collection, req.Replication)
  276. var altRequest *operation.VolumeAssignRequest
  277. dataCenter := req.DataCenter
  278. if dataCenter == "" {
  279. dataCenter = fs.option.DataCenter
  280. }
  281. assignRequest := &operation.VolumeAssignRequest{
  282. Count: uint64(req.Count),
  283. Replication: replication,
  284. Collection: collection,
  285. Ttl: ttlStr,
  286. DataCenter: dataCenter,
  287. }
  288. if dataCenter != "" {
  289. altRequest = &operation.VolumeAssignRequest{
  290. Count: uint64(req.Count),
  291. Replication: replication,
  292. Collection: collection,
  293. Ttl: ttlStr,
  294. DataCenter: "",
  295. }
  296. }
  297. assignResult, err := operation.Assign(fs.filer.GetMaster(), fs.grpcDialOption, assignRequest, altRequest)
  298. if err != nil {
  299. glog.V(3).Infof("AssignVolume: %v", err)
  300. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume: %v", err)}, nil
  301. }
  302. if assignResult.Error != "" {
  303. glog.V(3).Infof("AssignVolume error: %v", assignResult.Error)
  304. return &filer_pb.AssignVolumeResponse{Error: fmt.Sprintf("assign volume result: %v", assignResult.Error)}, nil
  305. }
  306. return &filer_pb.AssignVolumeResponse{
  307. FileId: assignResult.Fid,
  308. Count: int32(assignResult.Count),
  309. Url: assignResult.Url,
  310. PublicUrl: assignResult.PublicUrl,
  311. Auth: string(assignResult.Auth),
  312. Collection: collection,
  313. Replication: replication,
  314. }, nil
  315. }
  316. func (fs *FilerServer) CollectionList(ctx context.Context, req *filer_pb.CollectionListRequest) (resp *filer_pb.CollectionListResponse, err error) {
  317. glog.V(4).Infof("CollectionList %v", req)
  318. resp = &filer_pb.CollectionListResponse{}
  319. err = fs.filer.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  320. masterResp, err := client.CollectionList(context.Background(), &master_pb.CollectionListRequest{
  321. IncludeNormalVolumes: req.IncludeNormalVolumes,
  322. IncludeEcVolumes: req.IncludeEcVolumes,
  323. })
  324. if err != nil {
  325. return err
  326. }
  327. for _, c := range masterResp.Collections {
  328. resp.Collections = append(resp.Collections, &filer_pb.Collection{Name: c.Name})
  329. }
  330. return nil
  331. })
  332. return
  333. }
  334. func (fs *FilerServer) DeleteCollection(ctx context.Context, req *filer_pb.DeleteCollectionRequest) (resp *filer_pb.DeleteCollectionResponse, err error) {
  335. glog.V(4).Infof("DeleteCollection %v", req)
  336. err = fs.filer.MasterClient.WithClient(func(client master_pb.SeaweedClient) error {
  337. _, err := client.CollectionDelete(context.Background(), &master_pb.CollectionDeleteRequest{
  338. Name: req.GetCollection(),
  339. })
  340. return err
  341. })
  342. return &filer_pb.DeleteCollectionResponse{}, err
  343. }
  344. func (fs *FilerServer) Statistics(ctx context.Context, req *filer_pb.StatisticsRequest) (resp *filer_pb.StatisticsResponse, err error) {
  345. var output *master_pb.StatisticsResponse
  346. err = fs.filer.MasterClient.WithClient(func(masterClient master_pb.SeaweedClient) error {
  347. grpcResponse, grpcErr := masterClient.Statistics(context.Background(), &master_pb.StatisticsRequest{
  348. Replication: req.Replication,
  349. Collection: req.Collection,
  350. Ttl: req.Ttl,
  351. })
  352. if grpcErr != nil {
  353. return grpcErr
  354. }
  355. output = grpcResponse
  356. return nil
  357. })
  358. if err != nil {
  359. return nil, err
  360. }
  361. return &filer_pb.StatisticsResponse{
  362. TotalSize: output.TotalSize,
  363. UsedSize: output.UsedSize,
  364. FileCount: output.FileCount,
  365. }, nil
  366. }
  367. func (fs *FilerServer) GetFilerConfiguration(ctx context.Context, req *filer_pb.GetFilerConfigurationRequest) (resp *filer_pb.GetFilerConfigurationResponse, err error) {
  368. t := &filer_pb.GetFilerConfigurationResponse{
  369. Masters: fs.option.Masters,
  370. Collection: fs.option.Collection,
  371. Replication: fs.option.DefaultReplication,
  372. MaxMb: uint32(fs.option.MaxMB),
  373. DirBuckets: fs.filer.DirBucketsPath,
  374. Cipher: fs.filer.Cipher,
  375. Signature: fs.filer.Signature,
  376. MetricsAddress: fs.metricsAddress,
  377. MetricsIntervalSec: int32(fs.metricsIntervalSec),
  378. }
  379. glog.V(4).Infof("GetFilerConfiguration: %v", t)
  380. return t, nil
  381. }
  382. func (fs *FilerServer) KeepConnected(stream filer_pb.SeaweedFiler_KeepConnectedServer) error {
  383. req, err := stream.Recv()
  384. if err != nil {
  385. return err
  386. }
  387. clientName := fmt.Sprintf("%s:%d", req.Name, req.GrpcPort)
  388. m := make(map[string]bool)
  389. for _, tp := range req.Resources {
  390. m[tp] = true
  391. }
  392. fs.brokersLock.Lock()
  393. fs.brokers[clientName] = m
  394. glog.V(0).Infof("+ broker %v", clientName)
  395. fs.brokersLock.Unlock()
  396. defer func() {
  397. fs.brokersLock.Lock()
  398. delete(fs.brokers, clientName)
  399. glog.V(0).Infof("- broker %v: %v", clientName, err)
  400. fs.brokersLock.Unlock()
  401. }()
  402. for {
  403. if err := stream.Send(&filer_pb.KeepConnectedResponse{}); err != nil {
  404. glog.V(0).Infof("send broker %v: %+v", clientName, err)
  405. return err
  406. }
  407. // println("replied")
  408. if _, err := stream.Recv(); err != nil {
  409. glog.V(0).Infof("recv broker %v: %v", clientName, err)
  410. return err
  411. }
  412. // println("received")
  413. }
  414. }
  415. func (fs *FilerServer) LocateBroker(ctx context.Context, req *filer_pb.LocateBrokerRequest) (resp *filer_pb.LocateBrokerResponse, err error) {
  416. resp = &filer_pb.LocateBrokerResponse{}
  417. fs.brokersLock.Lock()
  418. defer fs.brokersLock.Unlock()
  419. var localBrokers []*filer_pb.LocateBrokerResponse_Resource
  420. for b, m := range fs.brokers {
  421. if _, found := m[req.Resource]; found {
  422. resp.Found = true
  423. resp.Resources = []*filer_pb.LocateBrokerResponse_Resource{
  424. {
  425. GrpcAddresses: b,
  426. ResourceCount: int32(len(m)),
  427. },
  428. }
  429. return
  430. }
  431. localBrokers = append(localBrokers, &filer_pb.LocateBrokerResponse_Resource{
  432. GrpcAddresses: b,
  433. ResourceCount: int32(len(m)),
  434. })
  435. }
  436. resp.Resources = localBrokers
  437. return resp, nil
  438. }