hmdeploy/deployers/nginx.go
2025-04-04 12:22:30 +02:00

124 lines
2.6 KiB
Go

package deployers
import (
"context"
"fmt"
"path/filepath"
"gitea.thegux.fr/hmdeploy/connection"
"gitea.thegux.fr/hmdeploy/models"
"github.com/rs/zerolog/log"
)
// NginxDeployer handles the deployment of an Nginx configuration.
type NginxDeployer struct {
*deployer
conn connection.IConnection
}
var _ IDeployer = (*NginxDeployer)(nil)
func NewNginxDeployer(
ctx context.Context,
project *models.Project,
netInfo *models.HMNetInfo,
) (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.deployer = newDeployer(ctx, Nginx, project)
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) 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 {
nd.processing.Store(true)
defer nd.processing.Store(false)
select {
case <-nd.ctx.Done():
nd.errFlag = ErrContextDone
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("transferring nginx conf...")
if err := nd.conn.CopyFile(nginxPath, nginxConf); err != nil {
nd.setDone(err)
return err
}
log.Info().Str("nginx", nginxConf).Msg("nginx conf transferred with success")
return nil
}
func (nd *NginxDeployer) Deploy() (err error) {
nd.processing.Store(true)
defer nd.processing.Store(false)
select {
case <-nd.ctx.Done():
nd.errFlag = ErrContextDone
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,
),
)
nd.setDone(err)
if err == nil {
log.Info().Str("nginx", nginxConf).Msg("nginx conf successfully deployed")
}
return err
}