github.com/niedbalski/juju@v0.0.0-20190215020005-8ff100488e47/provider/lxd/upgrades.go (about)

     1  // Copyright 2017 Canonical Ltd.
     2  // Licensed under the AGPLv3, see LICENCE file for details.
     3  
     4  package lxd
     5  
     6  import (
     7  	"os"
     8  	"path"
     9  
    10  	"github.com/juju/errors"
    11  
    12  	"github.com/juju/juju/cloud"
    13  	jujupaths "github.com/juju/juju/juju/paths"
    14  	"github.com/juju/juju/juju/version"
    15  )
    16  
    17  // ReadLegacyCloudCredentials reads cloud credentials off disk for an old
    18  // LXD controller, and returns them as a cloud.Credential with the
    19  // certificate auth-type.
    20  //
    21  // If the credential files are missing from the filesystem, an error
    22  // satisfying errors.IsNotFound will be returned.
    23  func ReadLegacyCloudCredentials(readFile func(string) ([]byte, error)) (cloud.Credential, error) {
    24  	var (
    25  		jujuConfDir    = jujupaths.MustSucceed(jujupaths.ConfDir(version.SupportedLTS()))
    26  		clientCertPath = path.Join(jujuConfDir, "lxd-client.crt")
    27  		clientKeyPath  = path.Join(jujuConfDir, "lxd-client.key")
    28  		serverCertPath = path.Join(jujuConfDir, "lxd-server.crt")
    29  	)
    30  	readFileString := func(path string) (string, error) {
    31  		data, err := readFile(path)
    32  		if err != nil {
    33  			if os.IsNotExist(err) {
    34  				err = errors.NotFoundf("%s", path)
    35  			}
    36  			return "", errors.Trace(err)
    37  		}
    38  		return string(data), nil
    39  	}
    40  	clientCert, err := readFileString(clientCertPath)
    41  	if err != nil {
    42  		return cloud.Credential{}, errors.Annotate(err, "reading client certificate")
    43  	}
    44  	clientKey, err := readFileString(clientKeyPath)
    45  	if err != nil {
    46  		return cloud.Credential{}, errors.Annotate(err, "reading client key")
    47  	}
    48  	serverCert, err := readFileString(serverCertPath)
    49  	if err != nil {
    50  		return cloud.Credential{}, errors.Annotate(err, "reading server certificate")
    51  	}
    52  	return cloud.NewCredential(cloud.CertificateAuthType, map[string]string{
    53  		credAttrServerCert: serverCert,
    54  		credAttrClientCert: clientCert,
    55  		credAttrClientKey:  clientKey,
    56  	}), nil
    57  }