hmdeploy/deployers/nginx.go
2025-04-03 13:37:43 +02:00

131 lines
2.7 KiB
Go

package deployers
import (
"context"
"fmt"
"path/filepath"
"github.com/rs/zerolog/log"
"gitea.thegux.fr/hmdeploy/connection"
"gitea.thegux.fr/hmdeploy/models"
)
type NginxDeployer struct {
ctx context.Context
conn connection.IConnection
project *models.Project
chDone chan struct{}
}
var _ IDeployer = (*NginxDeployer)(nil)
func NewNginxDeployer(ctx context.Context, netInfo *models.HMNetInfo, project *models.Project) (NginxDeployer, error) {
var nd NginxDeployer
conn, err := connection.NewSSHConn(netInfo.IP.String(), netInfo.SSH.User, netInfo.SSH.Port, netInfo.SSH.PrivKey)
if err != nil {
return nd, err
}
nd.conn = &conn
nd.project = project
nd.chDone = make(chan struct{}, 5)
nd.ctx = ctx
return nd, nil
}
func (nd *NginxDeployer) close() error {
return nd.conn.Close()
}
func (nd *NginxDeployer) clean() (err error) {
_, err = nd.conn.Execute("rm -f " + nd.project.Name + ".conf")
return
}
func (nd *NginxDeployer) setDone() {
nd.chDone <- struct{}{}
}
func (nd *NginxDeployer) Done() <-chan struct{} {
chDone := make(chan struct{})
go func() {
for {
select {
case <-nd.chDone:
chDone <- struct{}{}
return
case <-nd.ctx.Done():
chDone <- struct{}{}
return
}
}
}()
return chDone
}
func (nd *NginxDeployer) Clear() error {
log.Debug().Msg("clearing nginx deployment...")
if err := nd.clean(); err != nil {
log.Err(err).Msg("unable to clean nginx conf remotly")
}
if err := nd.close(); err != nil {
log.Err(err).Msg("unable to close nginx conn")
}
log.Debug().Msg("clear nginx deployment done")
return nil
}
func (nd *NginxDeployer) Build() error {
select {
case <-nd.ctx.Done():
nd.setDone()
return fmt.Errorf("%w, build nginx archive skipped", ErrContextDone)
default:
}
nginxPath := filepath.Join(nd.project.Dir, filepath.Base(nd.project.Deps.NginxFile))
nginxConf := nd.project.Name + ".conf"
log.Info().Str("nginx", nginxConf).Msg("transfering nginx conf...")
if err := nd.conn.CopyFile(nginxPath, nginxConf); err != nil {
nd.setDone()
return err
}
log.Info().Str("nginx", nginxConf).Msg("nginx conf transfered with success")
return nil
}
func (nd *NginxDeployer) Deploy() (err error) {
defer nd.setDone()
select {
case <-nd.ctx.Done():
return fmt.Errorf("%w, nginx deployment skipped", ErrContextDone)
default:
}
nginxConf := nd.project.Name + ".conf"
log.Info().Str("nginx", nginxConf).Msg("deploying nginx conf...")
_, err = nd.conn.Execute(
fmt.Sprintf(
"cp %s /etc/nginx/sites-available && ln -sf /etc/nginx/sites-available/%s /etc/nginx/sites-enabled/%s",
nginxConf, nginxConf, nginxConf,
),
)
log.Info().Str("nginx", nginxConf).Msg("nginx conf successfully deployed")
return err
}