models.go 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255
  1. // Copyright 2019 Yunion
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package db
  15. import (
  16. "fmt"
  17. "os"
  18. "reflect"
  19. "strings"
  20. "yunion.io/x/log"
  21. "yunion.io/x/pkg/utils"
  22. "yunion.io/x/sqlchemy"
  23. "yunion.io/x/onecloud/pkg/appsrv"
  24. common_options "yunion.io/x/onecloud/pkg/cloudcommon/options"
  25. )
  26. var globalTables map[string]IModelManager
  27. func GlobalModelManagerTables() map[string]IModelManager {
  28. return globalTables
  29. }
  30. func RegisterModelManager(modelMan IModelManager) {
  31. RegisterModelManagerWithKeyword(modelMan, "")
  32. }
  33. func RegisterModelManagerWithKeyword(modelMan IModelManager, keyword string) {
  34. if globalTables == nil {
  35. globalTables = make(map[string]IModelManager)
  36. }
  37. if len(keyword) == 0 {
  38. keyword = modelMan.Keyword()
  39. }
  40. mustCheckModelManager(modelMan)
  41. if _, ok := globalTables[keyword]; ok {
  42. log.Fatalf("keyword %s exists in globalTables!", keyword)
  43. }
  44. globalTables[keyword] = modelMan
  45. }
  46. func mustCheckModelManager(modelMan IModelManager) {
  47. allowedTags := map[string][]string{
  48. "create": {
  49. "required",
  50. "optional",
  51. "domain",
  52. "domain_required",
  53. "domain_optional",
  54. "admin_required",
  55. "admin_optional",
  56. },
  57. "search": {"user", "domain", "admin"},
  58. "get": {"user", "domain", "admin"},
  59. "list": {"user", "domain", "admin"},
  60. "update": {"user", "domain", "admin"},
  61. }
  62. for _, col := range modelMan.TableSpec().Columns() {
  63. tags := col.Tags()
  64. for tagName, allowedValues := range allowedTags {
  65. v, ok := tags[tagName]
  66. if !ok {
  67. continue
  68. }
  69. if len(v) > 0 && !utils.IsInStringArray(v, allowedValues) {
  70. msg := fmt.Sprintf("model manager %s: column %s has invalid tag %s:\"%s\", expecting %v",
  71. modelMan.KeywordPlural(), col.Name(), tagName, v, allowedValues)
  72. panic(msg)
  73. }
  74. }
  75. }
  76. if false {
  77. requiredManagerFuncNames := []string{
  78. "ListItemFilter",
  79. "OrderByExtraFields",
  80. "FetchCustomizeColumns",
  81. }
  82. for _, name := range requiredManagerFuncNames {
  83. manV := reflect.ValueOf(modelMan)
  84. methV := manV.MethodByName(name)
  85. if !methV.IsValid() {
  86. msg := fmt.Sprintf("model manager %T: has no valid %s, likely caused by ambiguity",
  87. modelMan, name)
  88. panic(msg)
  89. }
  90. }
  91. }
  92. }
  93. func tableSpecId(tableSpec ITableSpec) string {
  94. keys := []string{
  95. string(tableSpec.GetDBName()),
  96. tableSpec.Name(),
  97. }
  98. for _, c := range tableSpec.Columns() {
  99. keys = append(keys, c.Name())
  100. }
  101. return strings.Join(keys, "-")
  102. }
  103. func CheckSync(autoSync bool, enableChecksumTables bool, skipInitChecksum bool) bool {
  104. log.Infof("Start check database schema: autoSync(%v), enableChecksumTables(%v), skipInitChecksum(%v)", autoSync, enableChecksumTables, skipInitChecksum)
  105. inSync := true
  106. var err error
  107. foreignProcessedTbl := make(map[string]bool)
  108. for modelName, modelMan := range globalTables {
  109. tableSpec := modelMan.TableSpec()
  110. tableKey := tableSpecId(tableSpec)
  111. if _, ok := foreignProcessedTbl[tableKey]; ok {
  112. continue
  113. }
  114. foreignProcessedTbl[tableKey] = true
  115. dropFKSqls := tableSpec.DropForeignKeySQL()
  116. if len(dropFKSqls) > 0 {
  117. log.Infof("model %s drop foreign key constraints!!!", modelName)
  118. if autoSync {
  119. if ts, ok := tableSpec.(*sTableSpec); ok {
  120. err = commitSqlDiffWithName(dropFKSqls, ts.GetDBName())
  121. } else {
  122. err = commitSqlDIffs(dropFKSqls)
  123. }
  124. if err != nil {
  125. log.Errorf("commit sql error %s", err)
  126. return false
  127. }
  128. } else {
  129. for _, sql := range dropFKSqls {
  130. log.Infof("%s;", sql)
  131. }
  132. inSync = false
  133. }
  134. }
  135. }
  136. processedTbl := make(map[string]bool)
  137. for modelName, modelMan := range globalTables {
  138. tableSpec := modelMan.TableSpec()
  139. tableKey := tableSpecId(tableSpec)
  140. if _, ok := processedTbl[tableKey]; ok {
  141. log.Warningf("table %s has been synced!", tableKey)
  142. continue
  143. }
  144. processedTbl[tableKey] = true
  145. sqls := tableSpec.SyncSQL()
  146. if len(sqls) > 0 {
  147. log.Infof("model %s is not in SYNC!!!", modelName)
  148. if autoSync {
  149. if ts, ok := tableSpec.(*sTableSpec); ok {
  150. err = commitSqlDiffWithName(sqls, ts.GetDBName())
  151. } else {
  152. err = commitSqlDIffs(sqls)
  153. }
  154. if err != nil {
  155. log.Errorf("commit sql error %s", err)
  156. return false
  157. }
  158. } else {
  159. for _, sql := range sqls {
  160. log.Infof("%s;", sql)
  161. }
  162. inSync = false
  163. }
  164. }
  165. recordMan, ok := modelMan.(IRecordChecksumModelManager)
  166. if ok {
  167. recordMan.SetEnableRecordChecksum(enableChecksumTables)
  168. if recordMan.EnableRecordChecksum() {
  169. if len(sqls) > 0 || !skipInitChecksum {
  170. if err := InjectModelsChecksum(recordMan); err != nil {
  171. log.Errorf("InjectModelsChecksum for %q error: %v", modelMan.TableSpec().Name(), err)
  172. return false
  173. }
  174. }
  175. }
  176. }
  177. }
  178. return inSync
  179. }
  180. func EnsureAppSyncDB(app *appsrv.Application, opt *common_options.DBOptions, modelInitDBFunc func() error) {
  181. // cloudcommon.InitDB(opt)
  182. if !CheckSync(opt.AutoSyncTable, opt.EnableDBChecksumTables, opt.DBChecksumSkipInit) {
  183. log.Fatalf("database schema not in sync!")
  184. }
  185. if modelInitDBFunc != nil {
  186. if err := modelInitDBFunc(); err != nil {
  187. log.Fatalf("model init db: %v", err)
  188. }
  189. }
  190. if opt.ExitAfterDBInit {
  191. log.Infof("Exiting after db initialization ...")
  192. os.Exit(0)
  193. }
  194. AppDBInit(app)
  195. }
  196. func GetModelManager(keyword string) IModelManager {
  197. modelMan, ok := globalTables[keyword]
  198. if ok {
  199. return modelMan
  200. } else {
  201. return nil
  202. }
  203. }
  204. func commitSqlDIffs(sqls []string) error {
  205. db := sqlchemy.GetDB()
  206. for _, sql := range sqls {
  207. log.Infof("Exec %s", sql)
  208. _, err := db.Exec(sql)
  209. if err != nil {
  210. log.Errorf("Exec sql failed %s\n%s", sql, err)
  211. return err
  212. }
  213. }
  214. return nil
  215. }
  216. func commitSqlDiffWithName(sqls []string, dbName sqlchemy.DBName) error {
  217. db := sqlchemy.GetDBWithName(dbName)
  218. return execSqlDiffWithDb(sqls, db)
  219. }
  220. func execSqlDiffWithDb(sqls []string, db *sqlchemy.SDatabase) error {
  221. for _, sql := range sqls {
  222. log.Infof("Exec %s", sql)
  223. _, err := db.Exec(sql)
  224. if err != nil {
  225. log.Errorf("Exec sql failed %s\n%s", sql, err)
  226. return err
  227. }
  228. }
  229. return nil
  230. }