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.

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