// NextHook implements Relations.
331772
func (r *relations) NextHook(
	localState resolver.LocalState,
	remoteState remotestate.Snapshot,
) (hook.Info, error) {

	if remoteState.Life == params.Dying {
		// The unit is Dying, so make sure all subordinates are dying.
		var destroyAllSubordinates bool
		for relationId, relationSnapshot := range remoteState.Relations {
			if relationSnapshot.Life != params.Alive {
				continue
			}
			relationer, ok := r.relationers[relationId]
			if !ok {
				continue
			}
			if relationer.ru.Endpoint().Scope == corecharm.ScopeContainer {
				relationSnapshot.Life = params.Dying
				remoteState.Relations[relationId] = relationSnapshot
				destroyAllSubordinates = true
			}
		}
		if destroyAllSubordinates {
			if err := r.unit.DestroyAllSubordinates(); err != nil {
				return hook.Info{}, errors.Trace(err)
			}
		}
	}

	// Add/remove local relation state; enter and leave scope as necessary.
	if err := r.update(remoteState.Relations); err != nil {
		return hook.Info{}, errors.Trace(err)
	}

	if localState.Kind != operation.Continue {
		return hook.Info{}, resolver.ErrNoOperation
	}

	// See if any of the relations have operations to perform.
	for relationId, relationSnapshot := range remoteState.Relations {
		relationer, ok := r.relationers[relationId]
		if !ok || relationer.IsImplicit() {
			continue
		}
		var remoteBroken bool
		if remoteState.Life == params.Dying ||
			relationSnapshot.Life == params.Dying || relationSnapshot.Suspended {
			relationSnapshot = remotestate.RelationSnapshot{}
			remoteBroken = true
			// TODO(axw) if relation is implicit, leave scope & remove.
		}
		// If either the unit or the relation are Dying, or the relation becomes suspended,
		// then the relation should be broken.
		hook, err := nextRelationHook(relationer.dir, relationSnapshot, remoteBroken)
		if err == resolver.ErrNoOperation {
			continue
		}
		return hook, err
	}
	return hook.Info{}, resolver.ErrNoOperation
}
470654
func WebsocketConnectionClosedHook(hook func(req *http.Request, conn net.Conn)) optSetter {
	return func(f *Forwarder) error {
		f.httpForwarder.websocketConnectionClosedHook = hook
		return nil
	}
}
127029
func (qc *QueryCatcher) Next() (*tabletenv.LogStats, error) {
	event, err := qc.catcher.next()
	if err != nil {
		return nil, err
	}
	return event.(*tabletenv.LogStats), nil
}
290535
func nextKey(key string) string {
	fieldLen := strings.IndexAny(key, ".[")
	if fieldLen == -1 {
		return key
	}
	return key[:fieldLen]
}
342306
func (handler *Handler) Next(timeout time.Duration) *event.Event {
	var logEvent *event.Event
	if timeout == 0 {
		select {
		case logEvent = <-handler.channel:
		default:
		}
	} else {
		select {
		case logEvent = <-handler.channel:
		case <-time.After(timeout):
		}
	}
	return logEvent
}
1208657
func (r *Relationer) CommitHook(hi hook.Info) error {
	if r.IsImplicit() {
		panic("implicit relations must not run hooks")
	}
	if hi.Kind == hooks.RelationBroken {
		return r.die()
	}
	return r.dir.Write(hi)
}
1324179
func strconvHook(from, to reflect.Type, data reflect.Value) (reflect.Value, error) {
	if from.Kind() != reflect.String {
		return data, nil
	}

	s := data.String()
	switch to.Kind() {
	case reflect.Bool:
		b, err := strconv.ParseBool(s)
		return reflect.ValueOf(b), err
	case reflect.Float32, reflect.Float64:
		f, err := strconv.ParseFloat(s, to.Bits())
		return reflect.ValueOf(f).Convert(to), err
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
		i, err := strconv.ParseInt(s, 10, to.Bits())
		return reflect.ValueOf(i).Convert(to), err
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
		u, err := strconv.ParseUint(s, 10, to.Bits())
		return reflect.ValueOf(u).Convert(to), err
	}

	return data, nil
}
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
}
926636
func NewMailHook(appname string, host string, port int, from string, to string) (*MailHook, error) {
	// Connect to the remote SMTP server.
	c, err := smtp.Dial(host + ":" + strconv.Itoa(port))
	if err != nil {
		return nil, err
	}

	// Validate sender and recipient
	sender, err := mail.ParseAddress(from)
	if err != nil {
		return nil, err
	}
	recipient, err := mail.ParseAddress(to)
	if err != nil {
		return nil, err
	}

	// Set the sender and recipient.
	if err := c.Mail(sender.Address); err != nil {
		return nil, err
	}
	if err := c.Rcpt(recipient.Address); err != nil {
		return nil, err
	}

	return &MailHook{
		AppName: appname,
		c:       c,
	}, nil

}
96719
func (wr *Wrangler) ExecuteHook(ctx context.Context, tabletAlias *topodatapb.TabletAlias, hook *hk.Hook) (hookResult *hk.HookResult, err error) {
	if strings.Contains(hook.Name, "/") {
		return nil, fmt.Errorf("hook name cannot have a '/' in it")
	}
	ti, err := wr.ts.GetTablet(ctx, tabletAlias)
	if err != nil {
		return nil, err
	}
	return wr.ExecuteTabletHook(ctx, ti.Tablet, hook)
}
324920
func NewElasticHook(client *elastic.Client, host string, level logrus.Level, index string) (*ElasticHook, error) {
	return NewElasticHookWithFunc(client, host, level, func() string { return index })
}
682902
func (m *mutatingWebhookConfigurationManager) Webhooks() []v1beta1.Webhook {
	return m.configuration.Load().(*v1beta1.MutatingWebhookConfiguration).Webhooks
}
28568
func (logger *Logger) AddHook(hook lg.Hook) {
	mux := &sync.Mutex{}

	unsafeStd := (*unsafe.Pointer)(unsafe.Pointer(&logger.std))
	stdVal := (*lg.Logger)(atomic.LoadPointer(unsafeStd))
	old := logger.std
	mux.Lock()
	stdVal.Hooks.Add(hook)
	mux.Unlock()
	atomic.CompareAndSwapPointer(unsafeStd, unsafe.Pointer(old), unsafe.Pointer(logger.std))
}
1004198
func (c *connection) nextIDLoop() {
	var id int32 = 1
	for {
		select {
		case <-c.stop:
			close(c.nextID)
			return
		case c.nextID <- id:
			id++
			if id == math.MaxInt32 {
				id = 1
			}
		}
	}
}
1163245
func (r *FlatChain) handleNext(c *Context) {
	if r.next != nil {
		r.next.HandleContext(c)
	}
}
137029
func (v *Validator) CheckHooks() (errs error) {
	logrus.Debugf("check hooks")

	if v.platform != "linux" && v.platform != "solaris" {
		errs = multierror.Append(errs, fmt.Errorf("For %q platform, the configuration structure does not support hooks", v.platform))
		return
	}

	if v.spec.Hooks != nil {
		errs = multierror.Append(errs, v.checkEventHooks("prestart", v.spec.Hooks.Prestart, v.HostSpecific))
		errs = multierror.Append(errs, v.checkEventHooks("poststart", v.spec.Hooks.Poststart, v.HostSpecific))
		errs = multierror.Append(errs, v.checkEventHooks("poststop", v.spec.Hooks.Poststop, v.HostSpecific))
	}

	return
}
622977
func ParseHook(payload []byte) (*HookPayload, error) {
	hp := HookPayload{}
	if err := json.Unmarshal(payload, &hp); err != nil {
		return nil, err
	}

	// Basic sanity check
	switch {
	case len(hp.ObjectKind) == 0:
		// Assume this is a post-receive within repository
		if len(hp.After) == 0 {
			return nil, fmt.Errorf("Invalid hook received, commit hash not found.")
		}
	case hp.ObjectKind == "pipeline":
		fallthrough
	case hp.ObjectKind == "issue":
		fallthrough
	case hp.ObjectKind == "merge_request":
		if hp.ObjectAttributes == nil {
			return nil, fmt.Errorf("Invalid hook received, attributes not found.")
		}
	default:
		return nil, fmt.Errorf("Invalid hook received, payload format not recognized.")
	}

	return &hp, nil
}