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.

352 lines
11 KiB

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