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.

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