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.

254 lines
7.2 KiB

3 years ago
1 year ago
1 year ago
1 year ago
1 year ago
5 years ago
1 year ago
1 year ago
1 year ago
5 years ago
  1. package etcd
  2. import (
  3. "context"
  4. "crypto/tls"
  5. "fmt"
  6. "go.etcd.io/etcd/client/pkg/v3/transport"
  7. "strings"
  8. "time"
  9. "go.etcd.io/etcd/client/v3"
  10. "github.com/seaweedfs/seaweedfs/weed/filer"
  11. "github.com/seaweedfs/seaweedfs/weed/glog"
  12. "github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
  13. weed_util "github.com/seaweedfs/seaweedfs/weed/util"
  14. )
  15. const (
  16. DIR_FILE_SEPARATOR = byte(0x00)
  17. )
  18. func init() {
  19. filer.Stores = append(filer.Stores, &EtcdStore{})
  20. }
  21. type EtcdStore struct {
  22. client *clientv3.Client
  23. etcdKeyPrefix string
  24. timeout time.Duration
  25. }
  26. func (store *EtcdStore) GetName() string {
  27. return "etcd"
  28. }
  29. func (store *EtcdStore) Initialize(configuration weed_util.Configuration, prefix string) error {
  30. configuration.SetDefault(prefix+"servers", "localhost:2379")
  31. configuration.SetDefault(prefix+"timeout", "3s")
  32. servers := configuration.GetString(prefix + "servers")
  33. username := configuration.GetString(prefix + "username")
  34. password := configuration.GetString(prefix + "password")
  35. store.etcdKeyPrefix = configuration.GetString(prefix + "key_prefix")
  36. timeoutStr := configuration.GetString(prefix + "timeout")
  37. timeout, err := time.ParseDuration(timeoutStr)
  38. if err != nil {
  39. return fmt.Errorf("parse etcd store timeout: %v", err)
  40. }
  41. store.timeout = timeout
  42. certFile := configuration.GetString(prefix + "tls_client_crt_file")
  43. keyFile := configuration.GetString(prefix + "tls_client_key_file")
  44. caFile := configuration.GetString(prefix + "tls_ca_file")
  45. var tlsConfig *tls.Config
  46. if caFile != "" {
  47. tlsInfo := transport.TLSInfo{
  48. CertFile: certFile,
  49. KeyFile: keyFile,
  50. TrustedCAFile: caFile,
  51. }
  52. var err error
  53. tlsConfig, err = tlsInfo.ClientConfig()
  54. if err != nil {
  55. return fmt.Errorf("TLS client configuration error: %v", err)
  56. }
  57. }
  58. return store.initialize(servers, username, password, store.timeout, tlsConfig)
  59. }
  60. func (store *EtcdStore) initialize(servers, username, password string, timeout time.Duration, tlsConfig *tls.Config) error {
  61. glog.Infof("filer store etcd: %s", servers)
  62. client, err := clientv3.New(clientv3.Config{
  63. Endpoints: strings.Split(servers, ","),
  64. Username: username,
  65. Password: password,
  66. DialTimeout: timeout,
  67. TLS: tlsConfig,
  68. })
  69. if err != nil {
  70. return fmt.Errorf("connect to etcd %s: %s", servers, err)
  71. }
  72. ctx, cancel := context.WithTimeout(context.Background(), store.timeout)
  73. defer cancel()
  74. resp, err := client.Status(ctx, client.Endpoints()[0])
  75. if err != nil {
  76. client.Close()
  77. return fmt.Errorf("error checking etcd connection: %s", err)
  78. }
  79. glog.V(0).Infof("сonnection to etcd has been successfully verified. etcd version: %s", resp.Version)
  80. store.client = client
  81. return nil
  82. }
  83. func (store *EtcdStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  84. return ctx, nil
  85. }
  86. func (store *EtcdStore) CommitTransaction(ctx context.Context) error {
  87. return nil
  88. }
  89. func (store *EtcdStore) RollbackTransaction(ctx context.Context) error {
  90. return nil
  91. }
  92. func (store *EtcdStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  93. key := genKey(entry.DirAndName())
  94. meta, err := entry.EncodeAttributesAndChunks()
  95. if err != nil {
  96. return fmt.Errorf("encoding %s %+v: %v", entry.FullPath, entry.Attr, err)
  97. }
  98. if len(entry.GetChunks()) > filer.CountEntryChunksForGzip {
  99. meta = weed_util.MaybeGzipData(meta)
  100. }
  101. if _, err := store.client.Put(ctx, store.etcdKeyPrefix+string(key), string(meta)); err != nil {
  102. return fmt.Errorf("persisting %s : %v", entry.FullPath, err)
  103. }
  104. return nil
  105. }
  106. func (store *EtcdStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  107. return store.InsertEntry(ctx, entry)
  108. }
  109. func (store *EtcdStore) FindEntry(ctx context.Context, fullpath weed_util.FullPath) (entry *filer.Entry, err error) {
  110. key := genKey(fullpath.DirAndName())
  111. resp, err := store.client.Get(ctx, store.etcdKeyPrefix+string(key))
  112. if err != nil {
  113. return nil, fmt.Errorf("get %s : %v", fullpath, err)
  114. }
  115. if len(resp.Kvs) == 0 {
  116. return nil, filer_pb.ErrNotFound
  117. }
  118. entry = &filer.Entry{
  119. FullPath: fullpath,
  120. }
  121. err = entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(resp.Kvs[0].Value))
  122. if err != nil {
  123. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  124. }
  125. return entry, nil
  126. }
  127. func (store *EtcdStore) DeleteEntry(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  128. key := genKey(fullpath.DirAndName())
  129. if _, err := store.client.Delete(ctx, store.etcdKeyPrefix+string(key)); err != nil {
  130. return fmt.Errorf("delete %s : %v", fullpath, err)
  131. }
  132. return nil
  133. }
  134. func (store *EtcdStore) DeleteFolderChildren(ctx context.Context, fullpath weed_util.FullPath) (err error) {
  135. directoryPrefix := genDirectoryKeyPrefix(fullpath, "")
  136. if _, err := store.client.Delete(ctx, store.etcdKeyPrefix+string(directoryPrefix), clientv3.WithPrefix()); err != nil {
  137. return fmt.Errorf("deleteFolderChildren %s : %v", fullpath, err)
  138. }
  139. return nil
  140. }
  141. func (store *EtcdStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  142. directoryPrefix := genDirectoryKeyPrefix(dirPath, prefix)
  143. lastFileStart := directoryPrefix
  144. if startFileName != "" {
  145. lastFileStart = genDirectoryKeyPrefix(dirPath, startFileName)
  146. }
  147. resp, err := store.client.Get(ctx, store.etcdKeyPrefix+string(lastFileStart),
  148. clientv3.WithRange(clientv3.GetPrefixRangeEnd(store.etcdKeyPrefix+string(directoryPrefix))),
  149. clientv3.WithLimit(limit+1))
  150. if err != nil {
  151. return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
  152. }
  153. for _, kv := range resp.Kvs {
  154. fileName := getNameFromKey(kv.Key)
  155. if fileName == "" {
  156. continue
  157. }
  158. if fileName == startFileName && !includeStartFile {
  159. continue
  160. }
  161. limit--
  162. if limit < 0 {
  163. break
  164. }
  165. entry := &filer.Entry{
  166. FullPath: weed_util.NewFullPath(string(dirPath), fileName),
  167. }
  168. if decodeErr := entry.DecodeAttributesAndChunks(weed_util.MaybeDecompressData(kv.Value)); decodeErr != nil {
  169. err = decodeErr
  170. glog.V(0).Infof("list %s : %v", entry.FullPath, err)
  171. break
  172. }
  173. if !eachEntryFunc(entry) {
  174. break
  175. }
  176. lastFileName = fileName
  177. }
  178. return lastFileName, err
  179. }
  180. func (store *EtcdStore) ListDirectoryEntries(ctx context.Context, dirPath weed_util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  181. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", eachEntryFunc)
  182. }
  183. func genKey(dirPath, fileName string) (key []byte) {
  184. key = []byte(dirPath)
  185. key = append(key, DIR_FILE_SEPARATOR)
  186. key = append(key, []byte(fileName)...)
  187. return key
  188. }
  189. func genDirectoryKeyPrefix(fullpath weed_util.FullPath, startFileName string) (keyPrefix []byte) {
  190. keyPrefix = []byte(string(fullpath))
  191. keyPrefix = append(keyPrefix, DIR_FILE_SEPARATOR)
  192. if len(startFileName) > 0 {
  193. keyPrefix = append(keyPrefix, []byte(startFileName)...)
  194. }
  195. return keyPrefix
  196. }
  197. func getNameFromKey(key []byte) string {
  198. sepIndex := len(key) - 1
  199. for sepIndex >= 0 && key[sepIndex] != DIR_FILE_SEPARATOR {
  200. sepIndex--
  201. }
  202. return string(key[sepIndex+1:])
  203. }
  204. func (store *EtcdStore) Shutdown() {
  205. store.client.Close()
  206. }