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.

379 lines
12 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
2 years ago
5 years ago
5 years ago
2 years ago
7 years ago
3 years ago
7 years ago
4 years ago
7 years ago
2 years ago
2 years ago
5 years ago
2 years ago
2 years ago
2 years ago
3 years ago
5 years ago
4 years ago
5 years ago
5 years ago
7 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
7 years ago
4 years ago
4 years ago
7 years ago
4 years ago
4 years ago
4 years ago
7 years ago
7 years ago
1 year ago
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
  6. "os"
  7. "sort"
  8. "strings"
  9. "time"
  10. "github.com/seaweedfs/seaweedfs/weed/cluster/lock_manager"
  11. "github.com/seaweedfs/seaweedfs/weed/cluster"
  12. "github.com/seaweedfs/seaweedfs/weed/pb"
  13. "github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
  14. "google.golang.org/grpc"
  15. "github.com/seaweedfs/seaweedfs/weed/glog"
  16. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  17. "github.com/seaweedfs/seaweedfs/weed/util"
  18. "github.com/seaweedfs/seaweedfs/weed/util/log_buffer"
  19. "github.com/seaweedfs/seaweedfs/weed/wdclient"
  20. )
  21. const (
  22. LogFlushInterval = time.Minute
  23. PaginationSize = 1024
  24. FilerStoreId = "filer.store.id"
  25. )
  26. var (
  27. OS_UID = uint32(os.Getuid())
  28. OS_GID = uint32(os.Getgid())
  29. )
  30. type Filer struct {
  31. UniqueFilerId int32
  32. UniqueFilerEpoch int32
  33. Store VirtualFilerStore
  34. MasterClient *wdclient.MasterClient
  35. fileIdDeletionQueue *util.UnboundedQueue
  36. GrpcDialOption grpc.DialOption
  37. DirBucketsPath string
  38. Cipher bool
  39. LocalMetaLogBuffer *log_buffer.LogBuffer
  40. metaLogCollection string
  41. metaLogReplication string
  42. MetaAggregator *MetaAggregator
  43. Signature int32
  44. FilerConf *FilerConf
  45. RemoteStorage *FilerRemoteStorage
  46. Dlm *lock_manager.DistributedLockManager
  47. MaxFilenameLength uint32
  48. }
  49. func NewFiler(masters pb.ServerDiscovery, grpcDialOption grpc.DialOption, filerHost pb.ServerAddress, filerGroup string, collection string, replication string, dataCenter string, maxFilenameLength uint32, notifyFn func()) *Filer {
  50. f := &Filer{
  51. MasterClient: wdclient.NewMasterClient(grpcDialOption, filerGroup, cluster.FilerType, filerHost, dataCenter, "", masters),
  52. fileIdDeletionQueue: util.NewUnboundedQueue(),
  53. GrpcDialOption: grpcDialOption,
  54. FilerConf: NewFilerConf(),
  55. RemoteStorage: NewFilerRemoteStorage(),
  56. UniqueFilerId: util.RandomInt32(),
  57. Dlm: lock_manager.NewDistributedLockManager(filerHost),
  58. MaxFilenameLength: maxFilenameLength,
  59. }
  60. if f.UniqueFilerId < 0 {
  61. f.UniqueFilerId = -f.UniqueFilerId
  62. }
  63. f.LocalMetaLogBuffer = log_buffer.NewLogBuffer("local", LogFlushInterval, f.logFlushFunc, nil, notifyFn)
  64. f.metaLogCollection = collection
  65. f.metaLogReplication = replication
  66. go f.loopProcessingDeletion()
  67. return f
  68. }
  69. func (f *Filer) MaybeBootstrapFromOnePeer(self pb.ServerAddress, existingNodes []*master_pb.ClusterNodeUpdate, snapshotTime time.Time) (err error) {
  70. if len(existingNodes) == 0 {
  71. return
  72. }
  73. sort.Slice(existingNodes, func(i, j int) bool {
  74. return existingNodes[i].CreatedAtNs < existingNodes[j].CreatedAtNs
  75. })
  76. earliestNode := existingNodes[0]
  77. if earliestNode.Address == string(self) {
  78. return
  79. }
  80. glog.V(0).Infof("bootstrap from %v clientId:%d", earliestNode.Address, f.UniqueFilerId)
  81. return pb.WithFilerClient(false, f.UniqueFilerId, pb.ServerAddress(earliestNode.Address), f.GrpcDialOption, func(client filer_pb.SeaweedFilerClient) error {
  82. return filer_pb.StreamBfs(client, "/", snapshotTime.UnixNano(), func(parentPath util.FullPath, entry *filer_pb.Entry) error {
  83. return f.Store.InsertEntry(context.Background(), FromPbEntry(string(parentPath), entry))
  84. })
  85. })
  86. }
  87. func (f *Filer) AggregateFromPeers(self pb.ServerAddress, existingNodes []*master_pb.ClusterNodeUpdate, startFrom time.Time) {
  88. var snapshot []pb.ServerAddress
  89. for _, node := range existingNodes {
  90. address := pb.ServerAddress(node.Address)
  91. snapshot = append(snapshot, address)
  92. }
  93. f.Dlm.LockRing.SetSnapshot(snapshot)
  94. glog.V(0).Infof("%s aggregate from peers %+v", self, snapshot)
  95. f.MetaAggregator = NewMetaAggregator(f, self, f.GrpcDialOption)
  96. f.MasterClient.SetOnPeerUpdateFn(func(update *master_pb.ClusterNodeUpdate, startFrom time.Time) {
  97. if update.NodeType != cluster.FilerType {
  98. return
  99. }
  100. address := pb.ServerAddress(update.Address)
  101. if update.IsAdd {
  102. f.Dlm.LockRing.AddServer(address)
  103. } else {
  104. f.Dlm.LockRing.RemoveServer(address)
  105. }
  106. f.MetaAggregator.OnPeerUpdate(update, startFrom)
  107. })
  108. for _, peerUpdate := range existingNodes {
  109. f.MetaAggregator.OnPeerUpdate(peerUpdate, startFrom)
  110. }
  111. }
  112. func (f *Filer) ListExistingPeerUpdates(ctx context.Context) (existingNodes []*master_pb.ClusterNodeUpdate) {
  113. return cluster.ListExistingPeerUpdates(f.GetMaster(ctx), f.GrpcDialOption, f.MasterClient.FilerGroup, cluster.FilerType)
  114. }
  115. func (f *Filer) SetStore(store FilerStore) (isFresh bool) {
  116. f.Store = NewFilerStoreWrapper(store)
  117. return f.setOrLoadFilerStoreSignature(store)
  118. }
  119. func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) (isFresh bool) {
  120. storeIdBytes, err := store.KvGet(context.Background(), []byte(FilerStoreId))
  121. if err == ErrKvNotFound || err == nil && len(storeIdBytes) == 0 {
  122. f.Signature = util.RandomInt32()
  123. storeIdBytes = make([]byte, 4)
  124. util.Uint32toBytes(storeIdBytes, uint32(f.Signature))
  125. if err = store.KvPut(context.Background(), []byte(FilerStoreId), storeIdBytes); err != nil {
  126. glog.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  127. }
  128. glog.V(0).Infof("create %s to %d", FilerStoreId, f.Signature)
  129. return true
  130. } else if err == nil && len(storeIdBytes) == 4 {
  131. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  132. glog.V(0).Infof("existing %s = %d", FilerStoreId, f.Signature)
  133. } else {
  134. glog.Fatalf("read %v=%v : %v", FilerStoreId, string(storeIdBytes), err)
  135. }
  136. return false
  137. }
  138. func (f *Filer) GetStore() (store FilerStore) {
  139. return f.Store
  140. }
  141. func (fs *Filer) GetMaster(ctx context.Context) pb.ServerAddress {
  142. return fs.MasterClient.GetMaster(ctx)
  143. }
  144. func (fs *Filer) KeepMasterClientConnected(ctx context.Context) {
  145. fs.MasterClient.KeepConnectedToMaster(ctx)
  146. }
  147. func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) {
  148. return f.Store.BeginTransaction(ctx)
  149. }
  150. func (f *Filer) CommitTransaction(ctx context.Context) error {
  151. return f.Store.CommitTransaction(ctx)
  152. }
  153. func (f *Filer) RollbackTransaction(ctx context.Context) error {
  154. return f.Store.RollbackTransaction(ctx)
  155. }
  156. func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32, skipCreateParentDir bool, maxFilenameLength uint32) error {
  157. if string(entry.FullPath) == "/" {
  158. return nil
  159. }
  160. if entry.FullPath.IsLongerFileName(maxFilenameLength) {
  161. return fmt.Errorf("entry name too long")
  162. }
  163. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  164. /*
  165. if !hasWritePermission(lastDirectoryEntry, entry) {
  166. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  167. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  168. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  169. }
  170. */
  171. if oldEntry == nil {
  172. if !skipCreateParentDir {
  173. dirParts := strings.Split(string(entry.FullPath), "/")
  174. if err := f.ensureParentDirectoryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  175. return err
  176. }
  177. }
  178. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  179. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  180. glog.Errorf("insert entry %s: %v", entry.FullPath, err)
  181. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  182. }
  183. } else {
  184. if o_excl {
  185. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  186. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  187. }
  188. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  189. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  190. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  191. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  192. }
  193. }
  194. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  195. f.deleteChunksIfNotNew(oldEntry, entry)
  196. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  197. return nil
  198. }
  199. func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  200. if level == 0 {
  201. return nil
  202. }
  203. dirPath := "/" + util.Join(dirParts[:level]...)
  204. // fmt.Printf("%d dirPath: %+v\n", level, dirPath)
  205. // check the store directly
  206. glog.V(4).Infof("find uncached directory: %s", dirPath)
  207. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  208. // no such existing directory
  209. if dirEntry == nil {
  210. // fmt.Printf("dirParts: %v %v %v\n", dirParts[0], dirParts[1], dirParts[2])
  211. // dirParts[0] == "" and dirParts[1] == "buckets"
  212. if len(dirParts) >= 3 && dirParts[1] == "buckets" {
  213. if err := s3bucket.VerifyS3BucketName(dirParts[2]); err != nil {
  214. return fmt.Errorf("invalid bucket name %s: %v", dirParts[2], err)
  215. }
  216. }
  217. // ensure parent directory
  218. if err = f.ensureParentDirectoryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  219. return err
  220. }
  221. // create the directory
  222. now := time.Now()
  223. dirEntry = &Entry{
  224. FullPath: util.FullPath(dirPath),
  225. Attr: Attr{
  226. Mtime: now,
  227. Crtime: now,
  228. Mode: os.ModeDir | entry.Mode | 0111,
  229. Uid: entry.Uid,
  230. Gid: entry.Gid,
  231. UserName: entry.UserName,
  232. GroupNames: entry.GroupNames,
  233. },
  234. }
  235. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  236. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  237. if mkdirErr != nil {
  238. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  239. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  240. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  241. }
  242. } else {
  243. if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
  244. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  245. }
  246. }
  247. } else if !dirEntry.IsDirectory() {
  248. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  249. return fmt.Errorf("%s is a file", dirPath)
  250. }
  251. return nil
  252. }
  253. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  254. if oldEntry != nil {
  255. entry.Attr.Crtime = oldEntry.Attr.Crtime
  256. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  257. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  258. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  259. }
  260. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  261. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  262. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  263. }
  264. }
  265. return f.Store.UpdateEntry(ctx, entry)
  266. }
  267. var (
  268. Root = &Entry{
  269. FullPath: "/",
  270. Attr: Attr{
  271. Mtime: time.Now(),
  272. Crtime: time.Now(),
  273. Mode: os.ModeDir | 0755,
  274. Uid: OS_UID,
  275. Gid: OS_GID,
  276. },
  277. }
  278. )
  279. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  280. if string(p) == "/" {
  281. return Root, nil
  282. }
  283. entry, err = f.Store.FindEntry(ctx, p)
  284. if entry != nil && entry.TtlSec > 0 {
  285. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  286. f.Store.DeleteOneEntry(ctx, entry)
  287. return nil, filer_pb.ErrNotFound
  288. }
  289. }
  290. return
  291. }
  292. func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, startFileName string, inclusive bool, limit int64, prefix string, eachEntryFunc ListEachEntryFunc) (expiredCount int64, lastFileName string, err error) {
  293. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  294. select {
  295. case <-ctx.Done():
  296. return false
  297. default:
  298. if entry.TtlSec > 0 {
  299. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  300. f.Store.DeleteOneEntry(ctx, entry)
  301. expiredCount++
  302. return true
  303. }
  304. }
  305. return eachEntryFunc(entry)
  306. }
  307. })
  308. if err != nil {
  309. return expiredCount, lastFileName, err
  310. }
  311. return
  312. }
  313. func (f *Filer) Shutdown() {
  314. f.LocalMetaLogBuffer.ShutdownLogBuffer()
  315. f.Store.Shutdown()
  316. }