// MaybeWriteLXDProfile implements environs.LXDProfiler.
6282
func (broker *lxdBroker) MaybeWriteLXDProfile(pName string, put *charm.LXDProfile) error {
	profileMgr, ok := broker.manager.(container.LXDProfileManager)
	if !ok {
		return nil
	}
	return profileMgr.MaybeWriteLXDProfile(pName, put)
}
828833
func (p lxdStateCharmProfiler) LXDProfile() lxdprofile.LXDProfile {
	if p.Charm == nil {
		return nil
	}
	return p.Charm.LXDProfile()
}
633535
func (g *GenOpts) write(t *TemplateOpts, data interface{}) error {
	dir, fname, err := g.location(t, data)
	if err != nil {
		return fmt.Errorf("failed to resolve template location for template %s: %v", t.Name, err)
	}

	if t.SkipExists && fileExists(dir, fname) {
		debugLog("skipping generation of %s because it already exists and skip_exist directive is set for %s",
			filepath.Join(dir, fname), t.Name)
		return nil
	}

	log.Printf("creating generated file %q in %q as %s", fname, dir, t.Name)
	content, err := g.render(t, data)
	if err != nil {
		return fmt.Errorf("failed rendering template data for %s: %v", t.Name, err)
	}

	if dir != "" {
		_, exists := os.Stat(dir)
		if os.IsNotExist(exists) {
			debugLog("creating directory %q for \"%s\"", dir, t.Name)
			// Directory settings consistent with file privileges.
			// Environment's umask may alter this setup
			if e := os.MkdirAll(dir, 0755); e != nil {
				return e
			}
		}
	}

	// Conditionally format the code, unless the user wants to skip
	formatted := content
	var writeerr error

	if !t.SkipFormat {
		formatted, err = g.LanguageOpts.FormatContent(fname, content)
		if err != nil {
			log.Printf("source formatting failed on template-generated source (%q for %s). Check that your template produces valid code", filepath.Join(dir, fname), t.Name)
			writeerr = ioutil.WriteFile(filepath.Join(dir, fname), content, 0644)
			if writeerr != nil {
				return fmt.Errorf("failed to write (unformatted) file %q in %q: %v", fname, dir, writeerr)
			}
			log.Printf("unformatted generated source %q has been dumped for template debugging purposes. DO NOT build on this source!", fname)
			return fmt.Errorf("source formatting on generated source %q failed: %v", t.Name, err)
		}
	}

	writeerr = ioutil.WriteFile(filepath.Join(dir, fname), formatted, 0644)
	if writeerr != nil {
		return fmt.Errorf("failed to write file %q in %q: %v", fname, dir, writeerr)
	}
	return err
}
4326
func MaybeSaveHostFile(c *cli.Context, hostfile *Hostfile) {
	// If -n is passed, no-op and output the resultant hosts file to stdout.
	// Otherwise it's for real and we're going to write it.
	if AnyBool(c, "n") {
		fmt.Printf("%s", hostfile.Format())
	} else {
		err := hostfile.Save()
		if err != nil {
			MaybeError(c, ErrCantWriteHostFile.Error())
		}
	}
}
157373
func (c *Charm) LXDProfile() lxdprofile.Profile {
	c.mu.Lock()
	defer c.mu.Unlock()
	return c.details.LXDProfile
}
640002
func (p *ProvisionerAPI) machineLXDProfileNames(m *state.Machine, env environs.Environ) ([]string, error) {
	profileEnv, ok := env.(environs.LXDProfiler)
	if !ok {
		logger.Tracef("LXDProfiler not implemented by environ")
		return nil, nil
	}
	units, err := m.Units()
	if err != nil {
		return nil, errors.Trace(err)
	}
	var names []string
	for _, unit := range units {
		app, err := unit.Application()
		if err != nil {
			return nil, errors.Trace(err)
		}
		ch, _, err := app.Charm()
		if err != nil {
			return nil, errors.Trace(err)
		}
		profile := ch.LXDProfile()
		if profile == nil || (profile != nil && profile.Empty()) {
			continue
		}
		pName := lxdprofile.Name(p.m.Name(), app.Name(), ch.Revision())
		// Lock here, we get a new env for every call to ProvisioningInfo().
		p.mu.Lock()
		if err := profileEnv.MaybeWriteLXDProfile(pName, profile); err != nil {
			p.mu.Unlock()
			return nil, errors.Trace(err)
		}
		p.mu.Unlock()
		names = append(names, pName)
	}
	return names, nil
}
509677
func (u *LXDProfileAPI) WatchUnitLXDProfileUpgradeNotifications(args params.Entities) (params.StringsWatchResults, error) {
	u.logger.Tracef("Starting WatchUnitLXDProfileUpgradeNotifications with %+v", args)
	result := params.StringsWatchResults{
		Results: make([]params.StringsWatchResult, len(args.Entities)),
	}
	canAccess, err := u.accessUnit()
	if err != nil {
		return params.StringsWatchResults{}, err
	}
	for i, entity := range args.Entities {
		tag, err := names.ParseTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}

		if !canAccess(tag) {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		unit, err := u.getLXDProfileUnit(tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}
		watcherId, initial, err := u.watchOneChangeUnitLXDProfileUpgradeNotifications(unit)
		if err != nil {
			result.Results[i].Error = common.ServerError(err)
			continue
		}

		result.Results[i].StringsWatcherId = watcherId
		result.Results[i].Changes = initial
	}
	return result, nil
}
731811
func kbfsLibdokanWriteFile(
	fname C.LPCWSTR,
	Buffer C.LPCVOID,
	NumberOfBytesToWrite C.DWORD,
	NumberOfBytesWritten C.LPDWORD,
	Offset C.LONGLONG,
	pfi C.PDOKAN_FILE_INFO) C.NTSTATUS {
	debugf("WriteFile '%v' %d bytes @ %d %v", d16{fname}, NumberOfBytesToWrite, Offset, *pfi)
	ctx, cancel := getContext(pfi)
	if cancel != nil {
		defer cancel()
	}
	n, err := getfi(pfi).WriteFile(
		ctx,
		makeFI(fname, pfi),
		bufToSlice(unsafe.Pointer(Buffer), uint32(NumberOfBytesToWrite)),
		int64(Offset))
	*NumberOfBytesWritten = C.DWORD(n)
	debug("->", n, err)
	return errToNT(err)
}
1025949
func (l *linuxDatapath) writeStaticData(fw io.Writer, e datapath.EndpointConfiguration) {
	fmt.Fprint(fw, defineIPv6("LXC_IP", e.IPv6Address()))
	fmt.Fprint(fw, defineIPv4("LXC_IPV4", e.IPv4Address()))

	fmt.Fprint(fw, defineMAC("NODE_MAC", e.GetNodeMAC()))
	fmt.Fprint(fw, defineUint32("LXC_ID", uint32(e.GetID())))

	secID := e.GetIdentity().Uint32()
	fmt.Fprintf(fw, defineUint32("SECLABEL", secID))
	fmt.Fprintf(fw, defineUint32("SECLABEL_NB", byteorder.HostToNetwork(secID).(uint32)))

	epID := uint16(e.GetID())
	fmt.Fprintf(fw, "#define POLICY_MAP %s\n", bpf.LocalMapName(policymap.MapName, epID))
	fmt.Fprintf(fw, "#define CALLS_MAP %s\n", bpf.LocalMapName("cilium_calls_", epID))
	fmt.Fprintf(fw, "#define CONFIG_MAP %s\n", bpf.LocalMapName(bpfconfig.MapNamePrefix, epID))
}
798727
func (config *Config) WritePluginConfig() error {
	// Marshal JSON
	rawConfig, err := json.MarshalIndent(config.pluginsConfig, "", "  ")
	if err != nil {
		return err
	}

	pluginFileDir := filepath.Join(config.PluginHome())
	err = os.MkdirAll(pluginFileDir, 0700)
	if err != nil {
		return err
	}

	// Write to file
	return ioutil.WriteFile(filepath.Join(pluginFileDir, "config.json"), rawConfig, 0600)
}
1062597
func PgXlogfileNameOffset(db XODB, v0 pgtypes.PgLsn) (pgtypes.Record, error) {
	var err error

	// sql query
	const sqlstr = `SELECT pg_catalog.pg_xlogfile_name_offset($1)`

	// run query
	var ret pgtypes.Record
	XOLog(sqlstr, v0)
	err = db.QueryRow(sqlstr, v0).Scan(&ret)
	if err != nil {
		return pgtypes.Record{}, err
	}

	return ret, nil
}
238130
func WritePKIFiles(t *testing.T, dir string, files PKIFiles) {
	for filename, body := range files {
		switch body := body.(type) {
		case *x509.Certificate:
			if err := certutil.WriteCert(path.Join(dir, filename), pkiutil.EncodeCertPEM(body)); err != nil {
				t.Errorf("unable to write certificate to file %q: [%v]", dir, err)
			}
		case *rsa.PublicKey:
			publicKeyBytes, err := pkiutil.EncodePublicKeyPEM(body)
			if err != nil {
				t.Errorf("unable to write public key to file %q: [%v]", filename, err)
			}
			if err := keyutil.WriteKey(path.Join(dir, filename), publicKeyBytes); err != nil {
				t.Errorf("unable to write public key to file %q: [%v]", filename, err)
			}
		case *rsa.PrivateKey:
			privateKey, err := keyutil.MarshalPrivateKeyToPEM(body)
			if err != nil {
				t.Errorf("unable to write private key to file %q: [%v]", filename, err)
			}
			if err := keyutil.WriteKey(path.Join(dir, filename), privateKey); err != nil {
				t.Errorf("unable to write private key to file %q: [%v]", filename, err)
			}
		}
	}
}
769720
func (a *AliasAddAction) IsWriteIndex(flag bool) *AliasAddAction {
	a.isWriteIndex = &flag
	return a
}
1222240
func WriteXML(writer io.Writer, v interface{}, options XML) (int, error) {
	if prefix := options.Prefix; prefix != "" {
		writer.Write([]byte(prefix))
	}

	if indent := options.Indent; indent != "" {
		result, err := xml.MarshalIndent(v, "", indent)
		if err != nil {
			return 0, err
		}
		result = append(result, newLineB...)
		return writer.Write(result)
	}

	result, err := xml.Marshal(v)
	if err != nil {
		return 0, err
	}
	return writer.Write(result)
}
559116
func maybeCopy(obj interface{}) interface{} {
	v := reflect.ValueOf(obj)
	if v.Kind() == reflect.Ptr {
		return obj
	}
	v2 := reflect.New(v.Type())
	v2.Elem().Set(v)
	return v2.Interface()
}
650811
func WriteToFileFunction(env *Zlisp, name string, args []Sexp) (Sexp, error) {
	if len(args) != 2 {
		return SexpNull, WrongNargs
	}
	var fn string
	switch fna := args[1].(type) {
	case *SexpStr:
		fn = fna.S
	default:
		return SexpNull, fmt.Errorf("owrite requires a string (SexpStr) path to write to as the second argument. we got type %T / value = %v", args[1], args[1])
	}

	if name == "write" || name == "writef" || name == "save" {
		// don't overwrite existing file
		if FileExists(fn) {
			return SexpNull, fmt.Errorf("refusing to write to existing file '%s'",
				fn)
		}
	}
	// owrite / owritef overwrite indiscriminately.

	f, err := os.Create(fn)
	if err != nil {
		return SexpNull, err
	}
	defer f.Close()

	var slice []Sexp
	switch sl := args[0].(type) {
	case *SexpArray:
		slice = sl.Val
		for i := range slice {
			s := slice[i].SexpString(nil)
			if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
				s = s[1 : len(s)-1]
			} else if len(s) >= 2 && s[0] == '`' && s[len(s)-1] == '`' {
				s = s[1 : len(s)-1]
			}
			_, err = fmt.Fprintf(f, "%s\n", s)
			if err != nil {
				return SexpNull, err
			}
		}
	case *SexpRaw:
		_, err = f.Write([]byte(sl.Val))
		if err != nil {
			return SexpNull, err
		}

	default:
		s := sl.SexpString(nil)
		if len(s) >= 2 && s[0] == '"' && s[len(s)-1] == '"' {
			s = s[1 : len(s)-1]
		} else if len(s) >= 2 && s[0] == '`' && s[len(s)-1] == '`' {
			s = s[1 : len(s)-1]
		}
		_, err = fmt.Fprintf(f, "%s\n", s)
		if err != nil {
			return SexpNull, err
		}
	}

	return SexpNull, nil
}
596853
func (m *containerManager) LXDProfileNames(containerName string) ([]string, error) {
	return m.server.GetContainerProfiles(containerName)
}