You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
96 lines
1.8 KiB
96 lines
1.8 KiB
package zones |
|
|
|
import ( |
|
"bytes" |
|
"fmt" |
|
"io" |
|
"strings" |
|
) |
|
|
|
// WriteEnv generates environment variables for shell scripts |
|
func (m *Zones) WriteEnv(w io.Writer) error { |
|
var buf bytes.Buffer |
|
|
|
m.writeEnvVarFn(&buf, genEnvZones, "ZONES") |
|
m.ForEachZone(func(z *Zone) bool { |
|
m.writeEnvZone(&buf, z) |
|
return false |
|
}) |
|
|
|
_, err := buf.WriteTo(w) |
|
return err |
|
} |
|
|
|
func (m *Zones) writeEnvZone(w io.Writer, z *Zone) { |
|
zoneID := z.ID |
|
|
|
// ZONE{zoneID} |
|
m.writeEnvVar(w, genEnvZoneNodes(z), "ZONE%v", zoneID) |
|
|
|
// ZONE{zoneID}_NAME |
|
m.writeEnvVar(w, z.Name, "ZONE%v_%s", zoneID, "NAME") |
|
|
|
// ZONE{zoneID}_GW |
|
gatewayID := getRingZeroGatewayID(z) |
|
if gatewayID > 0 { |
|
m.writeEnvVar(w, fmt.Sprintf("%v", gatewayID), "ZONE%v_%s", zoneID, "GW") |
|
|
|
// ZONE{zoneID}_IP |
|
if ip, ok := RingZeroAddress(zoneID, gatewayID); ok { |
|
m.writeEnvVar(w, ip.String(), "ZONE%v_%s", zoneID, "IP") |
|
} |
|
} |
|
} |
|
|
|
func (m *Zones) writeEnvVarFn(w io.Writer, fn func(*Zones) string, name string, args ...any) { |
|
var value string |
|
|
|
if fn != nil { |
|
value = fn(m) |
|
} |
|
|
|
m.writeEnvVar(w, value, name, args...) |
|
} |
|
|
|
func (*Zones) writeEnvVar(w io.Writer, value string, name string, args ...any) { |
|
if len(args) > 0 { |
|
name = fmt.Sprintf(name, args...) |
|
} |
|
|
|
if name != "" { |
|
value = strings.TrimSpace(value) |
|
|
|
_, _ = fmt.Fprintf(w, "%s=%q\n", name, value) |
|
} |
|
} |
|
|
|
func genEnvZones(m *Zones) string { |
|
s := make([]string, 0, len(m.Zones)) |
|
for _, z := range m.Zones { |
|
s = append(s, fmt.Sprintf("%v", z.ID)) |
|
} |
|
|
|
return strings.Join(s, " ") |
|
} |
|
|
|
func genEnvZoneNodes(z *Zone) string { |
|
s := make([]string, 0, len(z.Machines)) |
|
for _, p := range z.Machines { |
|
s = append(s, p.Name) |
|
} |
|
return strings.Join(s, " ") |
|
} |
|
|
|
func getRingZeroGatewayID(z *Zone) int { |
|
var gatewayID int |
|
|
|
z.ForEachMachine(func(p *Machine) bool { |
|
if p.IsGateway() { |
|
gatewayID = p.ID |
|
} |
|
|
|
return gatewayID != 0 |
|
}) |
|
|
|
return gatewayID |
|
}
|
|
|