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.

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