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.

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