github.com/jonsyu1/godel@v0.0.0-20171017211503-64567a0cf169/apps/distgo/cmd/docker/sls_image.go (about) 1 // Copyright 2016 Palantir Technologies, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package docker 16 17 import ( 18 "bytes" 19 "encoding/base64" 20 "fmt" 21 "io" 22 "io/ioutil" 23 "os" 24 "os/exec" 25 "path" 26 27 "github.com/pkg/errors" 28 29 "github.com/palantir/godel/apps/distgo/params" 30 "github.com/palantir/godel/apps/distgo/pkg/script" 31 ) 32 33 const ( 34 ManifestLabel = "com.palantir.sls.manifest" 35 ConfigurationLabel = "com.palantir.sls.configuration" 36 ConfigurationFileName = "configuration.yml" 37 ) 38 39 type slsImageBuilder struct { 40 image *params.DockerImage 41 info *params.SLSDockerImageInfo 42 } 43 44 func (sib *slsImageBuilder) build(buildSpec params.ProductBuildSpecWithDeps, stdout io.Writer) error { 45 contextDir := path.Join(buildSpec.Spec.ProjectDir, sib.image.ContextDir) 46 configFile := path.Join(contextDir, ConfigurationFileName) 47 var args []string 48 args = append(args, "build") 49 args = append(args, "--tag", fmt.Sprintf("%s:%s", sib.image.Repository, sib.image.Tag)) 50 manifest, err := params.GetManifest(sib.info.GroupID, buildSpec.Spec.ProductName, buildSpec.Spec.ProductVersion, sib.info.ProuductType, sib.info.Extensions) 51 if err != nil { 52 return errors.Wrap(err, "Failed to get manifest for the image") 53 } 54 args = append(args, "--label", fmt.Sprintf("%s=%s", ManifestLabel, base64.StdEncoding.EncodeToString([]byte(manifest)))) 55 if _, err := os.Stat(configFile); err == nil { 56 content, err := ioutil.ReadFile(configFile) 57 if err != nil { 58 return errors.Wrapf(err, "Failed to read the file %s", configFile) 59 } 60 args = append(args, "--label", fmt.Sprintf("%s=%s", ConfigurationLabel, base64.StdEncoding.EncodeToString(content))) 61 } 62 buildArgs, err := script.GetBuildArgs(buildSpec.Spec, sib.image.BuildArgsScript) 63 if err != nil { 64 return err 65 } 66 args = append(args, buildArgs...) 67 args = append(args, contextDir) 68 69 buildCmd := exec.Command("docker", args...) 70 bufWriter := &bytes.Buffer{} 71 buildCmd.Stdout = io.MultiWriter(stdout, bufWriter) 72 buildCmd.Stderr = bufWriter 73 if err := buildCmd.Run(); err != nil { 74 return errors.Wrap(err, fmt.Sprintf("docker build failed with error:\n%s\n", bufWriter.String())) 75 } 76 return nil 77 }