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.

376 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
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. Dlm *lock_manager.DistributedLockManager
  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. Dlm: lock_manager.NewDistributedLockManager(filerHost),
  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: 0,
  89. StopTsNs: snapshotTime.UnixNano(),
  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. var snapshot []pb.ServerAddress
  99. for _, node := range existingNodes {
  100. address := pb.ServerAddress(node.Address)
  101. snapshot = append(snapshot, address)
  102. }
  103. f.Dlm.LockRing.SetSnapshot(snapshot)
  104. glog.V(0).Infof("%s aggregate from peers %+v", self, snapshot)
  105. f.MetaAggregator = NewMetaAggregator(f, self, f.GrpcDialOption)
  106. f.MasterClient.SetOnPeerUpdateFn(func(update *master_pb.ClusterNodeUpdate, startFrom time.Time) {
  107. if update.NodeType != cluster.FilerType {
  108. return
  109. }
  110. address := pb.ServerAddress(update.Address)
  111. if update.IsAdd {
  112. f.Dlm.LockRing.AddServer(address)
  113. } else {
  114. f.Dlm.LockRing.RemoveServer(address)
  115. }
  116. f.MetaAggregator.OnPeerUpdate(update, startFrom)
  117. })
  118. for _, peerUpdate := range existingNodes {
  119. f.MetaAggregator.OnPeerUpdate(peerUpdate, startFrom)
  120. }
  121. }
  122. func (f *Filer) ListExistingPeerUpdates() (existingNodes []*master_pb.ClusterNodeUpdate) {
  123. return cluster.ListExistingPeerUpdates(f.GetMaster(), f.GrpcDialOption, f.MasterClient.FilerGroup, cluster.FilerType)
  124. }
  125. func (f *Filer) SetStore(store FilerStore) (isFresh bool) {
  126. f.Store = NewFilerStoreWrapper(store)
  127. return f.setOrLoadFilerStoreSignature(store)
  128. }
  129. func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) (isFresh bool) {
  130. storeIdBytes, err := store.KvGet(context.Background(), []byte(FilerStoreId))
  131. if err == ErrKvNotFound || err == nil && len(storeIdBytes) == 0 {
  132. f.Signature = util.RandomInt32()
  133. storeIdBytes = make([]byte, 4)
  134. util.Uint32toBytes(storeIdBytes, uint32(f.Signature))
  135. if err = store.KvPut(context.Background(), []byte(FilerStoreId), storeIdBytes); err != nil {
  136. glog.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  137. }
  138. glog.V(0).Infof("create %s to %d", FilerStoreId, f.Signature)
  139. return true
  140. } else if err == nil && len(storeIdBytes) == 4 {
  141. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  142. glog.V(0).Infof("existing %s = %d", FilerStoreId, f.Signature)
  143. } else {
  144. glog.Fatalf("read %v=%v : %v", FilerStoreId, string(storeIdBytes), err)
  145. }
  146. return false
  147. }
  148. func (f *Filer) GetStore() (store FilerStore) {
  149. return f.Store
  150. }
  151. func (fs *Filer) GetMaster() pb.ServerAddress {
  152. return fs.MasterClient.GetMaster()
  153. }
  154. func (fs *Filer) KeepMasterClientConnected() {
  155. fs.MasterClient.KeepConnectedToMaster()
  156. }
  157. func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) {
  158. return f.Store.BeginTransaction(ctx)
  159. }
  160. func (f *Filer) CommitTransaction(ctx context.Context) error {
  161. return f.Store.CommitTransaction(ctx)
  162. }
  163. func (f *Filer) RollbackTransaction(ctx context.Context) error {
  164. return f.Store.RollbackTransaction(ctx)
  165. }
  166. func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32, skipCreateParentDir bool) error {
  167. if string(entry.FullPath) == "/" {
  168. return nil
  169. }
  170. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  171. /*
  172. if !hasWritePermission(lastDirectoryEntry, entry) {
  173. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  174. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  175. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  176. }
  177. */
  178. if oldEntry == nil {
  179. if !skipCreateParentDir {
  180. dirParts := strings.Split(string(entry.FullPath), "/")
  181. if err := f.ensureParentDirectoryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  182. return err
  183. }
  184. }
  185. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  186. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  187. glog.Errorf("insert entry %s: %v", entry.FullPath, err)
  188. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  189. }
  190. } else {
  191. if o_excl {
  192. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  193. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  194. }
  195. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  196. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  197. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  198. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  199. }
  200. }
  201. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  202. f.deleteChunksIfNotNew(oldEntry, entry)
  203. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  204. return nil
  205. }
  206. func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  207. if level == 0 {
  208. return nil
  209. }
  210. dirPath := "/" + util.Join(dirParts[:level]...)
  211. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  212. // check the store directly
  213. glog.V(4).Infof("find uncached directory: %s", dirPath)
  214. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  215. // no such existing directory
  216. if dirEntry == nil {
  217. // ensure parent directory
  218. if err = f.ensureParentDirectoryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  219. return err
  220. }
  221. // create the directory
  222. now := time.Now()
  223. dirEntry = &Entry{
  224. FullPath: util.FullPath(dirPath),
  225. Attr: Attr{
  226. Mtime: now,
  227. Crtime: now,
  228. Mode: os.ModeDir | entry.Mode | 0111,
  229. Uid: entry.Uid,
  230. Gid: entry.Gid,
  231. UserName: entry.UserName,
  232. GroupNames: entry.GroupNames,
  233. },
  234. }
  235. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  236. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  237. if mkdirErr != nil {
  238. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  239. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  240. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  241. }
  242. } else {
  243. if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
  244. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  245. }
  246. }
  247. } else if !dirEntry.IsDirectory() {
  248. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  249. return fmt.Errorf("%s is a file", dirPath)
  250. }
  251. return nil
  252. }
  253. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  254. if oldEntry != nil {
  255. entry.Attr.Crtime = oldEntry.Attr.Crtime
  256. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  257. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  258. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  259. }
  260. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  261. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  262. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  263. }
  264. }
  265. return f.Store.UpdateEntry(ctx, entry)
  266. }
  267. var (
  268. Root = &Entry{
  269. FullPath: "/",
  270. Attr: Attr{
  271. Mtime: time.Now(),
  272. Crtime: time.Now(),
  273. Mode: os.ModeDir | 0755,
  274. Uid: OS_UID,
  275. Gid: OS_GID,
  276. },
  277. }
  278. )
  279. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  280. if string(p) == "/" {
  281. return Root, nil
  282. }
  283. entry, err = f.Store.FindEntry(ctx, p)
  284. if entry != nil && entry.TtlSec > 0 {
  285. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  286. f.Store.DeleteOneEntry(ctx, entry)
  287. return nil, filer_pb.ErrNotFound
  288. }
  289. }
  290. return
  291. }
  292. 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) {
  293. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  294. select {
  295. case <-ctx.Done():
  296. return false
  297. default:
  298. if entry.TtlSec > 0 {
  299. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  300. f.Store.DeleteOneEntry(ctx, entry)
  301. expiredCount++
  302. return true
  303. }
  304. }
  305. return eachEntryFunc(entry)
  306. }
  307. })
  308. if err != nil {
  309. return expiredCount, lastFileName, err
  310. }
  311. return
  312. }
  313. func (f *Filer) Shutdown() {
  314. f.LocalMetaLogBuffer.Shutdown()
  315. f.Store.Shutdown()
  316. }