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.

513 lines
14 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
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. "strings"
  9. "time"
  10. "github.com/chrislusf/seaweedfs/weed/filer2"
  11. "github.com/chrislusf/seaweedfs/weed/glog"
  12. "github.com/chrislusf/seaweedfs/weed/operation"
  13. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  14. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  15. "github.com/chrislusf/seaweedfs/weed/storage/needle"
  16. "github.com/chrislusf/seaweedfs/weed/util"
  17. )
  18. func (fs *FilerServer) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
  19. glog.V(4).Infof("LookupDirectoryEntry %s", filepath.Join(req.Directory, req.Name))
  20. entry, err := fs.filer.FindEntry(ctx, util.JoinPath(req.Directory, req.Name))
  21. if err == filer_pb.ErrNotFound {
  22. return &filer_pb.LookupDirectoryEntryResponse{}, err
  23. }
  24. if err != nil {
  25. glog.V(3).Infof("LookupDirectoryEntry %s: %+v, ", filepath.Join(req.Directory, req.Name), err)
  26. return nil, err
  27. }
  28. return &filer_pb.LookupDirectoryEntryResponse{
  29. Entry: &filer_pb.Entry{
  30. Name: req.Name,
  31. IsDirectory: entry.IsDirectory(),
  32. Attributes: filer2.EntryAttributeToPb(entry),
  33. Chunks: entry.Chunks,
  34. Extended: entry.Extended,
  35. },
  36. }, nil
  37. }
  38. func (fs *FilerServer) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
  39. glog.V(4).Infof("ListEntries %v", req)
  40. limit := int(req.Limit)
  41. if limit == 0 {
  42. limit = fs.option.DirListingLimit
  43. }
  44. paginationLimit := filer2.PaginationSize
  45. if limit < paginationLimit {
  46. paginationLimit = limit
  47. }
  48. lastFileName := req.StartFromFileName
  49. includeLastFile := req.InclusiveStartFrom
  50. for limit > 0 {
  51. entries, err := fs.filer.ListDirectoryEntries(stream.Context(), util.FullPath(req.Directory), lastFileName, includeLastFile, paginationLimit)
  52. if err != nil {
  53. return err
  54. }
  55. if len(entries) == 0 {
  56. return nil
  57. }
  58. includeLastFile = false
  59. for _, entry := range entries {
  60. lastFileName = entry.Name()
  61. if req.Prefix != "" {
  62. if !strings.HasPrefix(entry.Name(), req.Prefix) {
  63. continue
  64. }
  65. }
  66. if err := stream.Send(&filer_pb.ListEntriesResponse{
  67. Entry: &filer_pb.Entry{
  68. Name: entry.Name(),
  69. IsDirectory: entry.IsDirectory(),
  70. Chunks: entry.Chunks,
  71. Attributes: filer2.EntryAttributeToPb(entry),
  72. Extended: entry.Extended,
  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) (targetUrl string, err error) {
  116. fid, err := needle.ParseFileIdFromString(fileId)
  117. if err != nil {
  118. return "", err
  119. }
  120. locations, found := fs.filer.MasterClient.GetLocations(uint32(fid.VolumeId))
  121. if !found || len(locations) == 0 {
  122. return "", fmt.Errorf("not found volume %d in %s", fid.VolumeId, fileId)
  123. }
  124. return fmt.Sprintf("http://%s/%s", locations[0].Url, fileId), nil
  125. }
  126. func (fs *FilerServer) CreateEntry(ctx context.Context, req *filer_pb.CreateEntryRequest) (resp *filer_pb.CreateEntryResponse, err error) {
  127. glog.V(4).Infof("CreateEntry %v", req)
  128. resp = &filer_pb.CreateEntryResponse{}
  129. chunks, garbage, err2 := fs.cleanupChunks(nil, req.Entry)
  130. if err2 != nil {
  131. return &filer_pb.CreateEntryResponse{}, fmt.Errorf("CreateEntry cleanupChunks %s %s: %v", req.Directory, req.Entry.Name, err2)
  132. }
  133. if req.Entry.Attributes == nil {
  134. glog.V(3).Infof("CreateEntry %s: nil attributes", filepath.Join(req.Directory, req.Entry.Name))
  135. resp.Error = fmt.Sprintf("can not create entry with empty attributes")
  136. return
  137. }
  138. createErr := fs.filer.CreateEntry(ctx, &filer2.Entry{
  139. FullPath: util.JoinPath(req.Directory, req.Entry.Name),
  140. Attr: filer2.PbToEntryAttribute(req.Entry.Attributes),
  141. Chunks: chunks,
  142. }, req.OExcl, req.IsFromOtherCluster)
  143. if createErr == nil {
  144. fs.filer.DeleteChunks(garbage)
  145. } else {
  146. glog.V(3).Infof("CreateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), createErr)
  147. resp.Error = createErr.Error()
  148. }
  149. return
  150. }
  151. func (fs *FilerServer) UpdateEntry(ctx context.Context, req *filer_pb.UpdateEntryRequest) (*filer_pb.UpdateEntryResponse, error) {
  152. glog.V(4).Infof("UpdateEntry %v", req)
  153. fullpath := util.Join(req.Directory, req.Entry.Name)
  154. entry, err := fs.filer.FindEntry(ctx, util.FullPath(fullpath))
  155. if err != nil {
  156. return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("not found %s: %v", fullpath, err)
  157. }
  158. chunks, garbage, err2 := fs.cleanupChunks(entry, req.Entry)
  159. if err2 != nil {
  160. return &filer_pb.UpdateEntryResponse{}, fmt.Errorf("UpdateEntry cleanupChunks %s: %v", fullpath, err2)
  161. }
  162. newEntry := &filer2.Entry{
  163. FullPath: util.JoinPath(req.Directory, req.Entry.Name),
  164. Attr: entry.Attr,
  165. Extended: req.Entry.Extended,
  166. Chunks: chunks,
  167. }
  168. glog.V(3).Infof("updating %s: %+v, chunks %d: %v => %+v, chunks %d: %v, extended: %v => %v",
  169. fullpath, entry.Attr, len(entry.Chunks), entry.Chunks,
  170. req.Entry.Attributes, len(req.Entry.Chunks), req.Entry.Chunks,
  171. entry.Extended, req.Entry.Extended)
  172. if req.Entry.Attributes != nil {
  173. if req.Entry.Attributes.Mtime != 0 {
  174. newEntry.Attr.Mtime = time.Unix(req.Entry.Attributes.Mtime, 0)
  175. }
  176. if req.Entry.Attributes.FileMode != 0 {
  177. newEntry.Attr.Mode = os.FileMode(req.Entry.Attributes.FileMode)
  178. }
  179. newEntry.Attr.Uid = req.Entry.Attributes.Uid
  180. newEntry.Attr.Gid = req.Entry.Attributes.Gid
  181. newEntry.Attr.Mime = req.Entry.Attributes.Mime
  182. newEntry.Attr.UserName = req.Entry.Attributes.UserName
  183. newEntry.Attr.GroupNames = req.Entry.Attributes.GroupName
  184. }
  185. if filer2.EqualEntry(entry, newEntry) {
  186. return &filer_pb.UpdateEntryResponse{}, err
  187. }
  188. if err = fs.filer.UpdateEntry(ctx, entry, newEntry); err == nil {
  189. fs.filer.DeleteChunks(garbage)
  190. } else {
  191. glog.V(3).Infof("UpdateEntry %s: %v", filepath.Join(req.Directory, req.Entry.Name), err)
  192. }
  193. fs.filer.NotifyUpdateEvent(ctx, entry, newEntry, true, req.IsFromOtherCluster)
  194. return &filer_pb.UpdateEntryResponse{}, err
  195. }
  196. func (fs *FilerServer) cleanupChunks(existingEntry *filer2.Entry, newEntry *filer_pb.Entry) (chunks, garbage []*filer_pb.FileChunk, err error) {
  197. // remove old chunks if not included in the new ones
  198. if existingEntry != nil {
  199. garbage, err = filer2.MinusChunks(fs.lookupFileId, existingEntry.Chunks, newEntry.Chunks)
  200. if err != nil {
  201. return newEntry.Chunks, nil, fmt.Errorf("MinusChunks: %v", err)
  202. }
  203. }
  204. // files with manifest chunks are usually large and append only, skip calculating covered chunks
  205. manifestChunks, nonManifestChunks := filer2.SeparateManifestChunks(newEntry.Chunks)
  206. chunks, coveredChunks := filer2.CompactFileChunks(fs.lookupFileId, nonManifestChunks)
  207. garbage = append(garbage, coveredChunks...)
  208. chunks, err = filer2.MaybeManifestize(fs.saveAsChunk(
  209. newEntry.Attributes.Replication,
  210. newEntry.Attributes.Collection,
  211. "",
  212. needle.SecondsToTTL(newEntry.Attributes.TtlSec),
  213. false), chunks)
  214. if err != nil {
  215. // not good, but should be ok
  216. glog.V(0).Infof("MaybeManifestize: %v", err)
  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 = &filer2.Entry{
  228. FullPath: fullpath,
  229. Attr: filer2.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(filer2.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 = filer2.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)
  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)
  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. }
  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. }