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.

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