github.com/johnnyeven/libtools@v0.0.0-20191126065708-61829c1adf46/service/dockerizier/docker_compose_yml.go (about)

     1  package dockerizier
     2  
     3  import (
     4  	"regexp"
     5  	"sort"
     6  	"strings"
     7  
     8  	"gopkg.in/yaml.v2"
     9  
    10  	"github.com/johnnyeven/libtools/conf"
    11  	"github.com/johnnyeven/libtools/docker"
    12  )
    13  
    14  func toDockerComposeYML(envVars conf.EnvVars, serviceName string) string {
    15  	d := docker.NewDockerCompose()
    16  	s := docker.NewService(Image)
    17  
    18  	keys := make([]string, 0)
    19  	for key := range envVars {
    20  		keys = append(keys, key)
    21  	}
    22  	sort.Strings(keys)
    23  
    24  	upstreams := make([]string, 0)
    25  
    26  	for _, key := range keys {
    27  		envVar := envVars[key]
    28  		if envVar.CanConfig {
    29  			s = s.SetEnvironment(key, `${`+key+`}`)
    30  		}
    31  		strValue := envVar.GetValue(false)
    32  		if strValue == "./swagger.json" {
    33  			s = s.SetLabel("lb.g7pay.expose80", "/"+getBaseURL(serviceName))
    34  			s = s.SetLabel("base_path", "/"+getBaseURL(serviceName))
    35  		}
    36  
    37  		if envVar.FallbackValue != nil {
    38  			if envVar.IsUpstream {
    39  				if envVar.CanConfig {
    40  					upstreams = append(upstreams, `${`+key+`}`)
    41  				} else {
    42  					upstreams = append(upstreams, envVar.GetFallbackValue(false))
    43  				}
    44  			}
    45  		}
    46  	}
    47  
    48  	if len(upstreams) > 0 {
    49  		s = s.SetLabel("upstreams", strings.Join(upstreams, ","))
    50  	}
    51  
    52  	s = s.SetEnvironment("GOENV", `${GOENV}`)
    53  
    54  	s = s.SetLabel("io.rancher.container.pull_image", "always")
    55  	s = s.SetLabel("io.rancher.container.start_once", "true")
    56  
    57  	s = s.SetLabel("project.description", "${PROJECT_DESCRIPTION}")
    58  	s = s.SetLabel("project.group", "${PROJECT_GROUP}")
    59  	s = s.SetLabel("project.name", "${PROJECT_NAME}")
    60  	s = s.SetLabel("project.version", "${PROJECT_VERSION}")
    61  
    62  	s = s.AddDns("169.254.169.250", "rancher.internal")
    63  
    64  	d = d.AddService(serviceName, s)
    65  	bytes, _ := yaml.Marshal(d)
    66  	return string(bytes)
    67  }
    68  
    69  func getBaseURL(name string) string {
    70  	pathReg := regexp.MustCompile("service-([xi]-)?(.+)")
    71  	return pathReg.ReplaceAllStringFunc(name, func(s string) string {
    72  		result := pathReg.FindAllStringSubmatch(s, -1)
    73  		if len(result[0]) == 3 {
    74  			return result[0][2]
    75  		}
    76  		return result[0][1]
    77  	})
    78  }