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