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.

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