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.

324 lines
9.3 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
5 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. glog.V(4).Infof("CreateEntry %s: old entry: %v exclusive:%v", entry.FullPath, oldEntry, o_excl)
  169. if oldEntry == nil {
  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. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  180. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  181. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  182. }
  183. }
  184. f.maybeAddBucket(entry)
  185. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  186. f.deleteChunksIfNotNew(oldEntry, entry)
  187. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  188. return nil
  189. }
  190. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  191. if oldEntry != nil {
  192. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  193. glog.Errorf("existing %s is a directory", entry.FullPath)
  194. return fmt.Errorf("existing %s is a directory", entry.FullPath)
  195. }
  196. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  197. glog.Errorf("existing %s is a file", entry.FullPath)
  198. return fmt.Errorf("existing %s is a file", entry.FullPath)
  199. }
  200. }
  201. return f.Store.UpdateEntry(ctx, entry)
  202. }
  203. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  204. now := time.Now()
  205. if string(p) == "/" {
  206. return &Entry{
  207. FullPath: p,
  208. Attr: Attr{
  209. Mtime: now,
  210. Crtime: now,
  211. Mode: os.ModeDir | 0755,
  212. Uid: OS_UID,
  213. Gid: OS_GID,
  214. },
  215. }, nil
  216. }
  217. entry, err = f.Store.FindEntry(ctx, p)
  218. if entry != nil && entry.TtlSec > 0 {
  219. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  220. f.Store.DeleteEntry(ctx, p.Child(entry.Name()))
  221. return nil, filer_pb.ErrNotFound
  222. }
  223. }
  224. return
  225. }
  226. func (f *Filer) ListDirectoryEntries(ctx context.Context, p util.FullPath, startFileName string, inclusive bool, limit int, prefix string) ([]*Entry, error) {
  227. if strings.HasSuffix(string(p), "/") && len(p) > 1 {
  228. p = p[0 : len(p)-1]
  229. }
  230. var makeupEntries []*Entry
  231. entries, expiredCount, lastFileName, err := f.doListDirectoryEntries(ctx, p, startFileName, inclusive, limit, prefix)
  232. for expiredCount > 0 && err == nil {
  233. makeupEntries, expiredCount, lastFileName, err = f.doListDirectoryEntries(ctx, p, lastFileName, false, expiredCount, prefix)
  234. if err == nil {
  235. entries = append(entries, makeupEntries...)
  236. }
  237. }
  238. return entries, err
  239. }
  240. 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) {
  241. listedEntries, listErr := f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix)
  242. if listErr != nil {
  243. return listedEntries, expiredCount, "", listErr
  244. }
  245. for _, entry := range listedEntries {
  246. lastFileName = entry.Name()
  247. if entry.TtlSec > 0 {
  248. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  249. f.Store.DeleteEntry(ctx, p.Child(entry.Name()))
  250. expiredCount++
  251. continue
  252. }
  253. }
  254. entries = append(entries, entry)
  255. }
  256. return
  257. }
  258. func (f *Filer) Shutdown() {
  259. f.LocalMetaLogBuffer.Shutdown()
  260. f.Store.Shutdown()
  261. }
  262. func (f *Filer) maybeDeleteHardLinks(hardLinkIds []HardLinkId) {
  263. for _, hardLinkId := range hardLinkIds {
  264. if err := f.Store.DeleteHardLink(context.Background(), hardLinkId); err != nil {
  265. glog.Errorf("delete hard link id %d : %v", hardLinkId, err)
  266. }
  267. }
  268. }