ot_apps.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. package service
  2. import (
  3. "errors"
  4. "fmt"
  5. "github.com/go-sql-driver/mysql"
  6. omodels "go-admin/app/observe/models"
  7. "time"
  8. "encoding/json"
  9. "github.com/go-admin-team/go-admin-core/sdk/service"
  10. "gorm.io/gorm"
  11. "go-admin/app/admin/models"
  12. "go-admin/app/admin/service/dto"
  13. "go-admin/common/actions"
  14. cDto "go-admin/common/dto"
  15. "go-admin/utils"
  16. )
  17. type OtApps struct {
  18. service.Service
  19. }
  20. // GetPage 获取OtApps列表
  21. func (e *OtApps) GetPage(c *dto.OtAppsGetPageReq, p *actions.DataPermission, list *[]models.OtApps, count *int64) error {
  22. var err error
  23. var data models.OtApps
  24. err = e.Orm.Model(&data).
  25. Scopes(
  26. cDto.MakeCondition(c.GetNeedSearch()),
  27. cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
  28. actions.Permission(data.TableName(), p),
  29. ).
  30. Find(list).Limit(-1).Offset(-1).
  31. Count(count).Error
  32. if err != nil {
  33. e.Log.Errorf("OtAppsService GetPage error:%s \r\n", err)
  34. return err
  35. }
  36. return nil
  37. }
  38. // Get 获取OtApps对象
  39. func (e *OtApps) Get(d *dto.OtAppsGetReq, p *actions.DataPermission, model *models.OtApps) error {
  40. var data models.OtApps
  41. err := e.Orm.Model(&data).
  42. Scopes(
  43. actions.Permission(data.TableName(), p),
  44. ).
  45. First(model, d.GetId()).Error
  46. if err != nil && errors.Is(err, gorm.ErrRecordNotFound) {
  47. err = errors.New("查看对象不存在或无权查看")
  48. e.Log.Errorf("Service GetOtApps error:%s \r\n", err)
  49. return err
  50. }
  51. if err != nil {
  52. e.Log.Errorf("db error:%s", err)
  53. return err
  54. }
  55. return nil
  56. }
  57. // Insert 创建OtApps对象
  58. func (e *OtApps) Insert(c *dto.OtAppsInsertReq) error {
  59. var err error
  60. var data models.OtApps
  61. c.Generate(&data)
  62. svcAppNames := make([]omodels.DataServiceAppName, 0, len(c.ServiceNames))
  63. for _, serviceName := range c.ServiceNames {
  64. svcAppNames = append(svcAppNames, omodels.DataServiceAppName{
  65. CreateAt: time.Now(),
  66. ServiceName: serviceName,
  67. AppName: c.Alias,
  68. })
  69. }
  70. if errTrans := e.Orm.Transaction(func(tx *gorm.DB) error {
  71. err = tx.Create(&data).Error
  72. if err != nil {
  73. e.Log.Errorf("OtAppsService Insert error:%s \r\n", err)
  74. return fmt.Errorf("insert otapp failed: %w", err)
  75. }
  76. if len(svcAppNames) == 0 {
  77. return nil
  78. }
  79. if errDel := tx.Delete(&omodels.DataServiceAppName{}, "app_name=?", c.Alias).Error; errDel != nil {
  80. return fmt.Errorf("删除appname关系失败:%w", errDel)
  81. }
  82. if errBatch := tx.CreateInBatches(&svcAppNames, len(svcAppNames)).Error; errBatch != nil {
  83. var mysqlErr *mysql.MySQLError
  84. if errors.As(errBatch, &mysqlErr) {
  85. switch mysqlErr.Number {
  86. case 1062: // MySQL code for duplicate entry
  87. return fmt.Errorf("一个service只能属于一个appname:%w", errBatch)
  88. default:
  89. return fmt.Errorf("写入data_service_appname出错:%w", errBatch)
  90. }
  91. }
  92. return fmt.Errorf("写入data_service_appname出错:%w", errBatch)
  93. }
  94. return nil
  95. }); errTrans != nil {
  96. return errTrans
  97. }
  98. return nil
  99. }
  100. // Update 修改OtApps对象
  101. func (e *OtApps) Update(c *dto.OtAppsUpdateReq, p *actions.DataPermission) error {
  102. var err error
  103. var data = models.OtApps{}
  104. e.Orm.Scopes(
  105. actions.Permission(data.TableName(), p),
  106. ).First(&data, c.GetId())
  107. c.Generate(&data)
  108. svcAppNames := make([]omodels.DataServiceAppName, 0, len(c.ServiceNames))
  109. for _, serviceName := range c.ServiceNames {
  110. svcAppNames = append(svcAppNames, omodels.DataServiceAppName{
  111. CreateAt: time.Now(),
  112. ServiceName: serviceName,
  113. AppName: c.Alias,
  114. })
  115. }
  116. if errTrans := e.Orm.Transaction(func(tx *gorm.DB) error {
  117. db := tx.Save(&data)
  118. if err = db.Error; err != nil {
  119. e.Log.Errorf("OtAppsService Save error:%s \r\n", err)
  120. return err
  121. }
  122. if db.RowsAffected == 0 {
  123. return errors.New("无权更新该数据")
  124. }
  125. if errDel := tx.Delete(&omodels.DataServiceAppName{}, "app_name=?", c.Alias).Error; errDel != nil {
  126. return fmt.Errorf("删除appname关系失败:%w", errDel)
  127. }
  128. if len(svcAppNames) == 0 {
  129. return nil
  130. }
  131. if errBatch := tx.CreateInBatches(&svcAppNames, len(svcAppNames)).Error; errBatch != nil {
  132. var mysqlErr *mysql.MySQLError
  133. if errors.As(errBatch, &mysqlErr) {
  134. switch mysqlErr.Number {
  135. case 1062: // MySQL code for duplicate entry
  136. return fmt.Errorf("一个service只能属于一个appname:%w", errBatch)
  137. default:
  138. return fmt.Errorf("写入data_service_appname出错:%w", errBatch)
  139. }
  140. }
  141. return fmt.Errorf("写入data_service_appname出错:%w", errBatch)
  142. }
  143. return nil
  144. }); errTrans != nil {
  145. return errTrans
  146. }
  147. return nil
  148. }
  149. // Remove 删除OtApps
  150. func (e *OtApps) Remove(d *dto.OtAppsDeleteReq, p *actions.DataPermission) error {
  151. var data models.OtApps
  152. db := e.Orm.Model(&data).
  153. Scopes(
  154. actions.Permission(data.TableName(), p),
  155. ).Delete(&data, d.GetId())
  156. if err := db.Error; err != nil {
  157. e.Log.Errorf("Service RemoveOtApps error:%s \r\n", err)
  158. return err
  159. }
  160. if db.RowsAffected == 0 {
  161. return errors.New("无权删除该数据")
  162. }
  163. return nil
  164. }
  165. func (e *OtApps) CreateDashBoard(ad *OtAppDashboard, op *OtPlugins, d *models.OtApps) error {
  166. // GetPlugin
  167. plugin := new(models.OtPlugins)
  168. plugin.Alias = "grafana"
  169. var err error
  170. err = op.GetPluginByAlias(plugin)
  171. if err != nil {
  172. e.Log.Error("Get Plugin %s error: %s \r\n", plugin.Alias, err)
  173. return err
  174. }
  175. configMap := make(map[string]string)
  176. err = json.Unmarshal([]byte(plugin.Config), &configMap)
  177. if err != nil {
  178. e.Log.Errorf("unmarshal error: %s \r\n", err)
  179. return err
  180. }
  181. // 请求grafana API,create
  182. grafanaApi := fmt.Sprintf("%s/api/dashboards/db", plugin.Url)
  183. e.Log.Debugf("create grafan dashboard: %s, token: %s", grafanaApi, configMap["admin"])
  184. g := utils.GrafanaViewer{
  185. Url: plugin.Url,
  186. Token: configMap["admin"],
  187. }
  188. gresp := utils.GrDashBoard{
  189. Title: fmt.Sprintf("%s-viewer", d.Alias),
  190. Tags: []string{d.Alias, d.Name},
  191. TimeZone: "browser",
  192. SchemaVersion: 16,
  193. Refresh: "1m",
  194. }
  195. gdbr := utils.GrDashBoardReq{
  196. Dashboard: &gresp,
  197. Overwrite: false,
  198. }
  199. err = g.CreateDashBoard(&gdbr, &gresp)
  200. if err != nil {
  201. e.Log.Errorf("CreateDashBoard error: %s \r\n", err.Error())
  202. return err
  203. }
  204. //TODO: 写入关系
  205. c := new(dto.OtAppDashboardInsertReq)
  206. c.AppId = int64(d.Id)
  207. c.DashboardUid = gresp.Url
  208. err = ad.Insert(c)
  209. if err != nil {
  210. e.Log.Errorf("CreateDashBoard insert app_dashboard error: %s \r\n", err.Error())
  211. return err
  212. }
  213. return nil
  214. }