filer.go 8.6 KB

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