filer.go 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327
  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/util/log"
  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 * 256
  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. log.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  80. }
  81. log.Infof("create %s to %d", FilerStoreId, f.Signature)
  82. } else if err == nil && len(storeIdBytes) == 4 {
  83. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  84. log.Infof("existing %s = %d", FilerStoreId, f.Signature)
  85. } else {
  86. log.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. dirParts := strings.Split(string(entry.FullPath), "/")
  112. // fmt.Printf("directory parts: %+v\n", dirParts)
  113. var lastDirectoryEntry *Entry
  114. for i := 1; i < len(dirParts); i++ {
  115. dirPath := "/" + util.Join(dirParts[:i]...)
  116. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  117. // check the store directly
  118. log.Tracef("find uncached directory: %s", dirPath)
  119. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  120. // no such existing directory
  121. if dirEntry == nil {
  122. // create the directory
  123. now := time.Now()
  124. dirEntry = &Entry{
  125. FullPath: util.FullPath(dirPath),
  126. Attr: Attr{
  127. Mtime: now,
  128. Crtime: now,
  129. Mode: os.ModeDir | entry.Mode | 0110,
  130. Uid: entry.Uid,
  131. Gid: entry.Gid,
  132. Collection: entry.Collection,
  133. Replication: entry.Replication,
  134. UserName: entry.UserName,
  135. GroupNames: entry.GroupNames,
  136. },
  137. }
  138. log.Debugf("create directory: %s %v", dirPath, dirEntry.Mode)
  139. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  140. if mkdirErr != nil {
  141. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  142. log.Tracef("mkdir %s: %v", dirPath, mkdirErr)
  143. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  144. }
  145. } else {
  146. f.maybeAddBucket(dirEntry)
  147. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  148. }
  149. } else if !dirEntry.IsDirectory() {
  150. log.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  151. return fmt.Errorf("%s is a file", dirPath)
  152. }
  153. // remember the direct parent directory entry
  154. if i == len(dirParts)-1 {
  155. lastDirectoryEntry = dirEntry
  156. }
  157. }
  158. if lastDirectoryEntry == nil {
  159. log.Errorf("CreateEntry %s: lastDirectoryEntry is nil", entry.FullPath)
  160. return fmt.Errorf("parent folder not found: %v", entry.FullPath)
  161. }
  162. /*
  163. if !hasWritePermission(lastDirectoryEntry, entry) {
  164. log.Infof("directory %s: %v, entry: uid=%d gid=%d",
  165. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  166. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  167. }
  168. */
  169. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  170. if oldEntry == nil {
  171. log.Tracef("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  172. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  173. log.Errorf("insert entry %s: %v", entry.FullPath, err)
  174. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  175. }
  176. } else {
  177. if o_excl {
  178. log.Tracef("EEXIST: entry %s already exists", entry.FullPath)
  179. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  180. }
  181. log.Tracef("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  182. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  183. log.Errorf("update entry %s: %v", entry.FullPath, err)
  184. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  185. }
  186. }
  187. f.maybeAddBucket(entry)
  188. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  189. f.deleteChunksIfNotNew(oldEntry, entry)
  190. log.Tracef("CreateEntry %s: created", entry.FullPath)
  191. return nil
  192. }
  193. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  194. if oldEntry != nil {
  195. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  196. log.Errorf("existing %s is a directory", entry.FullPath)
  197. return fmt.Errorf("existing %s is a directory", entry.FullPath)
  198. }
  199. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  200. log.Errorf("existing %s is a file", entry.FullPath)
  201. return fmt.Errorf("existing %s is a file", entry.FullPath)
  202. }
  203. }
  204. return f.Store.UpdateEntry(ctx, entry)
  205. }
  206. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  207. now := time.Now()
  208. if string(p) == "/" {
  209. return &Entry{
  210. FullPath: p,
  211. Attr: Attr{
  212. Mtime: now,
  213. Crtime: now,
  214. Mode: os.ModeDir | 0755,
  215. Uid: OS_UID,
  216. Gid: OS_GID,
  217. },
  218. }, nil
  219. }
  220. entry, err = f.Store.FindEntry(ctx, p)
  221. if entry != nil && entry.TtlSec > 0 {
  222. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  223. f.Store.DeleteEntry(ctx, p.Child(entry.Name()))
  224. return nil, filer_pb.ErrNotFound
  225. }
  226. }
  227. return
  228. }
  229. func (f *Filer) ListDirectoryEntries(ctx context.Context, p util.FullPath, startFileName string, inclusive bool, limit int, prefix string) ([]*Entry, error) {
  230. if strings.HasSuffix(string(p), "/") && len(p) > 1 {
  231. p = p[0 : len(p)-1]
  232. }
  233. var makeupEntries []*Entry
  234. entries, expiredCount, lastFileName, err := f.doListDirectoryEntries(ctx, p, startFileName, inclusive, limit, prefix)
  235. for expiredCount > 0 && err == nil {
  236. makeupEntries, expiredCount, lastFileName, err = f.doListDirectoryEntries(ctx, p, lastFileName, false, expiredCount, prefix)
  237. if err == nil {
  238. entries = append(entries, makeupEntries...)
  239. }
  240. }
  241. return entries, err
  242. }
  243. func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, startFileName string, inclusive bool, limit int, prefix string) (entries []*Entry, expiredCount int, lastFileName string, err error) {
  244. listedEntries, listErr := f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix)
  245. if listErr != nil {
  246. return listedEntries, expiredCount, "", listErr
  247. }
  248. for _, entry := range listedEntries {
  249. lastFileName = entry.Name()
  250. if entry.TtlSec > 0 {
  251. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  252. f.Store.DeleteEntry(ctx, p.Child(entry.Name()))
  253. expiredCount++
  254. continue
  255. }
  256. }
  257. entries = append(entries, entry)
  258. }
  259. return
  260. }
  261. func (f *Filer) Shutdown() {
  262. f.LocalMetaLogBuffer.Shutdown()
  263. f.Store.Shutdown()
  264. }
  265. func (f *Filer) maybeDeleteHardLinks(hardLinkIds []HardLinkId) {
  266. for _, hardLinkId := range hardLinkIds {
  267. if err := f.Store.DeleteHardLink(context.Background(), hardLinkId); err != nil {
  268. log.Errorf("delete hard link id %d : %v", hardLinkId, err)
  269. }
  270. }
  271. }