You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

320 lines
9.2 KiB

7 years ago
6 years ago
7 years ago
7 years ago
6 years ago
6 years ago
5 years ago
7 years ago
4 years ago
4 years ago
7 years ago
5 years ago
5 years ago
7 years ago
5 years ago
7 years ago
4 years ago
7 years ago
5 years ago
4 years ago
5 years ago
4 years ago
5 years ago
5 years ago
7 years ago
7 years ago
5 years ago
4 years ago
5 years ago
5 years ago
5 years ago
5 years ago
7 years ago
5 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
7 years ago
6 years ago
6 years ago
7 years ago
5 years ago
7 years ago
7 years ago
5 years ago
  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 * 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. 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. 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. glog.V(4).Infof("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. glog.V(2).Infof("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. glog.V(3).Infof("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. glog.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. glog.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. glog.V(0).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. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  172. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  173. glog.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. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  179. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  180. }
  181. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  182. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  183. glog.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. glog.V(4).Infof("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. entry.Attr.Crtime = oldEntry.Attr.Crtime
  196. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  197. glog.Errorf("existing %s is a directory", entry.FullPath)
  198. return fmt.Errorf("existing %s is a directory", entry.FullPath)
  199. }
  200. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  201. glog.Errorf("existing %s is a file", entry.FullPath)
  202. return fmt.Errorf("existing %s is a file", entry.FullPath)
  203. }
  204. }
  205. return f.Store.UpdateEntry(ctx, entry)
  206. }
  207. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  208. now := time.Now()
  209. if string(p) == "/" {
  210. return &Entry{
  211. FullPath: p,
  212. Attr: Attr{
  213. Mtime: now,
  214. Crtime: now,
  215. Mode: os.ModeDir | 0755,
  216. Uid: OS_UID,
  217. Gid: OS_GID,
  218. },
  219. }, nil
  220. }
  221. entry, err = f.Store.FindEntry(ctx, p)
  222. if entry != nil && entry.TtlSec > 0 {
  223. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  224. f.Store.DeleteOneEntry(ctx, entry)
  225. return nil, filer_pb.ErrNotFound
  226. }
  227. }
  228. return
  229. }
  230. func (f *Filer) ListDirectoryEntries(ctx context.Context, p util.FullPath, startFileName string, inclusive bool, limit int, prefix string) ([]*Entry, error) {
  231. if strings.HasSuffix(string(p), "/") && len(p) > 1 {
  232. p = p[0 : len(p)-1]
  233. }
  234. var makeupEntries []*Entry
  235. entries, expiredCount, lastFileName, err := f.doListDirectoryEntries(ctx, p, startFileName, inclusive, limit, prefix)
  236. for expiredCount > 0 && err == nil {
  237. makeupEntries, expiredCount, lastFileName, err = f.doListDirectoryEntries(ctx, p, lastFileName, false, expiredCount, prefix)
  238. if err == nil {
  239. entries = append(entries, makeupEntries...)
  240. }
  241. }
  242. return entries, err
  243. }
  244. 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) {
  245. listedEntries, listErr := f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix)
  246. if listErr != nil {
  247. return listedEntries, expiredCount, "", listErr
  248. }
  249. for _, entry := range listedEntries {
  250. lastFileName = entry.Name()
  251. if entry.TtlSec > 0 {
  252. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  253. f.Store.DeleteOneEntry(ctx, entry)
  254. expiredCount++
  255. continue
  256. }
  257. }
  258. entries = append(entries, entry)
  259. }
  260. return
  261. }
  262. func (f *Filer) Shutdown() {
  263. f.LocalMetaLogBuffer.Shutdown()
  264. f.Store.Shutdown()
  265. }