force.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package service
  2. import (
  3. "context"
  4. "go-common/app/admin/main/config/model"
  5. "go-common/library/log"
  6. "github.com/jinzhu/gorm"
  7. )
  8. //UpdateForce update force.
  9. func (s *Service) UpdateForce(ctx context.Context, treeID, version int64, env, zone, build, username string, hosts map[string]string) (err error) {
  10. var (
  11. app *model.App
  12. force *model.Force
  13. ups map[string]interface{}
  14. )
  15. if app, err = s.AppByTree(treeID, env, zone); err != nil {
  16. return
  17. }
  18. tx := s.dao.DB.Begin()
  19. for key, val := range hosts {
  20. force = &model.Force{}
  21. force.Hostname = key
  22. force.AppID = app.ID
  23. force.IP = val
  24. force.Operator = username
  25. force.Version = version
  26. if err = s.dao.DB.Where("app_id = ? and hostname = ? and ip = ?", app.ID, key, val).First(&model.Force{}).Error; err != nil {
  27. if err != gorm.ErrRecordNotFound {
  28. tx.Rollback()
  29. log.Error("UpdateForce first error(%v)", err)
  30. return
  31. }
  32. //create
  33. if err = s.dao.DB.Create(force).Error; err != nil {
  34. tx.Rollback()
  35. log.Error("UpdateForce(%s) error(%v)", force, err)
  36. return
  37. }
  38. } else {
  39. //update
  40. ups = map[string]interface{}{
  41. "hostname": key,
  42. "app_id": app.ID,
  43. "ip": val,
  44. "operator": username,
  45. "version": version,
  46. }
  47. if err = s.dao.DB.Model(&model.Force{}).Where("app_id = ? and hostname = ? and ip = ?", app.ID, key, val).Updates(ups).Error; err != nil {
  48. tx.Rollback()
  49. log.Error("UpdateForce(%s) error(%v)", force, err)
  50. return
  51. }
  52. }
  53. }
  54. if err = s.PushForce(ctx, treeID, env, zone, build, version, hosts, 1); err != nil {
  55. tx.Rollback()
  56. return
  57. }
  58. tx.Commit()
  59. return
  60. }
  61. //ClearForce delete force.
  62. func (s *Service) ClearForce(ctx context.Context, treeID int64, env, zone, build string, hosts map[string]string) (err error) {
  63. var (
  64. app *model.App
  65. )
  66. if app, err = s.AppByTree(treeID, env, zone); err != nil {
  67. return
  68. }
  69. tx := s.dao.DB.Begin()
  70. for key, val := range hosts {
  71. if err = s.dao.DB.Where("app_id = ? and hostname = ?", app.ID, key).Delete(model.Force{}).Error; err != nil {
  72. tx.Rollback()
  73. log.Error("ClearForce hostname(%s) ip(%v) error(%v)", key, val, err)
  74. return
  75. }
  76. }
  77. if err = s.PushForce(ctx, treeID, env, zone, build, 0, hosts, 0); err != nil {
  78. tx.Rollback()
  79. return
  80. }
  81. tx.Commit()
  82. return
  83. }