disable.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package site
  2. import (
  3. "fmt"
  4. "github.com/0xJacky/Nginx-UI/internal/nginx"
  5. "github.com/0xJacky/Nginx-UI/internal/notification"
  6. "github.com/0xJacky/Nginx-UI/model"
  7. "github.com/go-resty/resty/v2"
  8. "github.com/uozi-tech/cosy/logger"
  9. "net/http"
  10. "os"
  11. "runtime"
  12. "sync"
  13. )
  14. // Disable disables a site by removing the symlink in sites-enabled
  15. func Disable(name string) (err error) {
  16. enabledConfigFilePath := nginx.GetConfPath("sites-enabled", name)
  17. _, err = os.Stat(enabledConfigFilePath)
  18. if err != nil {
  19. return
  20. }
  21. err = os.Remove(enabledConfigFilePath)
  22. if err != nil {
  23. return
  24. }
  25. // delete auto cert record
  26. certModel := model.Cert{Filename: name}
  27. err = certModel.Remove()
  28. if err != nil {
  29. return
  30. }
  31. output := nginx.Reload()
  32. if nginx.GetLogLevel(output) > nginx.Warn {
  33. return fmt.Errorf("%s", output)
  34. }
  35. go syncDisable(name)
  36. return
  37. }
  38. func syncDisable(name string) {
  39. nodes := getSyncNodes(name)
  40. wg := &sync.WaitGroup{}
  41. wg.Add(len(nodes))
  42. for _, node := range nodes {
  43. go func() {
  44. defer func() {
  45. if err := recover(); err != nil {
  46. buf := make([]byte, 1024)
  47. runtime.Stack(buf, false)
  48. logger.Error(err)
  49. }
  50. }()
  51. defer wg.Done()
  52. client := resty.New()
  53. client.SetBaseURL(node.URL)
  54. resp, err := client.R().
  55. SetHeader("X-Node-Secret", node.Token).
  56. Post(fmt.Sprintf("/api/sites/%s/disable", name))
  57. if err != nil {
  58. notification.Error("Disable Remote Site Error", "", err.Error())
  59. return
  60. }
  61. if resp.StatusCode() != http.StatusOK {
  62. notification.Error("Disable Remote Site Error", "Disable site %{name} from %{node} failed", NewSyncResult(node.Name, name, resp))
  63. return
  64. }
  65. notification.Success("Disable Remote Site Success", "Disable site %{name} from %{node} successfully", NewSyncResult(node.Name, name, resp))
  66. }()
  67. }
  68. wg.Wait()
  69. }