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.

334 lines
9.8 KiB

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