// WriteFile is an implementation of the file system API interface
344798
func (fsh *Handler) WriteFile(file string, data []byte) error {
	fileObj, err := os.OpenFile(file, os.O_TRUNC|os.O_WRONLY, os.ModePerm)
	if err != nil {
		return fmt.Errorf("failed to open status file %s for writing: %v", file, err)
	}
	defer fileObj.Close()
	if _, err := fileObj.Write(data); err != nil {
		return fmt.Errorf("failed to write status file %s for writing: %v", file, err)
	}
	return nil
}
1182619
func (fsh *Handler) CreateFile(file string) error {
	path, _ := filepath.Split(file)
	// Create path at first if necessary
	if path != "" {
		if err := os.MkdirAll(path, os.ModePerm); err != nil {
			return errors.Errorf("failed to create path for file %s: %v", file, err)
		}
	}
	sf, err := os.Create(file)
	if err != nil {
		return errors.Errorf("failed to create file %s: %v", file, err)
	}
	return sf.Close()
}
520208
func (cert *Certificate) WriteToDERFile(filename string) (err error) {
	certOut, err := os.Create(filename)
	if err != nil {
		return fmt.Errorf("Failed to open %s for writing: %s", filename, err)
	}
	defer func() {
		if err := certOut.Close(); err != nil {
			log.Debugf("Unable to close file: %v", err)
		}
	}()
	_, err = certOut.Write(cert.derBytes)
	return err
}
383256
func (key *PrivateKey) WriteToFile(filename string) (err error) {
	keyOut, err := os.OpenFile(filename, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return fmt.Errorf("Failed to open %s for writing: %s", filename, err)
	}
	if err := pem.Encode(keyOut, key.pemBlock()); err != nil {
		return fmt.Errorf("Unable to PEM encode private key: %s", err)
	}
	if err := keyOut.Close(); err != nil {
		log.Debugf("Unable to close file: %v", err)
	}
	return
}
404517
func (s ServiceInfo) WriteFile(path string, log logger.Logger) error {
	out, err := json.MarshalIndent(s, "", "  ")
	if err != nil {
		return err
	}

	file := NewFile(path, []byte(out), 0644)
	return file.Save(log)
}
895149
func WriteFile(f *File, root string) (string, error) {
	if f.Encoding != "" {
		return "", fmt.Errorf("Unable to write file with encoding %s", f.Encoding)
	}

	fullpath := path.Join(root, f.Path)
	dir := path.Dir(fullpath)
	log.Printf("Writing file to %q", fullpath)

	if err := EnsureDirectoryExists(dir); err != nil {
		return "", err
	}

	perm, err := f.Permissions()
	if err != nil {
		return "", err
	}

	var tmp *os.File
	// Create a temporary file in the same directory to ensure it's on the same filesystem
	if tmp, err = ioutil.TempFile(dir, "cloudinit-temp"); err != nil {
		return "", err
	}

	if err := ioutil.WriteFile(tmp.Name(), []byte(f.Content), perm); err != nil {
		return "", err
	}

	if err := tmp.Close(); err != nil {
		return "", err
	}

	// Ensure the permissions are as requested (since WriteFile can be affected by sticky bit)
	if err := os.Chmod(tmp.Name(), perm); err != nil {
		return "", err
	}

	if f.Owner != "" {
		// We shell out since we don't have a way to look up unix groups natively
		cmd := exec.Command("chown", f.Owner, tmp.Name())
		if err := cmd.Run(); err != nil {
			return "", err
		}
	}

	if err := os.Rename(tmp.Name(), fullpath); err != nil {
		return "", err
	}

	log.Printf("Wrote file to %q", fullpath)
	return fullpath, nil
}
1108377
func (client *storageRESTClient) AppendFile(volume, path string, buffer []byte) error {
	values := make(url.Values)
	values.Set(storageRESTVolume, volume)
	values.Set(storageRESTFilePath, path)
	reader := bytes.NewBuffer(buffer)
	respBody, err := client.call(storageRESTMethodAppendFile, values, reader, -1)
	defer http.DrainBody(respBody)
	return err
}
1157271
func (cert *Certificate) WriteToFile(filename string) (err error) {
	certOut, err := os.Create(filename)
	if err != nil {
		return fmt.Errorf("Failed to open %s for writing: %s", filename, err)
	}
	defer func() {
		if err := certOut.Close(); err != nil {
			log.Debugf("Unable to close file: %v", err)
		}
	}()
	return pem.Encode(certOut, cert.pemBlock())
}
1338385
func WriteTokenFile(fpath string, tok *oauth2.Token) error {
	f, err := os.OpenFile(fpath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0600)
	if err != nil {
		return errors.Wrap(err, "Unable to write OAuth token")
	}
	defer f.Close()
	return json.NewEncoder(f).Encode(tok)
}
310274
func (c *DiskTokenCache) writeCacheFile(cache *cacheFile, now time.Time) error {
	// Throw away old entries.
	cleaned := *cache
	cleaned.Cache = make([]*cacheFileEntry, 0, len(cache.Cache))
	cleaned.LastUpdate = now
	for _, entry := range cache.Cache {
		if entry.isOld(now) {
			logging.Debugf(c.Context, "Cleaning up old token cache entry: %s", entry.Key.Key)
		} else {
			cleaned.Cache = append(cleaned.Cache, entry)
		}
	}

	// Nothing left? Remove the file completely.
	if len(cleaned.Cache) == 0 {
		if err := os.Remove(c.absPath()); err != nil && !os.IsNotExist(err) {
			return err
		}
		return nil
	}

	blob, err := json.MarshalIndent(cleaned, "", "  ")
	if err != nil {
		return err
	}

	// Write to temp file first.
	if err := os.MkdirAll(c.SecretsDir, 0700); err != nil {
		logging.WithError(err).Warningf(c.Context, "Failed to mkdir token cache dir")
		// carry on, TempFile will fail too.
	}
	tmp, err := ioutil.TempFile(c.SecretsDir, CacheFilename)
	if err != nil {
		return err
	}

	cleanup := func() {
		if err := os.Remove(tmp.Name()); err != nil {
			logging.WithError(err).Warningf(c.Context, "Failed to remove temp creds cache file: %s", tmp.Name())
		}
	}

	_, writeErr := tmp.Write(blob)
	closeErr := tmp.Close()
	switch {
	case writeErr != nil:
		err = writeErr
	case closeErr != nil:
		err = closeErr
	}
	if err != nil {
		cleanup()
		return err
	}

	// Note that TempFile creates the file in 0600 mode already, so we don't need
	// to chmod it.
	//
	// On Windows Rename may fail with sharing violation error if some other
	// process has opened the file. We treat it as transient error, to trigger
	// a retry in updateCacheFile.
	if err = os.Rename(tmp.Name(), c.absPath()); err != nil {
		cleanup()
		return transient.Tag.Apply(err)
	}
	return nil
}
1189219
func WritePidFile(pidFile string) error {
	if pidFile == "" {
		return nil
	}
	pid := []byte(strconv.Itoa(os.Getpid()) + "\n")
	return ioutil.WriteFile(pidFile, pid, 0644)
}
1072361
func (dir *Dir) WriteFile(fileName string, reader io.Reader) (file *File, err error) {
	if err = dir.createIfNoExist(); err == nil {
		relativeDir := strings.TrimPrefix(dir.DirPath, dir.Filebox.BaseDir)
		file = dir.Filebox.AccessFile(filepath.Join(relativeDir, fileName), dir.Roles...)
		err = file.Write(reader)
	}
	return
}
774592
func (hp HashedPasswords) WriteToFile(file string) error {
	return ioutil.WriteFile(file, hp.Bytes(), 0644)
}
1095450
func CopyFile(destFilename, srcFilename string) (err error) {

	destFile, err := os.Create(destFilename)
	if err != nil {
		return NewBuildIfError(err, "Failed to create file", "file", destFilename)
	}

	srcFile, err := os.Open(srcFilename)
	if err != nil {
		return NewBuildIfError(err, "Failed to open file", "file", srcFilename)
	}

	_, err = io.Copy(destFile, srcFile)
	if err != nil {
		return NewBuildIfError(err, "Failed to copy data", "fromfile", srcFilename, "tofile", destFilename)
	}

	err = destFile.Close()
	if err != nil {
		return NewBuildIfError(err, "Failed to close file", "file", destFilename)
	}

	err = srcFile.Close()
	if err != nil {
		return NewBuildIfError(err, "Failed to close file", "file", srcFilename)
	}

	return
}
443256
func (r *realFS) WriteFile(filename string, data []byte, perm os.FileMode) (int, error) {
	return len(data), ioutil.WriteFile(filename, data, perm)
}
633214
func (writer *NsenterWriter) WriteFile(filename string, data []byte, perm os.FileMode) error {
	cmd := "nsenter"
	base_args := []string{
		"--mount=/rootfs/proc/1/ns/mnt",
		"--",
	}

	echo_args := append(base_args, "sh", "-c", fmt.Sprintf("cat > %s", filename))
	glog.V(5).Infof("Command to write data to file: %v %v", cmd, echo_args)
	command := exec.Command(cmd, echo_args...)
	command.Stdin = bytes.NewBuffer(data)
	outputBytes, err := command.CombinedOutput()
	if err != nil {
		glog.Errorf("Output from writing to %q: %v", filename, string(outputBytes))
		return err
	}

	chmod_args := append(base_args, "chmod", fmt.Sprintf("%o", perm), filename)
	glog.V(5).Infof("Command to change permissions to file: %v %v", cmd, chmod_args)
	outputBytes, err = exec.Command(cmd, chmod_args...).CombinedOutput()
	if err != nil {
		glog.Errorf("Output from chmod command: %v", string(outputBytes))
		return err
	}

	return nil
}
874175
func (f *FakeFS) WriteFile(filename string, data []byte, perm os.FileMode) (int, error) {
	f.Files[filename] = new(bytes.Buffer)
	return f.Files[filename].Write(data)
}