github.com/feiyang21687/docker@v1.5.0/api/common.go (about)

     1  package api
     2  
     3  import (
     4  	"fmt"
     5  	"mime"
     6  	"os"
     7  	"path/filepath"
     8  	"strings"
     9  
    10  	log "github.com/Sirupsen/logrus"
    11  	"github.com/docker/docker/engine"
    12  	"github.com/docker/docker/pkg/parsers"
    13  	"github.com/docker/docker/pkg/version"
    14  	"github.com/docker/libtrust"
    15  )
    16  
    17  const (
    18  	APIVERSION            version.Version = "1.17"
    19  	DEFAULTHTTPHOST                       = "127.0.0.1"
    20  	DEFAULTUNIXSOCKET                     = "/var/run/docker.sock"
    21  	DefaultDockerfileName string          = "Dockerfile"
    22  )
    23  
    24  func ValidateHost(val string) (string, error) {
    25  	host, err := parsers.ParseHost(DEFAULTHTTPHOST, DEFAULTUNIXSOCKET, val)
    26  	if err != nil {
    27  		return val, err
    28  	}
    29  	return host, nil
    30  }
    31  
    32  //TODO remove, used on < 1.5 in getContainersJSON
    33  func DisplayablePorts(ports *engine.Table) string {
    34  	result := []string{}
    35  	ports.SetKey("PublicPort")
    36  	ports.Sort()
    37  	for _, port := range ports.Data {
    38  		if port.Get("IP") == "" {
    39  			result = append(result, fmt.Sprintf("%d/%s", port.GetInt("PrivatePort"), port.Get("Type")))
    40  		} else {
    41  			result = append(result, fmt.Sprintf("%s:%d->%d/%s", port.Get("IP"), port.GetInt("PublicPort"), port.GetInt("PrivatePort"), port.Get("Type")))
    42  		}
    43  	}
    44  	return strings.Join(result, ", ")
    45  }
    46  
    47  func MatchesContentType(contentType, expectedType string) bool {
    48  	mimetype, _, err := mime.ParseMediaType(contentType)
    49  	if err != nil {
    50  		log.Errorf("Error parsing media type: %s error: %s", contentType, err.Error())
    51  	}
    52  	return err == nil && mimetype == expectedType
    53  }
    54  
    55  // LoadOrCreateTrustKey attempts to load the libtrust key at the given path,
    56  // otherwise generates a new one
    57  func LoadOrCreateTrustKey(trustKeyPath string) (libtrust.PrivateKey, error) {
    58  	err := os.MkdirAll(filepath.Dir(trustKeyPath), 0700)
    59  	if err != nil {
    60  		return nil, err
    61  	}
    62  	trustKey, err := libtrust.LoadKeyFile(trustKeyPath)
    63  	if err == libtrust.ErrKeyFileDoesNotExist {
    64  		trustKey, err = libtrust.GenerateECP256PrivateKey()
    65  		if err != nil {
    66  			return nil, fmt.Errorf("Error generating key: %s", err)
    67  		}
    68  		if err := libtrust.SaveKey(trustKeyPath, trustKey); err != nil {
    69  			return nil, fmt.Errorf("Error saving key file: %s", err)
    70  		}
    71  	} else if err != nil {
    72  		return nil, fmt.Errorf("Error loading key file %s: %s", trustKeyPath, err)
    73  	}
    74  	return trustKey, nil
    75  }