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.

358 lines
11 KiB

7 years ago
7 years ago
7 years ago
3 years ago
7 years ago
7 years ago
7 years ago
7 years ago
5 years ago
7 years ago
4 years ago
7 years ago
5 years ago
5 years ago
7 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
3 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/chrislusf/seaweedfs/weed/cluster"
  6. "github.com/chrislusf/seaweedfs/weed/pb"
  7. "github.com/chrislusf/seaweedfs/weed/pb/master_pb"
  8. "os"
  9. "sort"
  10. "strings"
  11. "time"
  12. "google.golang.org/grpc"
  13. "github.com/chrislusf/seaweedfs/weed/glog"
  14. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  15. "github.com/chrislusf/seaweedfs/weed/util"
  16. "github.com/chrislusf/seaweedfs/weed/util/log_buffer"
  17. "github.com/chrislusf/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. Store VirtualFilerStore
  30. MasterClient *wdclient.MasterClient
  31. fileIdDeletionQueue *util.UnboundedQueue
  32. GrpcDialOption grpc.DialOption
  33. DirBucketsPath string
  34. Cipher bool
  35. LocalMetaLogBuffer *log_buffer.LogBuffer
  36. metaLogCollection string
  37. metaLogReplication string
  38. MetaAggregator *MetaAggregator
  39. Signature int32
  40. FilerConf *FilerConf
  41. RemoteStorage *FilerRemoteStorage
  42. UniqueFilerId int32
  43. UniqueFilerEpoch int32
  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.OnPeerUpdate = 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. if grpcErr := pb.WithMasterClient(false, f.MasterClient.GetMaster(), f.GrpcDialOption, func(client master_pb.SeaweedClient) error {
  92. resp, err := client.ListClusterNodes(context.Background(), &master_pb.ListClusterNodesRequest{
  93. ClientType: cluster.FilerType,
  94. FilerGroup: f.MasterClient.FilerGroup,
  95. })
  96. glog.V(0).Infof("the cluster has %d filers\n", len(resp.ClusterNodes))
  97. for _, node := range resp.ClusterNodes {
  98. existingNodes = append(existingNodes, &master_pb.ClusterNodeUpdate{
  99. NodeType: cluster.FilerType,
  100. Address: node.Address,
  101. IsLeader: node.IsLeader,
  102. IsAdd: true,
  103. CreatedAtNs: node.CreatedAtNs,
  104. })
  105. }
  106. return err
  107. }); grpcErr != nil {
  108. glog.V(0).Infof("connect to %s: %v", f.MasterClient.GetMaster(), grpcErr)
  109. }
  110. return
  111. }
  112. func (f *Filer) SetStore(store FilerStore) (isFresh bool) {
  113. f.Store = NewFilerStoreWrapper(store)
  114. return f.setOrLoadFilerStoreSignature(store)
  115. }
  116. func (f *Filer) setOrLoadFilerStoreSignature(store FilerStore) (isFresh bool) {
  117. storeIdBytes, err := store.KvGet(context.Background(), []byte(FilerStoreId))
  118. if err == ErrKvNotFound || err == nil && len(storeIdBytes) == 0 {
  119. f.Signature = util.RandomInt32()
  120. storeIdBytes = make([]byte, 4)
  121. util.Uint32toBytes(storeIdBytes, uint32(f.Signature))
  122. if err = store.KvPut(context.Background(), []byte(FilerStoreId), storeIdBytes); err != nil {
  123. glog.Fatalf("set %s=%d : %v", FilerStoreId, f.Signature, err)
  124. }
  125. glog.V(0).Infof("create %s to %d", FilerStoreId, f.Signature)
  126. return true
  127. } else if err == nil && len(storeIdBytes) == 4 {
  128. f.Signature = int32(util.BytesToUint32(storeIdBytes))
  129. glog.V(0).Infof("existing %s = %d", FilerStoreId, f.Signature)
  130. } else {
  131. glog.Fatalf("read %v=%v : %v", FilerStoreId, string(storeIdBytes), err)
  132. }
  133. return false
  134. }
  135. func (f *Filer) GetStore() (store FilerStore) {
  136. return f.Store
  137. }
  138. func (fs *Filer) GetMaster() pb.ServerAddress {
  139. return fs.MasterClient.GetMaster()
  140. }
  141. func (fs *Filer) KeepMasterClientConnected() {
  142. fs.MasterClient.KeepConnectedToMaster()
  143. }
  144. func (f *Filer) BeginTransaction(ctx context.Context) (context.Context, error) {
  145. return f.Store.BeginTransaction(ctx)
  146. }
  147. func (f *Filer) CommitTransaction(ctx context.Context) error {
  148. return f.Store.CommitTransaction(ctx)
  149. }
  150. func (f *Filer) RollbackTransaction(ctx context.Context) error {
  151. return f.Store.RollbackTransaction(ctx)
  152. }
  153. func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, o_excl bool, isFromOtherCluster bool, signatures []int32, skipCreateParentDir bool) error {
  154. if string(entry.FullPath) == "/" {
  155. return nil
  156. }
  157. oldEntry, _ := f.FindEntry(ctx, entry.FullPath)
  158. /*
  159. if !hasWritePermission(lastDirectoryEntry, entry) {
  160. glog.V(0).Infof("directory %s: %v, entry: uid=%d gid=%d",
  161. lastDirectoryEntry.FullPath, lastDirectoryEntry.Attr, entry.Uid, entry.Gid)
  162. return fmt.Errorf("no write permission in folder %v", lastDirectoryEntry.FullPath)
  163. }
  164. */
  165. if oldEntry == nil {
  166. if !skipCreateParentDir {
  167. dirParts := strings.Split(string(entry.FullPath), "/")
  168. if err := f.ensureParentDirecotryEntry(ctx, entry, dirParts, len(dirParts)-1, isFromOtherCluster); err != nil {
  169. return err
  170. }
  171. }
  172. glog.V(4).Infof("InsertEntry %s: new entry: %v", entry.FullPath, entry.Name())
  173. if err := f.Store.InsertEntry(ctx, entry); err != nil {
  174. glog.Errorf("insert entry %s: %v", entry.FullPath, err)
  175. return fmt.Errorf("insert entry %s: %v", entry.FullPath, err)
  176. }
  177. } else {
  178. if o_excl {
  179. glog.V(3).Infof("EEXIST: entry %s already exists", entry.FullPath)
  180. return fmt.Errorf("EEXIST: entry %s already exists", entry.FullPath)
  181. }
  182. glog.V(4).Infof("UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
  183. if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
  184. glog.Errorf("update entry %s: %v", entry.FullPath, err)
  185. return fmt.Errorf("update entry %s: %v", entry.FullPath, err)
  186. }
  187. }
  188. f.NotifyUpdateEvent(ctx, oldEntry, entry, true, isFromOtherCluster, signatures)
  189. f.deleteChunksIfNotNew(oldEntry, entry)
  190. glog.V(4).Infof("CreateEntry %s: created", entry.FullPath)
  191. return nil
  192. }
  193. func (f *Filer) ensureParentDirecotryEntry(ctx context.Context, entry *Entry, dirParts []string, level int, isFromOtherCluster bool) (err error) {
  194. if level == 0 {
  195. return nil
  196. }
  197. dirPath := "/" + util.Join(dirParts[:level]...)
  198. // fmt.Printf("%d directory: %+v\n", i, dirPath)
  199. // check the store directly
  200. glog.V(4).Infof("find uncached directory: %s", dirPath)
  201. dirEntry, _ := f.FindEntry(ctx, util.FullPath(dirPath))
  202. // no such existing directory
  203. if dirEntry == nil {
  204. // ensure parent directory
  205. if err = f.ensureParentDirecotryEntry(ctx, entry, dirParts, level-1, isFromOtherCluster); err != nil {
  206. return err
  207. }
  208. // create the directory
  209. now := time.Now()
  210. dirEntry = &Entry{
  211. FullPath: util.FullPath(dirPath),
  212. Attr: Attr{
  213. Mtime: now,
  214. Crtime: now,
  215. Mode: os.ModeDir | entry.Mode | 0111,
  216. Uid: entry.Uid,
  217. Gid: entry.Gid,
  218. UserName: entry.UserName,
  219. GroupNames: entry.GroupNames,
  220. },
  221. }
  222. glog.V(2).Infof("create directory: %s %v", dirPath, dirEntry.Mode)
  223. mkdirErr := f.Store.InsertEntry(ctx, dirEntry)
  224. if mkdirErr != nil {
  225. if _, err := f.FindEntry(ctx, util.FullPath(dirPath)); err == filer_pb.ErrNotFound {
  226. glog.V(3).Infof("mkdir %s: %v", dirPath, mkdirErr)
  227. return fmt.Errorf("mkdir %s: %v", dirPath, mkdirErr)
  228. }
  229. } else {
  230. f.NotifyUpdateEvent(ctx, nil, dirEntry, false, isFromOtherCluster, nil)
  231. }
  232. } else if !dirEntry.IsDirectory() {
  233. glog.Errorf("CreateEntry %s: %s should be a directory", entry.FullPath, dirPath)
  234. return fmt.Errorf("%s is a file", dirPath)
  235. }
  236. return nil
  237. }
  238. func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
  239. if oldEntry != nil {
  240. entry.Attr.Crtime = oldEntry.Attr.Crtime
  241. if oldEntry.IsDirectory() && !entry.IsDirectory() {
  242. glog.Errorf("existing %s is a directory", oldEntry.FullPath)
  243. return fmt.Errorf("existing %s is a directory", oldEntry.FullPath)
  244. }
  245. if !oldEntry.IsDirectory() && entry.IsDirectory() {
  246. glog.Errorf("existing %s is a file", oldEntry.FullPath)
  247. return fmt.Errorf("existing %s is a file", oldEntry.FullPath)
  248. }
  249. }
  250. return f.Store.UpdateEntry(ctx, entry)
  251. }
  252. var (
  253. Root = &Entry{
  254. FullPath: "/",
  255. Attr: Attr{
  256. Mtime: time.Now(),
  257. Crtime: time.Now(),
  258. Mode: os.ModeDir | 0755,
  259. Uid: OS_UID,
  260. Gid: OS_GID,
  261. },
  262. }
  263. )
  264. func (f *Filer) FindEntry(ctx context.Context, p util.FullPath) (entry *Entry, err error) {
  265. if string(p) == "/" {
  266. return Root, nil
  267. }
  268. entry, err = f.Store.FindEntry(ctx, p)
  269. if entry != nil && entry.TtlSec > 0 {
  270. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  271. f.Store.DeleteOneEntry(ctx, entry)
  272. return nil, filer_pb.ErrNotFound
  273. }
  274. }
  275. return
  276. }
  277. 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) {
  278. lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) bool {
  279. select {
  280. case <-ctx.Done():
  281. return false
  282. default:
  283. if entry.TtlSec > 0 {
  284. if entry.Crtime.Add(time.Duration(entry.TtlSec) * time.Second).Before(time.Now()) {
  285. f.Store.DeleteOneEntry(ctx, entry)
  286. expiredCount++
  287. return true
  288. }
  289. }
  290. return eachEntryFunc(entry)
  291. }
  292. })
  293. if err != nil {
  294. return expiredCount, lastFileName, err
  295. }
  296. return
  297. }
  298. func (f *Filer) Shutdown() {
  299. f.LocalMetaLogBuffer.Shutdown()
  300. f.Store.Shutdown()
  301. }