// HookVars implements runner.Context.
508099
func (ctx *hookContext) HookVars(paths context.Paths) ([]string, error) {
	vars := []string{
		"CHARM_DIR=" + paths.GetCharmDir(), // legacy
		"JUJU_CHARM_DIR=" + paths.GetCharmDir(),
		"JUJU_CONTEXT_ID=" + ctx.id,
		"JUJU_AGENT_SOCKET=" + paths.GetJujucSocket(),
		"JUJU_UNIT_NAME=" + ctx.unitName,
	}
	return append(vars, context.OSDependentEnvVars(paths)...), nil
}
381705
func (f *contextFactory) HookContext(hookInfo hook.Info) (*HookContext, error) {
	ctx, err := f.coreContext()
	if err != nil {
		return nil, errors.Trace(err)
	}
	hookName := string(hookInfo.Kind)
	if hookInfo.Kind.IsRelation() {
		ctx.relationId = hookInfo.RelationId
		ctx.remoteUnitName = hookInfo.RemoteUnit
		relation, found := ctx.relations[hookInfo.RelationId]
		if !found {
			return nil, errors.Errorf("unknown relation id: %v", hookInfo.RelationId)
		}
		if hookInfo.Kind == hooks.RelationDeparted {
			relation.cache.RemoveMember(hookInfo.RemoteUnit)
		} else if hookInfo.RemoteUnit != "" {
			// Clear remote settings cache for changing remote unit.
			relation.cache.InvalidateMember(hookInfo.RemoteUnit)
		}
		hookName = fmt.Sprintf("%s-%s", relation.Name(), hookInfo.Kind)
	}
	if hookInfo.Kind.IsStorage() {
		ctx.storageTag = names.NewStorageTag(hookInfo.StorageId)
		if _, err := ctx.storage.Storage(ctx.storageTag); err != nil {
			return nil, errors.Annotatef(err, "could not retrieve storage for id: %v", hookInfo.StorageId)
		}
		storageName, err := names.StorageName(hookInfo.StorageId)
		if err != nil {
			return nil, errors.Trace(err)
		}
		hookName = fmt.Sprintf("%s-%s", storageName, hookName)
	}
	ctx.id = f.newId(hookName)
	return ctx, nil
}
521156
func (t *Tree) popVars(n int) {
	t.vars = t.vars[:n]
}
450358
func prereceiveHook(vars map[string]string) ([]byte, error) {
	var out bytes.Buffer
	// We parse the template anew each receive in case it has changed.
	t, err := template.New("hooks").Parse(PrereceiveHookTpl)
	if err != nil {
		return []byte{}, err
	}

	err = t.Execute(&out, vars)
	return out.Bytes(), err
}
1229530
func registerVars(r *http.Request, vars map[string]string) {
	parts, i := make([]string, len(vars)), 0
	for key, value := range vars {
		parts[i] = url.QueryEscape(":"+key) + "=" + url.QueryEscape(value)
		i++
	}
	q := strings.Join(parts, "&")
	if r.URL.RawQuery == "" {
		r.URL.RawQuery = q
	} else {
		r.URL.RawQuery += "&" + q
	}
}
589991
func StringListVar(p *[]string, name string, defaultValue []string, usage string) {
	*p = defaultValue
	flag.Var((*StringListValue)(p), name, usage)
}
606628
func subEnvVars(s string) string {
	updatedConfig := envRegex.ReplaceAllStringFunc(s, func(s string) string {
		// Trim off the '${' and '}'
		if len(s) <= 3 {
			// This should never happen..
			return ""
		}
		varName := s[2 : len(s)-1]

		// Lookup the variable in the environment. We play by
		// bash rules.. if its undefined we'll treat it as an
		// empty string instead of raising an error.
		return os.Getenv(varName)
	})

	return updatedConfig
}
562170
func (p *KVParam) EnvVars() (string, string) {
	if len(p.values) == 0 {
		return p.EnvName(), p.Default()
	}
	vals := make([]string, len(p.values))
	for i, v := range p.values {
		vals[i] = v.String()
	}
	return p.EnvName(), strings.Join(vals, p.sep())
}
1207452
func (s *Environment) SetVariables(v map[string]*string) *Environment {
	s.Variables = v
	return s
}
1226880
func (f *Function) hookDeploy() error {
	for _, name := range f.Plugins {
		if p, ok := plugins[name].(Deployer); ok {
			if err := p.Deploy(f); err != nil {
				return err
			}
		}
	}
	return nil
}
420022
func (r *Route) prepareVars(pairs ...string) (map[string]string, error) {
	m, err := mapFromPairsToString(pairs...)
	if err != nil {
		return nil, err
	}
	return r.buildVars(m), nil
}
1181821
func (p *Plugin) addHook(hookName string, hookConfig HookConfig) error {
	var lgHook logrus.Hook
	var err error

	switch hookName {
	case HookSysLog:
		address := hookConfig.Address
		if hookConfig.Address != "" {
			address = address + ":" + strconv.Itoa(hookConfig.Port)
		}
		lgHook, err = lgSyslog.NewSyslogHook(
			hookConfig.Protocol,
			address,
			syslog.LOG_INFO,
			p.ServiceLabel.GetAgentLabel(),
		)
	case HookLogStash:
		lgHook, err = logrustash.NewHook(
			hookConfig.Protocol,
			hookConfig.Address+":"+strconv.Itoa(hookConfig.Port),
			p.ServiceLabel.GetAgentLabel(),
		)
	case HookFluent:
		lgHook, err = logrus_fluent.NewWithConfig(logrus_fluent.Config{
			Host:       hookConfig.Address,
			Port:       hookConfig.Port,
			DefaultTag: p.ServiceLabel.GetAgentLabel(),
		})
	default:
		return fmt.Errorf("unsupported hook: %q", hookName)
	}
	if err != nil {
		return fmt.Errorf("creating hook for %v failed: %v", hookName, err)
	}
	// create hook
	cHook := &commonHook{Hook: lgHook}
	// fill up defined levels, or use default if not defined
	if len(hookConfig.Levels) == 0 {
		cHook.levels = []logrus.Level{logrus.PanicLevel, logrus.FatalLevel, logrus.ErrorLevel}
	} else {
		for _, level := range hookConfig.Levels {
			if lgl, err := logrus.ParseLevel(level); err == nil {
				cHook.levels = append(cHook.levels, lgl)
			} else {
				p.Log.Warnf("cannot parse hook log level %v : %v", level, err.Error())
			}
		}
	}
	// add hook to existing loggers and store it into registry for late use
	p.LogRegistry.AddHook(cHook)
	return nil
}
579881
func (sc *syncContext) runHook(hook *unstructured.Unstructured, hookType appv1.HookType) (bool, error) {
	// Hook resources names are deterministic, whether they are defined by the user (metadata.name),
	// or formulated at the time of the operation (metadata.generateName). If user specifies
	// metadata.generateName, then we will generate a formulated metadata.name before submission.
	if hook.GetName() == "" {
		postfix := strings.ToLower(fmt.Sprintf("%s-%s-%d", sc.syncRes.Revision[0:7], hookType, sc.opState.StartedAt.UTC().Unix()))
		generatedName := hook.GetGenerateName()
		hook = hook.DeepCopy()
		hook.SetName(fmt.Sprintf("%s%s", generatedName, postfix))
	}
	// Check our hook statuses to see if we already completed this hook.
	// If so, this method is a noop
	prevStatus := sc.getHookStatus(hook, hookType)
	if prevStatus != nil && prevStatus.HookPhase.Completed() {
		return false, nil
	}

	gvk := hook.GroupVersionKind()
	apiResource, err := kube.ServerResourceForGroupVersionKind(sc.disco, gvk)
	if err != nil {
		return false, err
	}
	resource := kube.ToGroupVersionResource(gvk.GroupVersion().String(), apiResource)
	resIf := kube.ToResourceInterface(sc.dynamicIf, apiResource, resource, hook.GetNamespace())

	var liveObj *unstructured.Unstructured
	existing, err := resIf.Get(hook.GetName(), metav1.GetOptions{})
	if err != nil {
		if !apierr.IsNotFound(err) {
			return false, fmt.Errorf("Failed to get status of %s hook %s '%s': %v", hookType, gvk, hook.GetName(), err)
		}
		_, err := sc.kubectl.ApplyResource(sc.config, hook, hook.GetNamespace(), false, false)
		if err != nil {
			return false, fmt.Errorf("Failed to create %s hook %s '%s': %v", hookType, gvk, hook.GetName(), err)
		}
		created, err := resIf.Get(hook.GetName(), metav1.GetOptions{})
		if err != nil {
			return true, fmt.Errorf("Failed to get status of %s hook %s '%s': %v", hookType, gvk, hook.GetName(), err)
		}
		sc.log.Infof("%s hook %s '%s' created", hookType, gvk, created.GetName())
		sc.setOperationPhase(appv1.OperationRunning, fmt.Sprintf("running %s hooks", hookType))
		liveObj = created
	} else {
		liveObj = existing
	}
	hookStatus := newHookStatus(liveObj, hookType)
	if hookStatus.HookPhase.Completed() {
		if enforceHookDeletePolicy(hook, hookStatus.HookPhase) {
			err = sc.deleteHook(hook.GetName(), hook.GetNamespace(), hook.GroupVersionKind())
			if err != nil {
				hookStatus.HookPhase = appv1.OperationFailed
				hookStatus.Message = fmt.Sprintf("failed to delete %s hook: %v", hookStatus.HookPhase, err)
			}
		}
	}
	return sc.updateHookStatus(hookStatus), nil
}
845373
func (d *Debugger) LocalVariables(scope api.EvalScope, cfg proc.LoadConfig) ([]api.Variable, error) {
	d.processMutex.Lock()
	defer d.processMutex.Unlock()

	s, err := proc.ConvertEvalScope(d.target, scope.GoroutineID, scope.Frame, scope.DeferredCall)
	if err != nil {
		return nil, err
	}
	pv, err := s.LocalVariables(cfg)
	if err != nil {
		return nil, err
	}
	return convertVars(pv), err
}
725593
func (c *Config) EnvVars() map[string]string {
	vars := make(map[string]string, len(c.Params))
	for _, p := range c.Params {
		k, v := p.EnvVars()
		vars[k] = v
	}
	return vars
}
324993
func (s *GenericAPIServer) RunPreShutdownHooks() error {
	var errorList []error

	s.preShutdownHookLock.Lock()
	defer s.preShutdownHookLock.Unlock()
	s.preShutdownHooksCalled = true

	for hookName, hookEntry := range s.preShutdownHooks {
		if err := runPreShutdownHook(hookName, hookEntry); err != nil {
			errorList = append(errorList, err)
		}
	}
	return utilerrors.NewAggregate(errorList)
}
634984
func runHook(p *plugin.Plugin, event string) error {
	hook := p.Metadata.Hooks.Get(event)
	if hook == "" {
		return nil
	}

	prog := exec.Command("sh", "-c", hook)
	// TODO make this work on windows
	// I think its ... ¯\_(ツ)_/¯
	// prog := exec.Command("cmd", "/C", p.Metadata.Hooks.Install())

	debug("running %s hook: %s", event, prog)

	plugin.SetupPluginEnv(settings, p.Metadata.Name, p.Dir)
	prog.Stdout, prog.Stderr = os.Stdout, os.Stderr
	if err := prog.Run(); err != nil {
		if eerr, ok := err.(*exec.ExitError); ok {
			os.Stderr.Write(eerr.Stderr)
			return fmt.Errorf("plugin %s hook for %q exited with error", event, p.Metadata.Name)
		}
		return err
	}
	return nil
}