123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290 |
- package util
- import (
- "archive/tar"
- "bufio"
- "errors"
- "fmt"
- "io"
- "io/ioutil"
- "math/rand"
- "net/http"
- "os"
- "path"
- "strings"
- "gopkg.in/yaml.v2"
- log "github.com/Sirupsen/logrus"
- "github.com/docker/docker/pkg/mount"
- )
- var (
- letters = []rune("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ")
- ErrNoNetwork = errors.New("Networking not available to load resource")
- ErrNotFound = errors.New("Failed to find resource")
- )
- func GetOSType() string {
- f, err := os.Open("/etc/os-release")
- defer f.Close()
- if err != nil {
- return "busybox"
- }
- scanner := bufio.NewScanner(f)
- for scanner.Scan() {
- line := scanner.Text()
- if len(line) > 8 && line[:8] == "ID_LIKE=" {
- return line[8:]
- }
- }
- return "busybox"
- }
- func Remount(directory, options string) error {
- return mount.Mount("", directory, "", fmt.Sprintf("remount,%s", options))
- }
- func ExtractTar(archive string, dest string) error {
- f, err := os.Open(archive)
- if err != nil {
- return err
- }
- defer f.Close()
- input := tar.NewReader(f)
- for {
- header, err := input.Next()
- if err == io.EOF {
- break
- } else if err != nil {
- return err
- }
- if header == nil {
- break
- }
- fileInfo := header.FileInfo()
- fileName := path.Join(dest, header.Name)
- if fileInfo.IsDir() {
- //log.Debugf("DIR : %s", fileName)
- err = os.MkdirAll(fileName, fileInfo.Mode())
- if err != nil {
- return err
- }
- } else {
- //log.Debugf("FILE: %s", fileName)
- destFile, err := os.OpenFile(fileName, os.O_RDWR|os.O_CREATE|os.O_TRUNC, fileInfo.Mode())
- if err != nil {
- return err
- }
- _, err = io.Copy(destFile, input)
- // Not deferring, concerned about holding open too many files
- destFile.Close()
- if err != nil {
- return err
- }
- }
- }
- return nil
- }
- func Contains(values []string, value string) bool {
- if len(value) == 0 {
- return false
- }
- for _, i := range values {
- if i == value {
- return true
- }
- }
- return false
- }
- type ReturnsErr func() error
- func ShortCircuit(funcs ...ReturnsErr) error {
- for _, f := range funcs {
- err := f()
- if err != nil {
- return err
- }
- }
- return nil
- }
- type ErrWriter struct {
- w io.Writer
- Err error
- }
- func NewErrorWriter(w io.Writer) *ErrWriter {
- return &ErrWriter{
- w: w,
- }
- }
- func (e *ErrWriter) Write(buf []byte) *ErrWriter {
- if e.Err != nil {
- return e
- }
- _, e.Err = e.w.Write(buf)
- return e
- }
- func RandSeq(n int) string {
- b := make([]rune, n)
- for i := range b {
- b[i] = letters[rand.Intn(len(letters))]
- }
- return string(b)
- }
- func Convert(from, to interface{}) error {
- bytes, err := yaml.Marshal(from)
- if err != nil {
- return err
- }
- return yaml.Unmarshal(bytes, to)
- }
- func MergeBytes(left, right []byte) ([]byte, error) {
- leftMap := make(map[interface{}]interface{})
- rightMap := make(map[interface{}]interface{})
- err := yaml.Unmarshal(left, &leftMap)
- if err != nil {
- return nil, err
- }
- err = yaml.Unmarshal(right, &rightMap)
- if err != nil {
- return nil, err
- }
- MergeMaps(leftMap, rightMap)
- return yaml.Marshal(leftMap)
- }
- func MergeMaps(left, right map[interface{}]interface{}) {
- for k, v := range right {
- merged := false
- if existing, ok := left[k]; ok {
- if rightMap, ok := v.(map[interface{}]interface{}); ok {
- if leftMap, ok := existing.(map[interface{}]interface{}); ok {
- merged = true
- MergeMaps(leftMap, rightMap)
- }
- }
- }
- if !merged {
- left[k] = v
- }
- }
- }
- func GetServices(urls []string) ([]string, error) {
- result := []string{}
- for _, url := range urls {
- indexUrl := fmt.Sprintf("%s/index.yml", url)
- content, err := LoadResource(indexUrl, true, []string{})
- if err != nil {
- log.Errorf("Failed to load %s: %v", indexUrl, err)
- continue
- }
- services := make(map[string][]string)
- err = yaml.Unmarshal(content, &services)
- if err != nil {
- log.Errorf("Failed to unmarshal %s: %v", indexUrl, err)
- continue
- }
- if list, ok := services["services"]; ok {
- result = append(result, list...)
- }
- }
- return result, nil
- }
- func LoadResource(location string, network bool, urls []string) ([]byte, error) {
- var bytes []byte
- err := ErrNotFound
- if strings.HasPrefix(location, "http:/") || strings.HasPrefix(location, "https:/") {
- if !network {
- return nil, ErrNoNetwork
- }
- resp, err := http.Get(location)
- if err != nil {
- return nil, err
- }
- if resp.StatusCode != http.StatusOK {
- return nil, fmt.Errorf("non-200 http response: %d", resp.StatusCode)
- }
- defer resp.Body.Close()
- return ioutil.ReadAll(resp.Body)
- } else if strings.HasPrefix(location, "/") {
- return ioutil.ReadFile(location)
- } else if len(location) > 0 {
- for _, url := range urls {
- ymlUrl := fmt.Sprintf("%s/%s/%s.yml", url, location[0:1], location)
- bytes, err = LoadResource(ymlUrl, network, []string{})
- if err == nil {
- log.Debugf("Loaded %s from %s", location, ymlUrl)
- return bytes, nil
- }
- }
- }
- return nil, err
- }
- func GetValue(kvPairs []string, key string) string {
- if kvPairs == nil {
- return ""
- }
- prefix := key + "="
- for _, i := range kvPairs {
- if strings.HasPrefix(i, prefix) {
- return strings.TrimPrefix(i, prefix)
- }
- }
- return ""
- }
- func Map2KVPairs(m map[string]string) []string {
- r := make([]string, 0, len(m))
- for k, v := range m {
- r = append(r, k+"="+v)
- }
- return r
- }
- func KVPairs2Map(kvs []string) map[string]string {
- r := make(map[string]string, len(kvs))
- for _, kv := range kvs {
- s := strings.SplitN(kv, "=", 2)
- r[s[0]] = s[1]
- }
- return r
- }
|