2026-04-07 11:48:19 +08:00

70 lines
1.5 KiB
Go

package bootstrap
import (
"context"
"net/url"
"gorm.io/gorm"
"app-deploy-platform/backend/internal/config"
"app-deploy-platform/backend/internal/model"
)
func Seed(ctx context.Context, db *gorm.DB, cfg config.Config) error {
var hostCount int64
if err := db.WithContext(ctx).Model(&model.Host{}).Count(&hostCount).Error; err != nil {
return err
}
if hostCount > 0 {
return nil
}
for serviceName, serviceCfg := range cfg.Services {
for _, ref := range serviceCfg.Instances {
host := model.Host{
Name: ref.Name,
InstanceID: ref.InstanceID,
PrivateIP: ref.PrivateIP,
Role: serviceName,
Environment: cfg.Env,
TATOnline: true,
}
if err := db.WithContext(ctx).Create(&host).Error; err != nil {
return err
}
healthPath, readyPath := derivePaths(serviceCfg.HealthURL)
instance := model.ServiceInstance{
ServiceName: serviceName,
HostID: host.ID,
Port: serviceCfg.HTTPPort,
UnitName: serviceCfg.UnitName,
HealthPath: healthPath,
ReadyPath: readyPath,
}
if err := db.WithContext(ctx).Create(&instance).Error; err != nil {
return err
}
}
}
return nil
}
func derivePaths(healthURL string) (string, string) {
if healthURL == "" {
return "/health", "/ready"
}
parsed, err := url.Parse(healthURL)
if err != nil {
return "/health", "/ready"
}
readyPath := parsed.Path
if readyPath == "" {
readyPath = "/ready"
}
healthPath := "/health"
return healthPath, readyPath
}