abstract_sql_store.go 10 KB

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