filer.go 8.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "os"
  6. "strings"
  7. "time"
  8. "google.golang.org/grpc"
  9. "github.com/chrislusf/seaweedfs/weed/glog"
  10. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  11. "github.com/chrislusf/seaweedfs/weed/util"
  12. "github.com/chrislusf/seaweedfs/weed/util/log_buffer"
  13. "github.com/chrislusf/seaweedfs/weed/wdclient"
  14. )
  15. const (
  16. LogFlushInterval = time.Minute
  17. PaginationSize = 1024
  18. FilerStoreId = "filer.store.id"
  19. )
  20. var (
  21. OS_UID = uint32(os.Getuid())
  22. OS_GID = uint32(os.Getgid())
  23. )
  24. type Filer struct {
  25. Store VirtualFilerStore
  26. MasterClient *wdclient.MasterClient
  27. fileIdDeletionQueue *util.UnboundedQueue
  28. GrpcDialOption grpc.DialOption
  29. DirBucketsPath string
  30. FsyncBuckets []string
  31. buckets *FilerBuckets
  32. Cipher bool
  33. LocalMetaLogBuffer *log_buffer.LogBuffer
  34. metaLogCollection string
  35. metaLogReplication string
  36. MetaAggregator *MetaAggregator
  37. Signature int32
  38. FilerConf *FilerConf
  39. RemoteStorage *FilerRemoteStorage
  40. }
  41. func NewFiler(masters []string, grpcDialOption grpc.DialOption,
  42. filerHost string, filerGrpcPort uint32, collection string, replication string, dataCenter string, notifyFn func()) *Filer {
  43. f := &Filer{
  44. MasterClient: wdclient.NewMasterClient(grpcDialOption, "filer", filerHost, filerGrpcPort, dataCenter, masters),
  45. fileIdDeletionQueue: util.NewUnboundedQueue(),
  46. GrpcDialOption: grpcDialOption,
  47. FilerConf: NewFilerConf(),
  48. RemoteStorage: NewFilerRemoteStorage(),
  49. }
  50. f.LocalMetaLogBuffer = log_buffer.NewLogBuffer("local", LogFlushInterval, f.logFlushFunc, notifyFn)
  51. f.metaLogCollection = collection
  52. f.metaLogReplication = replication
  53. go f.loopProcessingDeletion()
  54. return f
  55. }
  56. func (f *Filer) AggregateFromPeers(self string, filers []string) {
  57. // set peers
  58. found := false
  59. for _, peer := range filers {
  60. if peer == self {
  61. found = true
  62. }
  63. }
  64. if !found {
  65. filers = append(filers, self)
  66. }
  67. f.MetaAggregator = NewMetaAggregator(filers, f.GrpcDialOption)
  68. f.MetaAggregator.StartLoopSubscribe(f, self)
  69. }
  70. func (f *Filer) SetStore(store FilerStore) {
  71. f.Store = NewFilerStoreWrapper(store)
  72. f.setOrLoadFilerStoreSignature(store)
  73. }
  74. func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) {
  75. storeIdBytes, err := store.KvGet(context.Background(), []byte(FilerStoreId))
  76. if err == ErrKvNotFound || err == nil && len(storeIdBytes) == 0 {
  77. f.Signature = util.RandomInt32()
  78. storeIdBytes = make([]byte, 4)
  79. util.Uint32toBytes(storeIdBytes, uint32(f.Signature))
  80. if err = store.KvPut(context.Background(), []byte(FilerStoreId), storeIdBytes); err != nil {
  81. glog.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  82. }
  83. glog.V(0).Infof("create %s to %d", FilerStoreId, f.Signature)
  84. } else if err == nil && len(storeIdBytes) == 4 {
  85. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  86. glog.V(0).Infof("existing %s = %d", FilerStoreId, f.Signature)
  87. } else {
  88. glog.Fatalf("read %v=%v : %v", FilerStoreId, string(storeIdBytes), err)
  89. }
  90. }
  91. func (f *Filer) GetStore() (store FilerStore) {
  92. return f.Store
  93. }
  94. func (fs *Filer) GetMaster() string {
  95. return fs.MasterClient.GetMaster()
  96. }
  97. func (fs *Filer) KeepConnectedToMaster() {
  98. fs.MasterClient.KeepConnectedToMaster()
  99. }
  100. func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) {
  101. return f.Store.BeginTransaction(ctx)
  102. }
  103. func (f *Filer) CommitTransaction(ctx context.Context) error {
  104. return f.Store.CommitTransaction(ctx)
  105. }
  106. func (f *Filer) RollbackTransaction(ctx context.Context) error {
  107. return f.Store.RollbackTransaction(ctx)
  108. }
  109. func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32) error {
  110. if string(entry.FullPath) == "/" {
  111. return nil
  112. }
  113. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  114. /*
  115. if !hasWritePermission(lastDirectoryEntry, entry) {
  116. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  117. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  118. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  119. }
  120. */
  121. if oldEntry == nil {
  122. dirParts := strings.Split(string(entry.FullPath), "/")
  123. if err := f.ensureParentDirecotryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  124. return err
  125. }
  126. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  127. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  128. glog.Errorf("insert entry %s: %v", entry.FullPath, err)
  129. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  130. }
  131. } else {
  132. if o_excl {
  133. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  134. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  135. }
  136. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  137. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  138. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  139. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  140. }
  141. }
  142. f.maybeAddBucket(entry)
  143. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  144. f.deleteChunksIfNotNew(oldEntry, entry)
  145. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  146. return nil
  147. }
  148. func (f *Filer) ensureParentDirecotryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  149. if level == 0 {
  150. return nil
  151. }
  152. dirPath := "/" + util.Join(dirParts[:level]...)
  153. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  154. // check the store directly
  155. glog.V(4).Infof("find uncached directory: %s", dirPath)
  156. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  157. // no such existing directory
  158. if dirEntry == nil {
  159. // ensure parent directory
  160. if err = f.ensureParentDirecotryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  161. return err
  162. }
  163. // create the directory
  164. now := time.Now()
  165. dirEntry = &Entry{
  166. FullPath: util.FullPath(dirPath),
  167. Attr: Attr{
  168. Mtime: now,
  169. Crtime: now,
  170. Mode: os.ModeDir | entry.Mode | 0111,
  171. Uid: entry.Uid,
  172. Gid: entry.Gid,
  173. Collection: entry.Collection,
  174. Replication: entry.Replication,
  175. UserName: entry.UserName,
  176. GroupNames: entry.GroupNames,
  177. },
  178. }
  179. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  180. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  181. if mkdirErr != nil {
  182. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  183. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  184. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  185. }
  186. } else {
  187. f.maybeAddBucket(dirEntry)
  188. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  189. }
  190. } else if !dirEntry.IsDirectory() {
  191. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  192. return fmt.Errorf("%s is a file", dirPath)
  193. }
  194. return nil
  195. }
  196. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  197. if oldEntry != nil {
  198. entry.Attr.Crtime = oldEntry.Attr.Crtime
  199. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  200. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  201. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  202. }
  203. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  204. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  205. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  206. }
  207. }
  208. return f.Store.UpdateEntry(ctx, entry)
  209. }
  210. var (
  211. Root = &Entry{
  212. FullPath: "/",
  213. Attr: Attr{
  214. Mtime: time.Now(),
  215. Crtime: time.Now(),
  216. Mode: os.ModeDir | 0755,
  217. Uid: OS_UID,
  218. Gid: OS_GID,
  219. },
  220. }
  221. )
  222. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  223. if string(p) == "/" {
  224. return Root, nil
  225. }
  226. entry, err = f.Store.FindEntry(ctx, p)
  227. if entry != nil && entry.TtlSec > 0 {
  228. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  229. f.Store.DeleteOneEntry(ctx, entry)
  230. return nil, filer_pb.ErrNotFound
  231. }
  232. }
  233. return
  234. }
  235. 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) {
  236. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  237. if entry.TtlSec > 0 {
  238. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  239. f.Store.DeleteOneEntry(ctx, entry)
  240. expiredCount++
  241. return true
  242. }
  243. }
  244. return eachEntryFunc(entry)
  245. })
  246. if err != nil {
  247. return expiredCount, lastFileName, err
  248. }
  249. return
  250. }
  251. func (f *Filer) Shutdown() {
  252. f.LocalMetaLogBuffer.Shutdown()
  253. f.Store.Shutdown()
  254. }