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.

368 lines
11 KiB

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