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.

370 lines
11 KiB

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