filer.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "sort"
  7. "strings"
  8. "time"
  9. "github.com/seaweedfs/seaweedfs/weed/s3api/s3bucket"
  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. if entry.IsDirectory() {
  164. entry.Attr.TtlSec = 0
  165. }
  166. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  167. /*
  168. if !hasWritePermission(lastDirectoryEntry, entry) {
  169. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  170. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  171. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  172. }
  173. */
  174. if oldEntry == nil {
  175. if !skipCreateParentDir {
  176. dirParts := strings.Split(string(entry.FullPath), "/")
  177. if err := f.ensureParentDirectoryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  178. return err
  179. }
  180. }
  181. glog.V(4).InfofCtx(ctx, "InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  182. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  183. glog.ErrorfCtx(ctx, "insert entry %s: %v", entry.FullPath, err)
  184. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  185. }
  186. } else {
  187. if o_excl {
  188. glog.V(3).InfofCtx(ctx, "EEXIST: entry %s already exists", entry.FullPath)
  189. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  190. }
  191. glog.V(4).InfofCtx(ctx, "UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  192. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  193. glog.ErrorfCtx(ctx, "update entry %s: %v", entry.FullPath, err)
  194. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  195. }
  196. }
  197. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  198. f.deleteChunksIfNotNew(ctx, oldEntry, entry)
  199. glog.V(4).InfofCtx(ctx, "CreateEntry %s: created", entry.FullPath)
  200. return nil
  201. }
  202. func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  203. if level == 0 {
  204. return nil
  205. }
  206. dirPath := "/" + util.Join(dirParts[:level]...)
  207. // fmt.Printf("%d dirPath: %+v\n", level, dirPath)
  208. // check the store directly
  209. glog.V(4).InfofCtx(ctx, "find uncached directory: %s", dirPath)
  210. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  211. // no such existing directory
  212. if dirEntry == nil {
  213. // fmt.Printf("dirParts: %v %v %v\n", dirParts[0], dirParts[1], dirParts[2])
  214. // dirParts[0] == "" and dirParts[1] == "buckets"
  215. if len(dirParts) >= 3 && dirParts[1] == "buckets" {
  216. if err := s3bucket.VerifyS3BucketName(dirParts[2]); err != nil {
  217. return fmt.Errorf("invalid bucket name %s: %v", dirParts[2], err)
  218. }
  219. }
  220. // ensure parent directory
  221. if err = f.ensureParentDirectoryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  222. return err
  223. }
  224. // create the directory
  225. now := time.Now()
  226. dirEntry = &Entry{
  227. FullPath: util.FullPath(dirPath),
  228. Attr: Attr{
  229. Mtime: now,
  230. Crtime: now,
  231. Mode: os.ModeDir | entry.Mode | 0111,
  232. Uid: entry.Uid,
  233. Gid: entry.Gid,
  234. UserName: entry.UserName,
  235. GroupNames: entry.GroupNames,
  236. },
  237. }
  238. glog.V(2).InfofCtx(ctx, "create directory: %s %v", dirPath, dirEntry.Mode)
  239. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  240. if mkdirErr != nil {
  241. if fEntry, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound || fEntry == nil {
  242. glog.V(3).InfofCtx(ctx, "mkdir %s: %v", dirPath, mkdirErr)
  243. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  244. }
  245. } else {
  246. if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
  247. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  248. }
  249. }
  250. } else if !dirEntry.IsDirectory() {
  251. glog.ErrorfCtx(ctx, "CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  252. return fmt.Errorf("%s is a file", dirPath)
  253. }
  254. return nil
  255. }
  256. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  257. if oldEntry != nil {
  258. entry.Attr.Crtime = oldEntry.Attr.Crtime
  259. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  260. glog.ErrorfCtx(ctx, "existing %s is a directory", oldEntry.FullPath)
  261. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  262. }
  263. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  264. glog.ErrorfCtx(ctx, "existing %s is a file", oldEntry.FullPath)
  265. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  266. }
  267. }
  268. return f.Store.UpdateEntry(ctx, entry)
  269. }
  270. var (
  271. Root = &Entry{
  272. FullPath: "/",
  273. Attr: Attr{
  274. Mtime: time.Now(),
  275. Crtime: time.Now(),
  276. Mode: os.ModeDir | 0755,
  277. Uid: OS_UID,
  278. Gid: OS_GID,
  279. },
  280. }
  281. )
  282. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  283. if string(p) == "/" {
  284. return Root, nil
  285. }
  286. entry, err = f.Store.FindEntry(ctx, p)
  287. if entry != nil && entry.TtlSec > 0 {
  288. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  289. f.Store.DeleteOneEntry(ctx, entry)
  290. return nil, filer_pb.ErrNotFound
  291. }
  292. }
  293. return
  294. }
  295. 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) {
  296. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  297. select {
  298. case <-ctx.Done():
  299. return false
  300. default:
  301. if entry.TtlSec > 0 {
  302. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  303. f.Store.DeleteOneEntry(ctx, entry)
  304. expiredCount++
  305. return true
  306. }
  307. }
  308. return eachEntryFunc(entry)
  309. }
  310. })
  311. if err != nil {
  312. return expiredCount, lastFileName, err
  313. }
  314. return
  315. }
  316. func (f *Filer) Shutdown() {
  317. f.LocalMetaLogBuffer.ShutdownLogBuffer()
  318. f.Store.Shutdown()
  319. }