github.com/microsoft/moc@v0.17.1/pkg/providerid/providerid.go (about)

     1  // Copyright (c) Microsoft Corporation.
     2  // Licensed under the Apache v2.0 license.
     3  
     4  package providerid
     5  
     6  import (
     7  	"strings"
     8  
     9  	"github.com/microsoft/moc/pkg/errors"
    10  )
    11  
    12  const (
    13  	ProviderName     string = "moc"
    14  	ProviderIDPrefix string = ProviderName + "://"
    15  )
    16  
    17  type HostType string
    18  
    19  const (
    20  	HostTypeVM        HostType = "vm"
    21  	HostTypeBareMetal HostType = "baremetal"
    22  )
    23  
    24  func FormatInstanceID(hostType HostType, machineName string) string {
    25  	switch hostType {
    26  	case HostTypeVM:
    27  		// Don't append the host type for VMs to maintain consistency with previous versions.
    28  		return machineName
    29  
    30  	default:
    31  		return string(hostType) + "/" + machineName
    32  	}
    33  }
    34  
    35  func FormatProviderID(hostType HostType, machineName string) string {
    36  	return ProviderIDPrefix + FormatInstanceID(hostType, machineName)
    37  }
    38  
    39  func ParseProviderID(providerID string) (HostType, string, error) {
    40  	if providerID == "" {
    41  		return "", "", errors.Wrap(errors.InvalidInput, "providerID is empty")
    42  	}
    43  
    44  	withoutPrefix := strings.TrimPrefix(providerID, ProviderIDPrefix)
    45  	if withoutPrefix == providerID {
    46  		return "", "", errors.Wrapf(errors.InvalidInput, "providerID is missing expected prefix (%s): %s", ProviderIDPrefix, providerID)
    47  	}
    48  
    49  	withoutPrefix = strings.TrimSpace(withoutPrefix)
    50  
    51  	// Parse out the host type.
    52  	split := strings.SplitN(withoutPrefix, "/", 2)
    53  	if len(split) < 1 {
    54  		return "", "", errors.Wrap(errors.InvalidInput, "providerID is invalid")
    55  	}
    56  
    57  	if len(split) == 1 {
    58  		// VMs don't have the host type prefix.
    59  		return HostTypeVM, split[0], nil
    60  	}
    61  
    62  	hostType := HostType(split[0])
    63  	machineName := split[1]
    64  
    65  	if hostType != HostTypeBareMetal {
    66  		return "", "", errors.Wrapf(errors.InvalidInput, "providerID contains unknown host type: %s", string(hostType))
    67  	}
    68  
    69  	return hostType, machineName, nil
    70  }