// dockerLogsToFile dumps container logs to file
7917
func dockerLogsToFile(containerid string, numlines int) {
	// TODO: need to get logs from api

	fname := filepath.Join(os.TempDir(), fmt.Sprintf("%s.container.log", containerid))
	f, e := os.Create(fname)
	if e != nil {
		plog.WithError(e).WithFields(log.Fields{
			"file": fname,
		}).Debug("Unable to create container log file")
		return
	}
	defer f.Close()
	cmd := exec.Command("docker", "logs", "--tail", fmt.Sprintf("%d", numlines), containerid)
	cmd.Stdout = f
	cmd.Stderr = f
	if err := cmd.Run(); err != nil {
		plog.WithError(err).Debug("Unable to get logs for container")
		return
	}
	plog.WithFields(log.Fields{
		"file":  fname,
		"lines": numlines,
	}).Infof("Container log dumped to file")
}
947176
func Logs(dockerID string, args []string) error {
	if _, err := FindContainer(dockerID); err != nil {
		return err
	}

	var command []string = []string{"/usr/bin/docker", "logs"}
	if len(args) > 0 {
		command = append(command, args...)
	}
	command = append(command, dockerID)

	glog.V(1).Infof("exec logs command for container:%v command: %+v\n", dockerID, command)
	return syscall.Exec(command[0], command[0:], os.Environ())
}
1366778
func (f *RemoteRuntime) ReopenContainerLog(ctx context.Context, req *kubeapi.ReopenContainerLogRequest) (*kubeapi.ReopenContainerLogResponse, error) {
	err := f.RuntimeService.ReopenContainerLog(req.ContainerId)
	if err != nil {
		return nil, err
	}

	return &kubeapi.ReopenContainerLogResponse{}, nil
}
1211915
func (c *HyperClient) GetContainerLogs(container string) ([]byte, error) {
	req := types.ContainerLogsRequest{
		Container:  container,
		Follow:     false,
		Timestamps: false,
		Tail:       "",
		Since:      "",
		Stdout:     true,
		Stderr:     true,
	}
	stream, err := c.client.ContainerLogs(
		c.ctx,
		&req,
	)
	if err != nil {
		return nil, err
	}

	ret := []byte{}
	for {
		res, err := stream.Recv()
		if err == io.EOF {
			if req.Follow == true {
				continue
			}
			break
		}
		if err != nil {
			return nil, err
		}
		ret = append(ret, res.Log...)
	}

	return ret, nil
}
228601
func (z *Zipkin) HeadersToLog() []string {
	if !z.zipkinEnabled {
		return z.headersToLog
	}
	headersToLog := z.headersToLog
	if !contains(headersToLog, B3TraceIdHeader) {
		headersToLog = append(headersToLog, B3TraceIdHeader)
	}

	if !contains(headersToLog, B3SpanIdHeader) {
		headersToLog = append(headersToLog, B3SpanIdHeader)
	}

	if !contains(headersToLog, B3ParentSpanIdHeader) {
		headersToLog = append(headersToLog, B3ParentSpanIdHeader)
	}

	if !contains(headersToLog, B3Header) {
		headersToLog = append(headersToLog, B3Header)
	}

	return headersToLog
}
487256
func (we *WorkflowExecutor) saveLogToFile(mainCtrID, path string) error {
	outFile, err := os.Create(path)
	if err != nil {
		return errors.InternalWrapError(err)
	}
	defer func() { _ = outFile.Close() }()
	reader, err := we.RuntimeExecutor.GetOutputStream(mainCtrID, true)
	if err != nil {
		return err
	}
	defer func() { _ = reader.Close() }()
	_, err = io.Copy(outFile, reader)
	if err != nil {
		return errors.InternalWrapError(err)
	}
	return nil
}
312643
func openContainerFile(rootfs string, path string) (io.ReadCloser, error) {
	fp, err := symlink.FollowSymlinkInScope(filepath.Join(rootfs, path), rootfs)
	if err != nil {
		return nil, err
	}
	return os.Open(fp)
}
1271796
func CheckFileMounting() (err error) {
	cli, err := newClient()
	if err != nil {
		return fmt.Errorf("creating client: %v", err)
	}

	tempDir, err := ioutil.TempDir("", "")
	if err != nil {
		return fmt.Errorf("creating temp dir: %v", err)
	}
	defer os.RemoveAll(tempDir)

	fileName := "foo"

	file, err := os.Create(filepath.Join(tempDir, fileName))
	if err != nil {
		return fmt.Errorf("creating file: %v", err)
	}

	// write 1 KiB of random data to the file
	randData := make([]byte, 1<<10)
	if _, err = io.ReadFull(rand.Reader, randData); err != nil {
		return fmt.Errorf("reading random data: %v", err)
	}
	if _, err = file.Write(randData); err != nil {
		return fmt.Errorf("writing random data: %v", err)
	}

	targetDir := "/tmp/bar"
	targetFile := "/tmp/bar/" + fileName

	volumes := map[string]struct{}{targetDir: struct{}{}}
	bindings := []string{tempDir + ":" + targetDir}

	hostConfig := docker.HostConfig{Binds: bindings}

	config := &docker.ContainerConfig{
		Image:      "ubuntu:14.04",
		Cmd:        []string{"cat", targetFile},
		Volumes:    volumes,
		HostConfig: hostConfig,
	}
	cid, err := cli.CreateContainer(config, "filemounttest")
	if err != nil {
		return fmt.Errorf("creating container: %v", err)
	}
	defer func() {
		rcErr := cli.RemoveContainer(cid, true, false)
		if err == nil {
			err = rcErr
		} else if rcErr != nil {
			fmt.Fprintf(os.Stderr, "removing container %v\n", rcErr)
		}
	}()

	// attach to the container
	streamOpts := &docker.AttachOptions{Stream: true, Stdout: true, Stderr: true}
	stream, err := cli.Attach(cid, streamOpts)
	if err != nil {
		return err
	}
	defer stream.Close()

	// start the container
	err = cli.StartContainer(cid, &docker.HostConfig{})
	if err != nil {
		return err
	}

	var stderr bytes.Buffer
	var stdout bytes.Buffer
	if err = docker.SplitStream(stream, &stdout, &stderr); err != nil {
		return fmt.Errorf("reading stdout: %v", err)
	}

	// wait for the container to exit
	exitCode, err := cli.Wait(cid)
	if err != nil {
		return err
	}

	if exitCode != 0 {
		return fmt.Errorf("bad exit code %d %s", exitCode, stderr)
	}
	if bytes.Compare(stdout.Bytes(), randData) != 0 {
		return fmt.Errorf("mounted file did not match")
	}
	if sErr := stderr.String(); sErr != "" {
		return fmt.Errorf("expected no response from stderr, got '%s'", sErr)
	}

	return nil
}
1532
func ParseJSONFile(path string) (*Container, error) {
	if len(path) > 0 {
		cBytes, err := ioutil.ReadFile(path)
		if err != nil {
			return nil, err
		}

		container, err := ParseJSON(cBytes)
		if err != nil {
			return nil, err
		}

		return container, nil
	}
	return nil, ErrInvalidPath
}
852243
func (c *Client) GetDockerLogs(dockerID string) (string, error) {
	var logs string
	err := c.rpcClient.Call("Agent.GetDockerLogs", dockerID, &logs, 0)
	return logs, err
}
1354595
func (d Dockerfile) WriteTo(w io.Writer) (n int64, err error) {
	bw := bufio.NewWriter(w)
	defer bw.Flush()
	i, err := bw.WriteString(fmt.Sprintf("## RECREATED FROM IMAGE ON %s\n", time.Now().Format(time.RFC3339)))
	if err != nil {
		return n, err
	}
	n += int64(i)
	i, err = bw.WriteString(fmt.Sprintf("## %s:%s (%s)\n\n", d.Ref.Name, d.Ref.Tag, d.Ref.ID))
	if err != nil {
		return n, err
	}
	n += int64(i)
	for _, layer := range d.Layers {
		i, err = bw.WriteString(layer.DockerfileInstruction().String() + "\n")
		if err != nil {
			return n, err
		}
		n += int64(i)
	}
	return n, nil
}
236900
func createLogFile(logDir string, logFile string) (io.Writer, error) {
	if ok, err := dirExists(logDir); !ok {
		return nil, err
	}

	file, err := os.Create(path.Join(logDir, logFile))
	if err != nil {
		return nil, err
	}

	return file, nil
}
852547
func OpenLogFile(logFile string) *os.File {
	f, err := os.OpenFile(logFile, os.O_RDWR|os.O_CREATE|os.O_APPEND, 0666)
	if err != nil {
		fmt.Printf("error opening file: %v\n", err)
	}
	// at callee: defer f.Close()
	return f
}
1097459
func (r *runtimeVM) ReopenContainerLog(c *Container) error {
	logrus.Debug("runtimeVM.ReopenContainerLog() start")
	defer logrus.Debug("runtimeVM.ReopenContainerLog() end")

	return nil
}
1020150
func initFileLog(cfg *zaplog.FileLogConfig, logger *log.Logger) error {
	if st, err := os.Stat(cfg.Filename); err == nil {
		if st.IsDir() {
			return errors.New("can't use directory as log file name")
		}
	}
	if cfg.MaxSize == 0 {
		cfg.MaxSize = DefaultLogMaxSize
	}

	// use lumberjack to logrotate
	output := &lumberjack.Logger{
		Filename:   cfg.Filename,
		MaxSize:    int(cfg.MaxSize),
		MaxBackups: int(cfg.MaxBackups),
		MaxAge:     int(cfg.MaxDays),
		LocalTime:  true,
	}

	if logger == nil {
		log.SetOutput(output)
	} else {
		logger.Out = output
	}
	return nil
}
677892
func BuildDockerImage(serviceName string,
	dockerFilepath string,
	tags map[string]string,
	logger *logrus.Logger) error {

	return BuildDockerImageWithFlags(serviceName,
		dockerFilepath,
		tags,
		"",
		"",
		logger)
}
72401
func (ds *dockerService) ReopenContainerLog(_ context.Context, _ *runtimeapi.ReopenContainerLogRequest) (*runtimeapi.ReopenContainerLogResponse, error) {
	return nil, fmt.Errorf("docker does not support reopening container log files")
}