|
| 1 | +package phase |
| 2 | + |
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "fmt" |
| 6 | + "io" |
| 7 | + |
| 8 | + "github.com/k0sproject/k0sctl/pkg/apis/k0sctl.k0sproject.io/v1beta1" |
| 9 | + "github.com/k0sproject/k0sctl/pkg/apis/k0sctl.k0sproject.io/v1beta1/cluster" |
| 10 | + "github.com/k0sproject/rig/exec" |
| 11 | + log "github.com/sirupsen/logrus" |
| 12 | +) |
| 13 | + |
| 14 | +// ApplyManifests is a phase that applies additional manifests to the cluster |
| 15 | +type ApplyManifests struct { |
| 16 | + GenericPhase |
| 17 | + leader *cluster.Host |
| 18 | +} |
| 19 | + |
| 20 | +// Title for the phase |
| 21 | +func (p *ApplyManifests) Title() string { |
| 22 | + return "Apply additional manifests" |
| 23 | +} |
| 24 | + |
| 25 | +// Prepare the phase |
| 26 | +func (p *ApplyManifests) Prepare(config *v1beta1.Cluster) error { |
| 27 | + p.Config = config |
| 28 | + p.leader = p.Config.Spec.K0sLeader() |
| 29 | + |
| 30 | + return nil |
| 31 | +} |
| 32 | + |
| 33 | +// ShouldRun is true when there are additional manifests to apply |
| 34 | +func (p *ApplyManifests) ShouldRun() bool { |
| 35 | + return len(p.Config.Metadata.Manifests) > 0 |
| 36 | +} |
| 37 | + |
| 38 | +// Run the phase |
| 39 | +func (p *ApplyManifests) Run() error { |
| 40 | + for name, content := range p.Config.Metadata.Manifests { |
| 41 | + if err := p.apply(name, content); err != nil { |
| 42 | + return err |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + return nil |
| 47 | +} |
| 48 | + |
| 49 | +func (p *ApplyManifests) apply(name string, content []byte) error { |
| 50 | + if !p.IsWet() { |
| 51 | + p.DryMsgf(p.leader, "apply manifest %s (%d bytes)", name, len(content)) |
| 52 | + return nil |
| 53 | + } |
| 54 | + |
| 55 | + log.Infof("%s: apply manifest %s (%d bytes)", p.leader, name, len(content)) |
| 56 | + kubectlCmd := p.leader.Configurer.KubectlCmdf(p.leader, p.leader.K0sDataDir(), "apply -f -") |
| 57 | + var stdout, stderr bytes.Buffer |
| 58 | + |
| 59 | + cmd, err := p.leader.ExecStreams(kubectlCmd, io.NopCloser(bytes.NewReader(content)), &stdout, &stderr, exec.Sudo(p.leader)) |
| 60 | + if err != nil { |
| 61 | + return fmt.Errorf("failed to run apply for manifest %s: %w", name, err) |
| 62 | + } |
| 63 | + if err := cmd.Wait(); err != nil { |
| 64 | + log.Errorf("%s: kubectl apply failed for manifest %s", p.leader, name) |
| 65 | + log.Errorf("%s: kubectl apply stderr: %s", p.leader, stderr.String()) |
| 66 | + } |
| 67 | + log.Infof("%s: kubectl apply: %s", p.leader, stdout.String()) |
| 68 | + return nil |
| 69 | +} |
0 commit comments