disable.go 1.9 KB

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