github.com/coreos/mantle@v0.13.0/platform/machine/openstack/cluster.go (about)

     1  // Copyright 2018 Red Hat
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain a copy of the License at
     6  //
     7  //     http://www.apache.org/licenses/LICENSE-2.0
     8  //
     9  // Unless required by applicable law or agreed to in writing, software
    10  // distributed under the License is distributed on an "AS IS" BASIS,
    11  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    12  // See the License for the specific language governing permissions and
    13  // limitations under the License.
    14  
    15  package openstack
    16  
    17  import (
    18  	"crypto/rand"
    19  	"fmt"
    20  	"os"
    21  	"path/filepath"
    22  
    23  	"github.com/coreos/mantle/platform"
    24  	"github.com/coreos/mantle/platform/conf"
    25  )
    26  
    27  type cluster struct {
    28  	*platform.BaseCluster
    29  	flight *flight
    30  }
    31  
    32  func (oc *cluster) NewMachine(userdata *conf.UserData) (platform.Machine, error) {
    33  	conf, err := oc.RenderUserData(userdata, map[string]string{
    34  		"$public_ipv4":  "${COREOS_OPENSTACK_IPV4_PUBLIC}",
    35  		"$private_ipv4": "${COREOS_OPENSTACK_IPV4_LOCAL}",
    36  	})
    37  	if err != nil {
    38  		return nil, err
    39  	}
    40  
    41  	var keyname string
    42  	if !oc.RuntimeConf().NoSSHKeyInMetadata {
    43  		keyname = oc.flight.Name()
    44  	}
    45  	instance, err := oc.flight.api.CreateServer(oc.vmname(), keyname, conf.String())
    46  	if err != nil {
    47  		return nil, err
    48  	}
    49  
    50  	mach := &machine{
    51  		cluster: oc,
    52  		mach:    instance,
    53  	}
    54  
    55  	mach.dir = filepath.Join(oc.RuntimeConf().OutputDir, mach.ID())
    56  	if err := os.Mkdir(mach.dir, 0777); err != nil {
    57  		mach.Destroy()
    58  		return nil, err
    59  	}
    60  
    61  	confPath := filepath.Join(mach.dir, "user-data")
    62  	if err := conf.WriteFile(confPath); err != nil {
    63  		mach.Destroy()
    64  		return nil, err
    65  	}
    66  
    67  	if mach.journal, err = platform.NewJournal(mach.dir); err != nil {
    68  		mach.Destroy()
    69  		return nil, err
    70  	}
    71  
    72  	if err := platform.StartMachine(mach, mach.journal); err != nil {
    73  		mach.Destroy()
    74  		return nil, err
    75  	}
    76  
    77  	oc.AddMach(mach)
    78  
    79  	return mach, nil
    80  }
    81  
    82  func (oc *cluster) vmname() string {
    83  	b := make([]byte, 5)
    84  	rand.Read(b)
    85  	return fmt.Sprintf("%s-%x", oc.Name()[0:13], b)
    86  }
    87  
    88  func (oc *cluster) Destroy() {
    89  	oc.BaseCluster.Destroy()
    90  	oc.flight.DelCluster(oc)
    91  }