github.com/GoogleContainerTools/skaffold@v1.39.18/pkg/skaffold/sync/docker.go (about) 1 /* 2 Copyright 2021 The Skaffold Authors 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package sync 18 19 import ( 20 "context" 21 "fmt" 22 "io" 23 "os/exec" 24 25 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/output/log" 26 "github.com/GoogleContainerTools/skaffold/pkg/skaffold/util" 27 ) 28 29 type ContainerSyncer struct{} 30 31 func NewContainerSyncer() *ContainerSyncer { 32 return &ContainerSyncer{} 33 } 34 35 func (s *ContainerSyncer) Sync(ctx context.Context, _ io.Writer, item *Item) error { 36 if len(item.Copy) > 0 { 37 log.Entry(ctx).Info("Copying files:", item.Copy, "to", item.Image) 38 if _, err := util.RunCmdOut(ctx, s.copyFileFn(ctx, item.Artifact.ImageName, item.Copy)); err != nil { 39 return fmt.Errorf("copying files: %w", err) 40 } 41 } 42 43 if len(item.Delete) > 0 { 44 log.Entry(ctx).Info("Deleting files:", item.Delete, "from", item.Image) 45 if _, err := util.RunCmdOut(ctx, s.deleteFileFn(ctx, item.Artifact.ImageName, item.Delete)); err != nil { 46 return fmt.Errorf("deleting files: %w", err) 47 } 48 } 49 50 return nil 51 } 52 53 func (s *ContainerSyncer) deleteFileFn(ctx context.Context, containerName string, files syncMap) *exec.Cmd { 54 var args []string 55 args = append(args, "exec", "-i", containerName, "rm", "-rf", "--") 56 for _, dsts := range files { 57 args = append(args, dsts...) 58 } 59 return exec.CommandContext(ctx, "docker", args...) 60 } 61 62 func (s *ContainerSyncer) copyFileFn(ctx context.Context, containerName string, files syncMap) *exec.Cmd { 63 reader, writer := io.Pipe() 64 go func() { 65 if err := util.CreateMappedTar(writer, "/", files); err != nil { 66 writer.CloseWithError(err) 67 } else { 68 writer.Close() 69 } 70 }() 71 72 copyCmd := exec.CommandContext(ctx, "docker", "exec", "-i", containerName, "tar", "xmf", "-", "-C", "/", "--no-same-owner") 73 copyCmd.Stdin = reader 74 return copyCmd 75 }