k3s/pkg/daemons/control/bootstrap.go

101 lines
2.1 KiB
Go
Raw Normal View History

2019-06-27 19:00:43 +00:00
package control
import (
"context"
"encoding/json"
"io/ioutil"
"os"
"path/filepath"
2019-06-27 19:00:43 +00:00
"github.com/pkg/errors"
2019-06-27 19:00:43 +00:00
"github.com/rancher/k3s/pkg/daemons/config"
"github.com/rancher/kine/pkg/client"
2019-06-30 19:39:54 +00:00
"github.com/sirupsen/logrus"
2019-06-27 19:00:43 +00:00
)
const (
k3sRuntimeEtcdPath = "/k3s/runtime"
)
2019-07-17 07:25:34 +00:00
// fetchBootstrapData copies the bootstrap data (certs, keys, passwords)
// from etcd to individual files specified by cfg.Runtime.
func fetchBootstrapData(ctx context.Context, cfg *config.Control, c client.Client) error {
2019-07-14 07:49:08 +00:00
logrus.Info("Fetching bootstrap data from etcd")
gr, err := c.Get(ctx, k3sRuntimeEtcdPath)
2019-06-27 19:00:43 +00:00
if err != nil {
return err
}
if gr.Modified == 0 {
2019-06-27 19:00:43 +00:00
return nil
}
2019-06-30 19:39:54 +00:00
paths, err := objToMap(&cfg.Runtime.ControlRuntimeBootstrap)
if err != nil {
return err
}
files := map[string][]byte{}
if err := json.Unmarshal(gr.Data, &files); err != nil {
2019-06-27 19:00:43 +00:00
return err
}
for pathKey, data := range files {
path, ok := paths[pathKey]
if !ok {
continue
}
if err := os.MkdirAll(filepath.Dir(path), 0700); err != nil {
return errors.Wrapf(err, "failed to mkdir %s", filepath.Dir(path))
}
2019-06-30 19:39:54 +00:00
if err := ioutil.WriteFile(path, data, 0700); err != nil {
return errors.Wrapf(err, "failed to write to %s", path)
}
2019-06-27 19:00:43 +00:00
}
2019-06-30 19:39:54 +00:00
return nil
}
// storeBootstrapData copies the bootstrap data in the opposite direction to
// fetchBootstrapData.
func storeBootstrapData(ctx context.Context, cfg *config.Control, client client.Client) error {
if cfg.BootstrapReadOnly {
return nil
2019-06-30 19:39:54 +00:00
}
paths, err := objToMap(&cfg.Runtime.ControlRuntimeBootstrap)
if err != nil {
return nil
2019-06-30 19:39:54 +00:00
}
2019-06-27 19:00:43 +00:00
dataMap := map[string][]byte{}
for pathKey, path := range paths {
if path == "" {
continue
}
data, err := ioutil.ReadFile(path)
if err != nil {
return errors.Wrapf(err, "failed to read %s", path)
}
dataMap[pathKey] = data
2019-06-30 19:39:54 +00:00
}
bytes, err := json.Marshal(dataMap)
if err != nil {
return err
2019-06-30 19:39:54 +00:00
}
return client.Put(ctx, k3sRuntimeEtcdPath, bytes)
2019-06-27 19:00:43 +00:00
}
func objToMap(obj interface{}) (map[string]string, error) {
bytes, err := json.Marshal(obj)
if err != nil {
return nil, err
2019-06-27 19:00:43 +00:00
}
data := map[string]string{}
return data, json.Unmarshal(bytes, &data)
2019-06-27 19:00:43 +00:00
}