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.

424 lines
13 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
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
1 year 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) RenameEntry(ctx context.Context, oldEntry, newEntry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32, skipCreateParentDir bool, maxFilenameLength uint32) error {
  199. if string(newEntry.FullPath) == "/" {
  200. return nil
  201. }
  202. if newEntry.FullPath.IsLongerFileName(maxFilenameLength) {
  203. return fmt.Errorf("entry name too long")
  204. }
  205. currentEntry, _ := f.FindEntry(ctx, newEntry.FullPath)
  206. if currentEntry != nil && o_excl {
  207. glog.V(3).Infof("EEXIST: entry %s already exists", newEntry.FullPath)
  208. return fmt.Errorf("EEXIST: entry %s already exists", newEntry.FullPath)
  209. }
  210. if currentEntry == nil && !skipCreateParentDir {
  211. dirParts := strings.Split(string(newEntry.FullPath), "/")
  212. if err := f.ensureParentDirectoryEntry(ctx, newEntry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  213. return err
  214. }
  215. }
  216. glog.V(4).Infof("renameEntry %s: old entry: %v", newEntry.FullPath, oldEntry.FullPath)
  217. if err := f.renameEntry(ctx, oldEntry, newEntry, currentEntry != nil); err != nil {
  218. glog.Errorf("rename entry %s: %v", newEntry.FullPath, err)
  219. return fmt.Errorf("rename entry %s: %v", newEntry.FullPath, err)
  220. }
  221. f.NotifyUpdateEvent(ctx, oldEntry, newEntry, true, isFromOtherCluster, signatures)
  222. f.deleteChunksIfNotNew(currentEntry, newEntry)
  223. glog.V(4).Infof("RenameEntry %s: renamed", newEntry.FullPath)
  224. return nil
  225. }
  226. func (f *Filer) ensureParentDirectoryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  227. if level == 0 {
  228. return nil
  229. }
  230. dirPath := "/" + util.Join(dirParts[:level]...)
  231. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  232. // check the store directly
  233. glog.V(4).Infof("find uncached directory: %s", dirPath)
  234. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  235. // no such existing directory
  236. if dirEntry == nil {
  237. // ensure parent directory
  238. if err = f.ensureParentDirectoryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  239. return err
  240. }
  241. // create the directory
  242. now := time.Now()
  243. dirEntry = &Entry{
  244. FullPath: util.FullPath(dirPath),
  245. Attr: Attr{
  246. Mtime: now,
  247. Crtime: now,
  248. Mode: os.ModeDir | entry.Mode | 0111,
  249. Uid: entry.Uid,
  250. Gid: entry.Gid,
  251. UserName: entry.UserName,
  252. GroupNames: entry.GroupNames,
  253. },
  254. }
  255. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  256. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  257. if mkdirErr != nil {
  258. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  259. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  260. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  261. }
  262. } else {
  263. if !strings.HasPrefix("/"+util.Join(dirParts[:]...), SystemLogDir) {
  264. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  265. }
  266. }
  267. } else if !dirEntry.IsDirectory() {
  268. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  269. return fmt.Errorf("%s is a file", dirPath)
  270. }
  271. return nil
  272. }
  273. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  274. if oldEntry != nil {
  275. entry.Attr.Crtime = oldEntry.Attr.Crtime
  276. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  277. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  278. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  279. }
  280. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  281. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  282. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  283. }
  284. }
  285. return f.Store.UpdateEntry(ctx, entry)
  286. }
  287. func (f *Filer) renameEntry(ctx context.Context, oldEntry, newEntry *Entry, newEntryExists bool) error {
  288. if oldEntry.IsDirectory() && !newEntry.IsDirectory() {
  289. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  290. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  291. }
  292. if !oldEntry.IsDirectory() && newEntry.IsDirectory() {
  293. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  294. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  295. }
  296. newEntry.Attr.Crtime = oldEntry.Attr.Crtime
  297. if newEntryExists {
  298. return f.Store.UpdateEntry(ctx, newEntry)
  299. }
  300. return f.Store.InsertEntry(ctx, newEntry)
  301. }
  302. var (
  303. Root = &Entry{
  304. FullPath: "/",
  305. Attr: Attr{
  306. Mtime: time.Now(),
  307. Crtime: time.Now(),
  308. Mode: os.ModeDir | 0755,
  309. Uid: OS_UID,
  310. Gid: OS_GID,
  311. },
  312. }
  313. )
  314. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  315. if string(p) == "/" {
  316. return Root, nil
  317. }
  318. entry, err = f.Store.FindEntry(ctx, p)
  319. if entry != nil && entry.TtlSec > 0 {
  320. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  321. f.Store.DeleteOneEntry(ctx, entry)
  322. return nil, filer_pb.ErrNotFound
  323. }
  324. }
  325. return
  326. }
  327. 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) {
  328. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  329. select {
  330. case <-ctx.Done():
  331. return false
  332. default:
  333. if entry.TtlSec > 0 {
  334. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  335. f.Store.DeleteOneEntry(ctx, entry)
  336. expiredCount++
  337. return true
  338. }
  339. }
  340. return eachEntryFunc(entry)
  341. }
  342. })
  343. if err != nil {
  344. return expiredCount, lastFileName, err
  345. }
  346. return
  347. }
  348. func (f *Filer) Shutdown() {
  349. f.LocalMetaLogBuffer.ShutdownLogBuffer()
  350. f.Store.Shutdown()
  351. }