database.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  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. "context"
  17. "database/sql"
  18. "fmt"
  19. "net/http"
  20. "strings"
  21. "yunion.io/x/jsonutils"
  22. "yunion.io/x/log"
  23. "yunion.io/x/pkg/appctx"
  24. "yunion.io/x/sqlchemy"
  25. "yunion.io/x/onecloud/pkg/appsrv"
  26. "yunion.io/x/onecloud/pkg/mcclient"
  27. "yunion.io/x/onecloud/pkg/util/splitable"
  28. )
  29. const (
  30. MIN_DB_CONN_MAX = 5
  31. ClickhouseDB = sqlchemy.DBName("clickhouse_db")
  32. )
  33. func AppDBInit(app *appsrv.Application) {
  34. dbConn := sqlchemy.GetDefaultDB()
  35. if dbConn != nil {
  36. setDbConnection(dbConn.DB())
  37. }
  38. dbConn = sqlchemy.GetDBWithName(ClickhouseDB)
  39. if dbConn != nil {
  40. setDbConnection(dbConn.DB())
  41. }
  42. app.AddDefaultHandler("GET", "/db_stats", DBStatsHandler, "db_stats")
  43. app.AddDefaultHandler("GET", "/db_stats/<db>", DBStatsHandler, "db_stats_with_name")
  44. }
  45. func setDbConnection(dbConn *sql.DB) {
  46. if dbConn != nil {
  47. connMax := appsrv.GetDBConnectionCount()
  48. if connMax < MIN_DB_CONN_MAX {
  49. connMax = MIN_DB_CONN_MAX
  50. }
  51. log.Infof("Total %d db workers, set db connection max", connMax)
  52. dbConn.SetMaxIdleConns(connMax)
  53. dbConn.SetMaxOpenConns(connMax*2 + 1)
  54. }
  55. }
  56. func DBStatsHandler(ctx context.Context, w http.ResponseWriter, r *http.Request) {
  57. var dbname sqlchemy.DBName
  58. params := appctx.AppContextParams(ctx)
  59. if dbn, ok := params["<db>"]; ok && strings.HasPrefix(dbn, "click") {
  60. dbname = ClickhouseDB
  61. } else {
  62. dbname = sqlchemy.DefaultDB
  63. }
  64. result := jsonutils.NewDict()
  65. dbConn := sqlchemy.GetDBWithName(dbname)
  66. if dbConn != nil {
  67. stats := dbConn.DB().Stats()
  68. result.Add(jsonutils.Marshal(&stats), "db_stats")
  69. }
  70. fmt.Fprintf(w, "%s", result.String())
  71. }
  72. func AutoPurgeSplitable(ctx context.Context, userCred mcclient.TokenCredential, startRun bool) {
  73. err := splitable.PurgeAll()
  74. if err != nil {
  75. log.Errorf("AutoPurgeSplitable fail %s", err)
  76. }
  77. }