filer.go 11 KB

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