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.

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