github.com/coreos/mantle@v0.13.0/platform/machine/packet/flight.go (about)

     1  // Copyright 2017 CoreOS, Inc.
     2  // Copyright 2018 Red Hat
     3  //
     4  // Licensed under the Apache License, Version 2.0 (the "License");
     5  // you may not use this file except in compliance with the License.
     6  // You may obtain a copy of the License at
     7  //
     8  //     http://www.apache.org/licenses/LICENSE-2.0
     9  //
    10  // Unless required by applicable law or agreed to in writing, software
    11  // distributed under the License is distributed on an "AS IS" BASIS,
    12  // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  // See the License for the specific language governing permissions and
    14  // limitations under the License.
    15  
    16  package packet
    17  
    18  import (
    19  	"github.com/coreos/pkg/capnslog"
    20  
    21  	ctplatform "github.com/coreos/container-linux-config-transpiler/config/platform"
    22  	"github.com/coreos/mantle/platform"
    23  	"github.com/coreos/mantle/platform/api/packet"
    24  )
    25  
    26  const (
    27  	Platform platform.Name = "packet"
    28  )
    29  
    30  var (
    31  	plog = capnslog.NewPackageLogger("github.com/coreos/mantle", "platform/machine/packet")
    32  )
    33  
    34  type flight struct {
    35  	*platform.BaseFlight
    36  	api      *packet.API
    37  	sshKeyID string
    38  }
    39  
    40  func NewFlight(opts *packet.Options) (platform.Flight, error) {
    41  	api, err := packet.New(opts)
    42  	if err != nil {
    43  		return nil, err
    44  	}
    45  
    46  	bf, err := platform.NewBaseFlight(opts.Options, Platform, ctplatform.Packet)
    47  	if err != nil {
    48  		return nil, err
    49  	}
    50  
    51  	pf := &flight{
    52  		BaseFlight: bf,
    53  		api:        api,
    54  	}
    55  
    56  	keys, err := pf.Keys()
    57  	if err != nil {
    58  		pf.Destroy()
    59  		return nil, err
    60  	}
    61  	pf.sshKeyID, err = pf.api.AddKey(pf.Name(), keys[0].String())
    62  	if err != nil {
    63  		pf.Destroy()
    64  		return nil, err
    65  	}
    66  
    67  	return pf, nil
    68  }
    69  
    70  func (pf *flight) NewCluster(rconf *platform.RuntimeConfig) (platform.Cluster, error) {
    71  	bc, err := platform.NewBaseCluster(pf.BaseFlight, rconf)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	pc := &cluster{
    77  		BaseCluster: bc,
    78  		flight:      pf,
    79  	}
    80  	if !rconf.NoSSHKeyInMetadata {
    81  		pc.sshKeyID = pf.sshKeyID
    82  	}
    83  
    84  	pf.AddCluster(pc)
    85  
    86  	return pc, nil
    87  }
    88  
    89  func (pf *flight) Destroy() {
    90  	if pf.sshKeyID != "" {
    91  		if err := pf.api.DeleteKey(pf.sshKeyID); err != nil {
    92  			plog.Errorf("Error deleting key %v: %v", pf.sshKeyID, err)
    93  		}
    94  	}
    95  
    96  	pf.BaseFlight.Destroy()
    97  }