filer.go 8.6 KB

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