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.

335 lines
9.2 KiB

7 years ago
4 years ago
5 years ago
5 years ago
  1. package abstract_sql
  2. import (
  3. "context"
  4. "database/sql"
  5. "fmt"
  6. "github.com/chrislusf/seaweedfs/weed/filer"
  7. "github.com/chrislusf/seaweedfs/weed/glog"
  8. "github.com/chrislusf/seaweedfs/weed/pb/filer_pb"
  9. "github.com/chrislusf/seaweedfs/weed/util"
  10. "strings"
  11. "sync"
  12. )
  13. type SqlGenerator interface {
  14. GetSqlInsert(bucket string) string
  15. GetSqlUpdate(bucket string) string
  16. GetSqlFind(bucket string) string
  17. GetSqlDelete(bucket string) string
  18. GetSqlDeleteFolderChildren(bucket string) string
  19. GetSqlListExclusive(bucket string) string
  20. GetSqlListInclusive(bucket string) string
  21. GetSqlCreateTable(bucket string) string
  22. GetSqlDropTable(bucket string) string
  23. }
  24. type AbstractSqlStore struct {
  25. SqlGenerator
  26. DB *sql.DB
  27. SupportBucketTable bool
  28. dbs map[string]bool
  29. dbsLock sync.Mutex
  30. }
  31. const (
  32. DEFAULT_TABLE = "filemeta"
  33. )
  34. type TxOrDB interface {
  35. ExecContext(ctx context.Context, query string, args ...interface{}) (sql.Result, error)
  36. QueryRowContext(ctx context.Context, query string, args ...interface{}) *sql.Row
  37. QueryContext(ctx context.Context, query string, args ...interface{}) (*sql.Rows, error)
  38. }
  39. func (store *AbstractSqlStore) BeginTransaction(ctx context.Context) (context.Context, error) {
  40. tx, err := store.DB.BeginTx(ctx, &sql.TxOptions{
  41. Isolation: sql.LevelReadCommitted,
  42. ReadOnly: false,
  43. })
  44. if err != nil {
  45. return ctx, err
  46. }
  47. return context.WithValue(ctx, "tx", tx), nil
  48. }
  49. func (store *AbstractSqlStore) CommitTransaction(ctx context.Context) error {
  50. if tx, ok := ctx.Value("tx").(*sql.Tx); ok {
  51. return tx.Commit()
  52. }
  53. return nil
  54. }
  55. func (store *AbstractSqlStore) RollbackTransaction(ctx context.Context) error {
  56. if tx, ok := ctx.Value("tx").(*sql.Tx); ok {
  57. return tx.Rollback()
  58. }
  59. return nil
  60. }
  61. func (store *AbstractSqlStore) getTxOrDB(ctx context.Context, fullpath util.FullPath, isForChildren bool) (txOrDB TxOrDB, bucket string, shortPath util.FullPath, err error) {
  62. shortPath = fullpath
  63. bucket = DEFAULT_TABLE
  64. if tx, ok := ctx.Value("tx").(*sql.Tx); ok {
  65. txOrDB = tx
  66. } else {
  67. txOrDB = store.DB
  68. }
  69. if !store.SupportBucketTable {
  70. return
  71. }
  72. if !strings.HasPrefix(string(fullpath), "/buckets/") {
  73. return
  74. }
  75. // detect bucket
  76. bucketAndObjectKey := string(fullpath)[len("/buckets/"):]
  77. t := strings.Index(bucketAndObjectKey, "/")
  78. if t < 0 && !isForChildren {
  79. return
  80. }
  81. if t > 0 {
  82. bucket = bucketAndObjectKey[:t]
  83. shortPath = util.FullPath(bucketAndObjectKey[t:])
  84. }
  85. if isValidBucket(bucket) {
  86. store.dbsLock.Lock()
  87. defer store.dbsLock.Unlock()
  88. if store.dbs == nil {
  89. store.dbs = make(map[string]bool)
  90. }
  91. if _, found := store.dbs[bucket]; !found {
  92. if err = store.createTable(ctx, bucket); err != nil {
  93. store.dbs[bucket] = true
  94. }
  95. }
  96. }
  97. return
  98. }
  99. func (store *AbstractSqlStore) InsertEntry(ctx context.Context, entry *filer.Entry) (err error) {
  100. db, bucket, shortPath, err := store.getTxOrDB(ctx, entry.FullPath, false)
  101. if err != nil {
  102. return fmt.Errorf("findDB %s : %v", entry.FullPath, err)
  103. }
  104. dir, name := shortPath.DirAndName()
  105. meta, err := entry.EncodeAttributesAndChunks()
  106. if err != nil {
  107. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  108. }
  109. if len(entry.Chunks) > 50 {
  110. meta = util.MaybeGzipData(meta)
  111. }
  112. res, err := db.ExecContext(ctx, store.GetSqlInsert(bucket), util.HashStringToLong(dir), name, dir, meta)
  113. if err == nil {
  114. return
  115. }
  116. if !strings.Contains(strings.ToLower(err.Error()), "duplicate") {
  117. // return fmt.Errorf("insert: %s", err)
  118. // skip this since the error can be in a different language
  119. }
  120. // now the insert failed possibly due to duplication constraints
  121. glog.V(1).Infof("insert %s falls back to update: %v", entry.FullPath, err)
  122. res, err = db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
  123. if err != nil {
  124. return fmt.Errorf("upsert %s: %s", entry.FullPath, err)
  125. }
  126. _, err = res.RowsAffected()
  127. if err != nil {
  128. return fmt.Errorf("upsert %s but no rows affected: %s", entry.FullPath, err)
  129. }
  130. return nil
  131. }
  132. func (store *AbstractSqlStore) UpdateEntry(ctx context.Context, entry *filer.Entry) (err error) {
  133. db, bucket, shortPath, err := store.getTxOrDB(ctx, entry.FullPath, false)
  134. if err != nil {
  135. return fmt.Errorf("findDB %s : %v", entry.FullPath, err)
  136. }
  137. dir, name := shortPath.DirAndName()
  138. meta, err := entry.EncodeAttributesAndChunks()
  139. if err != nil {
  140. return fmt.Errorf("encode %s: %s", entry.FullPath, err)
  141. }
  142. res, err := db.ExecContext(ctx, store.GetSqlUpdate(bucket), meta, util.HashStringToLong(dir), name, dir)
  143. if err != nil {
  144. return fmt.Errorf("update %s: %s", entry.FullPath, err)
  145. }
  146. _, err = res.RowsAffected()
  147. if err != nil {
  148. return fmt.Errorf("update %s but no rows affected: %s", entry.FullPath, err)
  149. }
  150. return nil
  151. }
  152. func (store *AbstractSqlStore) FindEntry(ctx context.Context, fullpath util.FullPath) (*filer.Entry, error) {
  153. db, bucket, shortPath, err := store.getTxOrDB(ctx, fullpath, false)
  154. if err != nil {
  155. return nil, fmt.Errorf("findDB %s : %v", fullpath, err)
  156. }
  157. dir, name := shortPath.DirAndName()
  158. row := db.QueryRowContext(ctx, store.GetSqlFind(bucket), util.HashStringToLong(dir), name, dir)
  159. var data []byte
  160. if err := row.Scan(&data); err != nil {
  161. if err == sql.ErrNoRows {
  162. return nil, filer_pb.ErrNotFound
  163. }
  164. return nil, fmt.Errorf("find %s: %v", fullpath, err)
  165. }
  166. entry := &filer.Entry{
  167. FullPath: fullpath,
  168. }
  169. if err := entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  170. return entry, fmt.Errorf("decode %s : %v", entry.FullPath, err)
  171. }
  172. return entry, nil
  173. }
  174. func (store *AbstractSqlStore) DeleteEntry(ctx context.Context, fullpath util.FullPath) error {
  175. db, bucket, shortPath, err := store.getTxOrDB(ctx, fullpath, false)
  176. if err != nil {
  177. return fmt.Errorf("findDB %s : %v", fullpath, err)
  178. }
  179. dir, name := shortPath.DirAndName()
  180. res, err := db.ExecContext(ctx, store.GetSqlDelete(bucket), util.HashStringToLong(dir), name, dir)
  181. if err != nil {
  182. return fmt.Errorf("delete %s: %s", fullpath, err)
  183. }
  184. _, err = res.RowsAffected()
  185. if err != nil {
  186. return fmt.Errorf("delete %s but no rows affected: %s", fullpath, err)
  187. }
  188. return nil
  189. }
  190. func (store *AbstractSqlStore) DeleteFolderChildren(ctx context.Context, fullpath util.FullPath) error {
  191. db, bucket, shortPath, err := store.getTxOrDB(ctx, fullpath, true)
  192. if err != nil {
  193. return fmt.Errorf("findDB %s : %v", fullpath, err)
  194. }
  195. if isValidBucket(bucket) && shortPath == "/" {
  196. if err = store.deleteTable(ctx, bucket); err != nil {
  197. store.dbsLock.Lock()
  198. delete(store.dbs, bucket)
  199. store.dbsLock.Unlock()
  200. return nil
  201. }
  202. }
  203. res, err := db.ExecContext(ctx, store.GetSqlDeleteFolderChildren(bucket), util.HashStringToLong(string(shortPath)), fullpath)
  204. if err != nil {
  205. return fmt.Errorf("deleteFolderChildren %s: %s", fullpath, err)
  206. }
  207. _, err = res.RowsAffected()
  208. if err != nil {
  209. return fmt.Errorf("deleteFolderChildren %s but no rows affected: %s", fullpath, err)
  210. }
  211. return nil
  212. }
  213. func (store *AbstractSqlStore) ListDirectoryPrefixedEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, prefix string, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  214. db, bucket, shortPath, err := store.getTxOrDB(ctx, dirPath, true)
  215. if err != nil {
  216. return lastFileName, fmt.Errorf("findDB %s : %v", dirPath, err)
  217. }
  218. sqlText := store.GetSqlListExclusive(bucket)
  219. if includeStartFile {
  220. sqlText = store.GetSqlListInclusive(bucket)
  221. }
  222. rows, err := db.QueryContext(ctx, sqlText, util.HashStringToLong(string(shortPath)), startFileName, string(shortPath), prefix+"%", limit+1)
  223. if err != nil {
  224. return lastFileName, fmt.Errorf("list %s : %v", dirPath, err)
  225. }
  226. defer rows.Close()
  227. for rows.Next() {
  228. var name string
  229. var data []byte
  230. if err = rows.Scan(&name, &data); err != nil {
  231. glog.V(0).Infof("scan %s : %v", dirPath, err)
  232. return lastFileName, fmt.Errorf("scan %s: %v", dirPath, err)
  233. }
  234. lastFileName = name
  235. entry := &filer.Entry{
  236. FullPath: util.NewFullPath(string(dirPath), name),
  237. }
  238. if err = entry.DecodeAttributesAndChunks(util.MaybeDecompressData(data)); err != nil {
  239. glog.V(0).Infof("scan decode %s : %v", entry.FullPath, err)
  240. return lastFileName, fmt.Errorf("scan decode %s : %v", entry.FullPath, err)
  241. }
  242. if !eachEntryFunc(entry) {
  243. break
  244. }
  245. }
  246. return lastFileName, nil
  247. }
  248. func (store *AbstractSqlStore) ListDirectoryEntries(ctx context.Context, dirPath util.FullPath, startFileName string, includeStartFile bool, limit int64, eachEntryFunc filer.ListEachEntryFunc) (lastFileName string, err error) {
  249. return store.ListDirectoryPrefixedEntries(ctx, dirPath, startFileName, includeStartFile, limit, "", nil)
  250. }
  251. func (store *AbstractSqlStore) Shutdown() {
  252. store.DB.Close()
  253. }
  254. func isValidBucket(bucket string) bool {
  255. return bucket != DEFAULT_TABLE && bucket != ""
  256. }
  257. func (store *AbstractSqlStore) createTable(ctx context.Context, bucket string) error {
  258. if !store.SupportBucketTable {
  259. return nil
  260. }
  261. _, err := store.DB.ExecContext(ctx, store.SqlGenerator.GetSqlCreateTable(bucket))
  262. return err
  263. }
  264. func (store *AbstractSqlStore) deleteTable(ctx context.Context, bucket string) error {
  265. if !store.SupportBucketTable {
  266. return nil
  267. }
  268. _, err := store.DB.ExecContext(ctx, store.SqlGenerator.GetSqlDropTable(bucket))
  269. return err
  270. }