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.

335 lines
9.9 KiB

7 years ago
6 years ago
7 years ago
3 years ago
7 years ago
6 years ago
6 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
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, filerHost pb.ServerAddress,
  46. filerGroup string, collection string, replication string, dataCenter string, notifyFn func()) *Filer {
  47. f := &Filer{
  48. MasterClient: wdclient.NewMasterClient(grpcDialOption, filerGroup, 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. FilerGroup: f.MasterClient.FilerGroup,
  73. })
  74. glog.V(0).Infof("the cluster has %d filers\n", len(resp.ClusterNodes))
  75. for _, node := range resp.ClusterNodes {
  76. existingNodes = append(existingNodes, &master_pb.ClusterNodeUpdate{
  77. NodeType: cluster.FilerType,
  78. Address: node.Address,
  79. IsLeader: node.IsLeader,
  80. IsAdd: true,
  81. })
  82. }
  83. return err
  84. }); grpcErr != nil {
  85. glog.V(0).Infof("connect to %s: %v", f.MasterClient.GetMaster(), grpcErr)
  86. }
  87. return
  88. }
  89. func (f *Filer) SetStore(store FilerStore) {
  90. f.Store = NewFilerStoreWrapper(store)
  91. f.setOrLoadFilerStoreSignature(store)
  92. }
  93. func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) {
  94. storeIdBytes, err := store.KvGet(context.Background(), []byte(FilerStoreId))
  95. if err == ErrKvNotFound || err == nil && len(storeIdBytes) == 0 {
  96. f.Signature = util.RandomInt32()
  97. storeIdBytes = make([]byte, 4)
  98. util.Uint32toBytes(storeIdBytes, uint32(f.Signature))
  99. if err = store.KvPut(context.Background(), []byte(FilerStoreId), storeIdBytes); err != nil {
  100. glog.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  101. }
  102. glog.V(0).Infof("create %s to %d", FilerStoreId, f.Signature)
  103. } else if err == nil && len(storeIdBytes) == 4 {
  104. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  105. glog.V(0).Infof("existing %s = %d", FilerStoreId, f.Signature)
  106. } else {
  107. glog.Fatalf("read %v=%v : %v", FilerStoreId, string(storeIdBytes), err)
  108. }
  109. }
  110. func (f *Filer) GetStore() (store FilerStore) {
  111. return f.Store
  112. }
  113. func (fs *Filer) GetMaster() pb.ServerAddress {
  114. return fs.MasterClient.GetMaster()
  115. }
  116. func (fs *Filer) KeepMasterClientConnected() {
  117. fs.MasterClient.KeepConnectedToMaster()
  118. }
  119. func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) {
  120. return f.Store.BeginTransaction(ctx)
  121. }
  122. func (f *Filer) CommitTransaction(ctx context.Context) error {
  123. return f.Store.CommitTransaction(ctx)
  124. }
  125. func (f *Filer) RollbackTransaction(ctx context.Context) error {
  126. return f.Store.RollbackTransaction(ctx)
  127. }
  128. func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32, skipCreateParentDir bool) error {
  129. if string(entry.FullPath) == "/" {
  130. return nil
  131. }
  132. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  133. /*
  134. if !hasWritePermission(lastDirectoryEntry, entry) {
  135. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  136. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  137. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  138. }
  139. */
  140. if oldEntry == nil {
  141. if !skipCreateParentDir {
  142. dirParts := strings.Split(string(entry.FullPath), "/")
  143. if err := f.ensureParentDirecotryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  144. return err
  145. }
  146. }
  147. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  148. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  149. glog.Errorf("insert entry %s: %v", entry.FullPath, err)
  150. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  151. }
  152. } else {
  153. if o_excl {
  154. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  155. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  156. }
  157. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  158. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  159. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  160. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  161. }
  162. }
  163. f.maybeAddBucket(entry)
  164. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  165. f.deleteChunksIfNotNew(oldEntry, entry)
  166. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  167. return nil
  168. }
  169. func (f *Filer) ensureParentDirecotryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  170. if level == 0 {
  171. return nil
  172. }
  173. dirPath := "/" + util.Join(dirParts[:level]...)
  174. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  175. // check the store directly
  176. glog.V(4).Infof("find uncached directory: %s", dirPath)
  177. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  178. // no such existing directory
  179. if dirEntry == nil {
  180. // ensure parent directory
  181. if err = f.ensureParentDirecotryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  182. return err
  183. }
  184. // create the directory
  185. now := time.Now()
  186. dirEntry = &Entry{
  187. FullPath: util.FullPath(dirPath),
  188. Attr: Attr{
  189. Mtime: now,
  190. Crtime: now,
  191. Mode: os.ModeDir | entry.Mode | 0111,
  192. Uid: entry.Uid,
  193. Gid: entry.Gid,
  194. Collection: entry.Collection,
  195. Replication: entry.Replication,
  196. UserName: entry.UserName,
  197. GroupNames: entry.GroupNames,
  198. },
  199. }
  200. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  201. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  202. if mkdirErr != nil {
  203. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  204. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  205. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  206. }
  207. } else {
  208. f.maybeAddBucket(dirEntry)
  209. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  210. }
  211. } else if !dirEntry.IsDirectory() {
  212. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  213. return fmt.Errorf("%s is a file", dirPath)
  214. }
  215. return nil
  216. }
  217. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  218. if oldEntry != nil {
  219. entry.Attr.Crtime = oldEntry.Attr.Crtime
  220. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  221. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  222. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  223. }
  224. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  225. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  226. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  227. }
  228. }
  229. return f.Store.UpdateEntry(ctx, entry)
  230. }
  231. var (
  232. Root = &Entry{
  233. FullPath: "/",
  234. Attr: Attr{
  235. Mtime: time.Now(),
  236. Crtime: time.Now(),
  237. Mode: os.ModeDir | 0755,
  238. Uid: OS_UID,
  239. Gid: OS_GID,
  240. },
  241. }
  242. )
  243. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  244. if string(p) == "/" {
  245. return Root, nil
  246. }
  247. entry, err = f.Store.FindEntry(ctx, p)
  248. if entry != nil && entry.TtlSec > 0 {
  249. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  250. f.Store.DeleteOneEntry(ctx, entry)
  251. return nil, filer_pb.ErrNotFound
  252. }
  253. }
  254. return
  255. }
  256. 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) {
  257. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  258. select {
  259. case <-ctx.Done():
  260. return false
  261. default:
  262. if entry.TtlSec > 0 {
  263. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  264. f.Store.DeleteOneEntry(ctx, entry)
  265. expiredCount++
  266. return true
  267. }
  268. }
  269. return eachEntryFunc(entry)
  270. }
  271. })
  272. if err != nil {
  273. return expiredCount, lastFileName, err
  274. }
  275. return
  276. }
  277. func (f *Filer) Shutdown() {
  278. f.LocalMetaLogBuffer.Shutdown()
  279. f.Store.Shutdown()
  280. }