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.

326 lines
9.6 KiB

7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
4 years ago
7 years ago
5 years ago
5 years ago
7 years ago
7 years ago
4 years ago
7 years ago
5 years ago
5 years ago
4 years ago
5 years ago
5 years ago
7 years ago
7 years ago
7 years ago
6 years ago
5 years ago
6 years ago
5 years ago
7 years ago
4 years ago
4 years ago
7 years ago
4 years ago
4 years ago
4 years ago
7 years ago
7 years ago
5 years ago
  1. package filer
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/chrislusf/seaweedfs/weed/pb"
  6. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  7. "os"
  8. "strings"
  9. "time"
  10. "google.golang.org/grpc"
  11. "github.com/chrislusf/seaweedfs/weed/glog"
  12. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  13. "github.com/chrislusf/seaweedfs/weed/util"
  14. "github.com/chrislusf/seaweedfs/weed/util/log_buffer"
  15. "github.com/chrislusf/seaweedfs/weed/wdclient"
  16. )
  17. const (
  18. LogFlushInterval = time.Minute
  19. PaginationSize = 1024
  20. FilerStoreId = "filer.store.id"
  21. )
  22. var (
  23. OS_UID = uint32(os.Getuid())
  24. OS_GID = uint32(os.Getgid())
  25. )
  26. type Filer struct {
  27. Store VirtualFilerStore
  28. MasterClient *wdclient.MasterClient
  29. fileIdDeletionQueue *util.UnboundedQueue
  30. GrpcDialOption grpc.DialOption
  31. DirBucketsPath string
  32. FsyncBuckets []string
  33. buckets *FilerBuckets
  34. Cipher bool
  35. LocalMetaLogBuffer *log_buffer.LogBuffer
  36. metaLogCollection string
  37. metaLogReplication string
  38. MetaAggregator *MetaAggregator
  39. Signature int32
  40. FilerConf *FilerConf
  41. RemoteStorage *FilerRemoteStorage
  42. UniqueFileId uint32
  43. }
  44. func NewFiler(masters []pb.ServerAddress, grpcDialOption grpc.DialOption,
  45. filerHost pb.ServerAddress, collection string, replication string, dataCenter string, notifyFn func()) *Filer {
  46. f := &Filer{
  47. MasterClient: wdclient.NewMasterClient(grpcDialOption, "filer", filerHost, dataCenter, masters),
  48. fileIdDeletionQueue: util.NewUnboundedQueue(),
  49. GrpcDialOption: grpcDialOption,
  50. FilerConf: NewFilerConf(),
  51. RemoteStorage: NewFilerRemoteStorage(),
  52. UniqueFileId: uint32(util.RandomInt32()),
  53. }
  54. f.LocalMetaLogBuffer = log_buffer.NewLogBuffer("local", LogFlushInterval, f.logFlushFunc, notifyFn)
  55. f.metaLogCollection = collection
  56. f.metaLogReplication = replication
  57. go f.loopProcessingDeletion()
  58. return f
  59. }
  60. func (f *Filer) AggregateFromPeers(self pb.ServerAddress) {
  61. f.MetaAggregator = NewMetaAggregator(f, self, f.GrpcDialOption)
  62. f.MasterClient.OnPeerUpdate = f.MetaAggregator.OnPeerUpdate
  63. for _, peerUpdate := range f.ListExistingPeerUpdates() {
  64. f.MetaAggregator.OnPeerUpdate(peerUpdate)
  65. }
  66. }
  67. func (f *Filer) ListExistingPeerUpdates() (existingNodes []*master_pb.ClusterNodeUpdate){
  68. if grpcErr := pb.WithMasterClient(f.MasterClient.GetMaster(), f.GrpcDialOption, func(client master_pb.SeaweedClient) error {
  69. resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
  70. ClientType: "filer",
  71. })
  72. glog.V(0).Infof("the cluster has %d filers\n", len(resp.ClusterNodes))
  73. for _, node := range resp.ClusterNodes {
  74. existingNodes = append(existingNodes, &master_pb.ClusterNodeUpdate{
  75. NodeType: "filer",
  76. Address: node.Address,
  77. IsLeader: node.IsLeader,
  78. IsAdd: true,
  79. })
  80. }
  81. return err
  82. }); grpcErr != nil {
  83. glog.V(0).Infof("connect to %s: %v", f.MasterClient.GetMaster(), grpcErr)
  84. }
  85. return
  86. }
  87. func (f *Filer) SetStore(store FilerStore) {
  88. f.Store = NewFilerStoreWrapper(store)
  89. f.setOrLoadFilerStoreSignature(store)
  90. }
  91. func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) {
  92. storeIdBytes, err := store.KvGet(context.Background(), []byte(FilerStoreId))
  93. if err == ErrKvNotFound || err == nil && len(storeIdBytes) == 0 {
  94. f.Signature = util.RandomInt32()
  95. storeIdBytes = make([]byte, 4)
  96. util.Uint32toBytes(storeIdBytes, uint32(f.Signature))
  97. if err = store.KvPut(context.Background(), []byte(FilerStoreId), storeIdBytes); err != nil {
  98. glog.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  99. }
  100. glog.V(0).Infof("create %s to %d", FilerStoreId, f.Signature)
  101. } else if err == nil && len(storeIdBytes) == 4 {
  102. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  103. glog.V(0).Infof("existing %s = %d", FilerStoreId, f.Signature)
  104. } else {
  105. glog.Fatalf("read %v=%v : %v", FilerStoreId, string(storeIdBytes), err)
  106. }
  107. }
  108. func (f *Filer) GetStore() (store FilerStore) {
  109. return f.Store
  110. }
  111. func (fs *Filer) GetMaster() pb.ServerAddress {
  112. return fs.MasterClient.GetMaster()
  113. }
  114. func (fs *Filer) KeepMasterClientConnected() {
  115. fs.MasterClient.KeepConnectedToMaster()
  116. }
  117. func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) {
  118. return f.Store.BeginTransaction(ctx)
  119. }
  120. func (f *Filer) CommitTransaction(ctx context.Context) error {
  121. return f.Store.CommitTransaction(ctx)
  122. }
  123. func (f *Filer) RollbackTransaction(ctx context.Context) error {
  124. return f.Store.RollbackTransaction(ctx)
  125. }
  126. func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32) error {
  127. if string(entry.FullPath) == "/" {
  128. return nil
  129. }
  130. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  131. /*
  132. if !hasWritePermission(lastDirectoryEntry, entry) {
  133. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  134. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  135. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  136. }
  137. */
  138. if oldEntry == nil {
  139. dirParts := strings.Split(string(entry.FullPath), "/")
  140. if err := f.ensureParentDirecotryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  141. return err
  142. }
  143. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  144. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  145. glog.Errorf("insert entry %s: %v", entry.FullPath, err)
  146. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  147. }
  148. } else {
  149. if o_excl {
  150. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  151. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  152. }
  153. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  154. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  155. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  156. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  157. }
  158. }
  159. f.maybeAddBucket(entry)
  160. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  161. f.deleteChunksIfNotNew(oldEntry, entry)
  162. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  163. return nil
  164. }
  165. func (f *Filer) ensureParentDirecotryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  166. if level == 0 {
  167. return nil
  168. }
  169. dirPath := "/" + util.Join(dirParts[:level]...)
  170. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  171. // check the store directly
  172. glog.V(4).Infof("find uncached directory: %s", dirPath)
  173. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  174. // no such existing directory
  175. if dirEntry == nil {
  176. // ensure parent directory
  177. if err = f.ensureParentDirecotryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  178. return err
  179. }
  180. // create the directory
  181. now := time.Now()
  182. dirEntry = &Entry{
  183. FullPath: util.FullPath(dirPath),
  184. Attr: Attr{
  185. Mtime: now,
  186. Crtime: now,
  187. Mode: os.ModeDir | entry.Mode | 0111,
  188. Uid: entry.Uid,
  189. Gid: entry.Gid,
  190. Collection: entry.Collection,
  191. Replication: entry.Replication,
  192. UserName: entry.UserName,
  193. GroupNames: entry.GroupNames,
  194. },
  195. }
  196. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  197. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  198. if mkdirErr != nil {
  199. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  200. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  201. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  202. }
  203. } else {
  204. f.maybeAddBucket(dirEntry)
  205. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  206. }
  207. } else if !dirEntry.IsDirectory() {
  208. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  209. return fmt.Errorf("%s is a file", dirPath)
  210. }
  211. return nil
  212. }
  213. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  214. if oldEntry != nil {
  215. entry.Attr.Crtime = oldEntry.Attr.Crtime
  216. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  217. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  218. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  219. }
  220. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  221. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  222. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  223. }
  224. }
  225. return f.Store.UpdateEntry(ctx, entry)
  226. }
  227. var (
  228. Root = &Entry{
  229. FullPath: "/",
  230. Attr: Attr{
  231. Mtime: time.Now(),
  232. Crtime: time.Now(),
  233. Mode: os.ModeDir | 0755,
  234. Uid: OS_UID,
  235. Gid: OS_GID,
  236. },
  237. }
  238. )
  239. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  240. if string(p) == "/" {
  241. return Root, nil
  242. }
  243. entry, err = f.Store.FindEntry(ctx, p)
  244. if entry != nil && entry.TtlSec > 0 {
  245. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  246. f.Store.DeleteOneEntry(ctx, entry)
  247. return nil, filer_pb.ErrNotFound
  248. }
  249. }
  250. return
  251. }
  252. 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) {
  253. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  254. if entry.TtlSec > 0 {
  255. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  256. f.Store.DeleteOneEntry(ctx, entry)
  257. expiredCount++
  258. return true
  259. }
  260. }
  261. return eachEntryFunc(entry)
  262. })
  263. if err != nil {
  264. return expiredCount, lastFileName, err
  265. }
  266. return
  267. }
  268. func (f *Filer) Shutdown() {
  269. f.LocalMetaLogBuffer.Shutdown()
  270. f.Store.Shutdown()
  271. }