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.

358 lines
11 KiB

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