// Function to call on webhook failure; behavior determined by defaultAllow flag
975011
func (a *Plugin) webhookError(pod *api.Pod, attributes admission.Attributes, err error) error {
	if err != nil {
		klog.V(2).Infof("error contacting webhook backend: %s", err)
		if a.defaultAllow {
			attributes.AddAnnotation(AuditKeyPrefix+ImagePolicyFailedOpenKeySuffix, "true")
			// TODO(wteiken): Remove the annotation code for the 1.13 release
			annotations := pod.GetAnnotations()
			if annotations == nil {
				annotations = make(map[string]string)
			}
			annotations[api.ImagePolicyFailedOpenKey] = "true"
			pod.ObjectMeta.SetAnnotations(annotations)

			klog.V(2).Infof("resource allowed in spite of webhook backend failure")
			return nil
		}
		klog.V(2).Infof("resource not allowed due to webhook backend failure ")
		return admission.NewForbidden(attributes, err)
	}
	return nil
}
341327
func (b *Remote) retryLogHook(attemptNum int, resp *http.Response) {
	if b.CLI != nil {
		// Ignore the first retry to make sure any delayed output will
		// be written to the console before we start logging retries.
		//
		// The retry logic in the TFE client will retry both rate limited
		// requests and server errors, but in the remote backend we only
		// care about server errors so we ignore rate limit (429) errors.
		if attemptNum == 0 || resp.StatusCode == 429 {
			// Reset the last retry time.
			b.lastRetry = time.Now()
			return
		}

		if attemptNum == 1 {
			b.CLI.Output(b.Colorize().Color(strings.TrimSpace(initialRetryError)))
		} else {
			b.CLI.Output(b.Colorize().Color(strings.TrimSpace(
				fmt.Sprintf(repeatedRetryError, time.Since(b.lastRetry).Round(time.Second)))))
		}
	}
}
1114790
func callWorkflowHook(hookPhase string,
	hook WorkflowHook,
	hooks []WorkflowHookHandler,
	ctx *workflowContext) error {

	if hook != nil {
		ctx.logger.Warn(fmt.Sprintf("DEPRECATED: Single %s hook superseded by %ss slice",
			hookPhase,
			hookPhase))
		hooks = append(hooks, WorkflowHookFunc(hook))
	}
	for _, eachHook := range hooks {
		// Run the hook
		ctx.logger.WithFields(logrus.Fields{
			"Phase":               hookPhase,
			"WorkflowHookContext": ctx.context.workflowHooksContext,
		}).Info("Calling WorkflowHook")

		hookErr := eachHook.DecorateWorkflow(ctx.context.workflowHooksContext,
			ctx.userdata.serviceName,
			ctx.userdata.s3Bucket,
			ctx.userdata.buildID,
			ctx.context.awsSession,
			ctx.userdata.noop,
			ctx.logger)
		if hookErr != nil {
			return errors.Wrapf(hookErr, "DecorateWorkflow returned an error")
		}
	}
	return nil
}
450935
func Fail() fibre.MiddlewareFunc {
	return func(h fibre.HandlerFunc) fibre.HandlerFunc {
		return func(c *fibre.Context) error {

			defer func() {
				if err := recover(); err != nil {
					trace := make([]byte, 1<<16)
					n := runtime.Stack(trace, false)
					c.Fibre().Logger().Errorf("%v\n stack trace %s", err, trace[:n])
					c.Error(fmt.Errorf("panic recover\n %v\n stack trace %d bytes\n %s", err, n, trace[:n]))
				}
			}()

			return h(c)

		}
	}
}
117392
func (a *Webhook) Dispatch(attr admission.Attributes, o admission.ObjectInterfaces) error {
	if rules.IsWebhookConfigurationResource(attr) {
		return nil
	}
	if !a.WaitForReady() {
		return admission.NewForbidden(attr, fmt.Errorf("not yet ready to handle request"))
	}
	hooks := a.hookSource.Webhooks()
	// TODO: Figure out if adding one second timeout make sense here.
	ctx := context.TODO()

	var relevantHooks []*v1beta1.Webhook
	for i := range hooks {
		call, err := a.ShouldCallHook(&hooks[i], attr)
		if err != nil {
			return err
		}
		if call {
			relevantHooks = append(relevantHooks, &hooks[i])
		}
	}

	if len(relevantHooks) == 0 {
		// no matching hooks
		return nil
	}

	// convert the object to the external version before sending it to the webhook
	versionedAttr := VersionedAttributes{
		Attributes: attr,
	}
	if oldObj := attr.GetOldObject(); oldObj != nil {
		out, err := ConvertToGVK(oldObj, attr.GetKind(), o)
		if err != nil {
			return apierrors.NewInternalError(err)
		}
		versionedAttr.VersionedOldObject = out
	}
	if obj := attr.GetObject(); obj != nil {
		out, err := ConvertToGVK(obj, attr.GetKind(), o)
		if err != nil {
			return apierrors.NewInternalError(err)
		}
		versionedAttr.VersionedObject = out
	}
	return a.dispatcher.Dispatch(ctx, &versionedAttr, o, relevantHooks)
}
548590
func (m *Manager) HandleHTTPWebSocket(pattern string) {
	log.Infof("workflow Manager listening to websocket traffic at %v", pattern)
	http.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) {
		defer func() {
			if x := recover(); x != nil {
				errMsg := fmt.Sprintf("uncaught panic: %v", x)
				log.Error(errMsg)
				http.Error(w, errMsg, http.StatusInternalServerError)
			}
		}()

		// Check ACL.
		if err := acl.CheckAccessHTTP(r, acl.ADMIN); err != nil {
			msg := fmt.Sprintf("WorkflowManager acl.CheckAccessHTTP failed: %v", err)
			log.Error(msg)
			http.Error(w, msg, http.StatusUnauthorized)
			return
		}

		// Upgrade to WebSocket.
		c, err := upgrader.Upgrade(w, r, nil)
		if err != nil {
			log.Errorf("upgrade error: %v", err)
			return
		}
		defer c.Close()

		// Register the handler.
		tree, notifications, i, err := m.getAndWatchFullTree(r.URL)
		if err != nil {
			log.Warningf("GetAndWatchFullTree failed: %v", err)
			return
		}
		if notifications != nil {
			defer m.NodeManager().CloseWatcher(i)
		}

		// First we send the full dump
		if err := c.WriteMessage(websocket.TextMessage, tree); err != nil {
			log.Warningf("WriteMessage(tree) failed: %v", err)
			return
		}

		// If we didn't get a channel back (redirect case), we're done.
		// We will just return the redirect, and close the websocket.
		if notifications == nil {
			return
		}

		// Start a go routine to get messages, send them to a channel.
		recv := make(chan *ActionParameters, 10)
		go func() {
			for {
				mt, message, err := c.ReadMessage()
				if err != nil {
					log.Warningf("failed to read message from websocket: %v", err)
					close(recv)
					return
				}
				if mt != websocket.TextMessage {
					log.Warningf("weird message type: %v", mt)
				}

				ap := &ActionParameters{}
				if err := json.Unmarshal(message, ap); err != nil {
					log.Warningf("failed to JSON-decode message from websocket: %v", err)
					close(recv)
					return
				}
				recv <- ap
			}
		}()

		// Let's listen to the channels until we're done.
		for {
			select {
			case ap, ok := <-recv:
				if !ok {
					// The websocket was most likely closed.
					return
				}

				ctx := context.TODO()
				if err := m.NodeManager().Action(ctx, ap); err != nil {
					log.Warningf("Action failed: %v", err)
				}

			case message, ok := <-notifications:
				if !ok {
					// We ran out of space on the update
					// channel, so we had to close it.
					return
				}
				if err := c.WriteMessage(websocket.TextMessage, message); err != nil {
					log.Warningf("WriteMessage(tree) failed: %v", err)
					return
				}
			}
		}
	})
}
1093073
func (app *KitchenSink) Callback(w http.ResponseWriter, r *http.Request) {
	events, err := app.bot.ParseRequest(r)
	if err != nil {
		if err == linebot.ErrInvalidSignature {
			w.WriteHeader(400)
		} else {
			w.WriteHeader(500)
		}
		return
	}
	for _, event := range events {
		log.Printf("Got event %v", event)
		switch event.Type {
		case linebot.EventTypeMessage:
			switch message := event.Message.(type) {
			case *linebot.TextMessage:
				if err := app.handleText(message, event.ReplyToken, event.Source); err != nil {
					log.Print(err)
				}
			case *linebot.ImageMessage:
				if err := app.handleImage(message, event.ReplyToken); err != nil {
					log.Print(err)
				}
			case *linebot.VideoMessage:
				if err := app.handleVideo(message, event.ReplyToken); err != nil {
					log.Print(err)
				}
			case *linebot.AudioMessage:
				if err := app.handleAudio(message, event.ReplyToken); err != nil {
					log.Print(err)
				}
			case *linebot.FileMessage:
				if err := app.handleFile(message, event.ReplyToken); err != nil {
					log.Print(err)
				}
			case *linebot.LocationMessage:
				if err := app.handleLocation(message, event.ReplyToken); err != nil {
					log.Print(err)
				}
			case *linebot.StickerMessage:
				if err := app.handleSticker(message, event.ReplyToken); err != nil {
					log.Print(err)
				}
			default:
				log.Printf("Unknown message: %v", message)
			}
		case linebot.EventTypeFollow:
			if err := app.replyText(event.ReplyToken, "Got followed event"); err != nil {
				log.Print(err)
			}
		case linebot.EventTypeUnfollow:
			log.Printf("Unfollowed this bot: %v", event)
		case linebot.EventTypeJoin:
			if err := app.replyText(event.ReplyToken, "Joined "+string(event.Source.Type)); err != nil {
				log.Print(err)
			}
		case linebot.EventTypeLeave:
			log.Printf("Left: %v", event)
		case linebot.EventTypePostback:
			data := event.Postback.Data
			if data == "DATE" || data == "TIME" || data == "DATETIME" {
				data += fmt.Sprintf("(%v)", *event.Postback.Params)
			}
			if err := app.replyText(event.ReplyToken, "Got postback: "+data); err != nil {
				log.Print(err)
			}
		case linebot.EventTypeBeacon:
			if err := app.replyText(event.ReplyToken, "Got beacon: "+event.Beacon.Hwid); err != nil {
				log.Print(err)
			}
		default:
			log.Printf("Unknown event: %v", event)
		}
	}
}
716705
func (c *Callbacks) OnCMsgClearWorldDecalsEvent(fn func(*dota.CMsgClearWorldDecalsEvent) error) {
	c.onCMsgClearWorldDecalsEvent = append(c.onCMsgClearWorldDecalsEvent, fn)
}
57296
func (agent *ActionAgent) ExecuteHook(ctx context.Context, hk *hook.Hook) *hook.HookResult {
	if err := agent.lock(ctx); err != nil {
		// client gave up
		return &hook.HookResult{}
	}
	defer agent.unlock()

	// Execute the hooks
	topotools.ConfigureTabletHook(hk, agent.TabletAlias)
	hr := hk.Execute()

	// We never know what the hook did, so let's refresh our state.
	if err := agent.refreshTablet(ctx, "ExecuteHook"); err != nil {
		log.Errorf("refreshTablet after ExecuteHook failed: %v", err)
	}

	return hr
}
317402
func (a *MandrillAPI) WebhookAdd(url string, events []string) (Webhook, error) {
	if url == "" {
		return Webhook{}, errors.New("url cannot be blank")
	}
	var params map[string]interface{} = make(map[string]interface{})
	params["url"] = url
	params["events"] = events
	return getWebhook(a, params, webhooks_add_endpoint)
}
58511
func (opc *operationCallbacks) NotifyHookFailed(hook string, ctx runner.Context) {
	if opc.u.observer != nil {
		notifyHook(hook, ctx, opc.u.observer.HookFailed)
	}
}
1039397
func ValidateWebhookThrottleConfig(c *auditregistration.WebhookThrottleConfig, fldPath *field.Path) field.ErrorList {
	var allErrs field.ErrorList
	if c.QPS != nil && *c.QPS <= 0 {
		allErrs = append(allErrs, field.Invalid(fldPath.Child("qps"), c.QPS, "qps must be a positive number"))
	}
	if c.Burst != nil && *c.Burst <= 0 {
		allErrs = append(allErrs, field.Invalid(fldPath.Child("burst"), c.Burst, "burst must be a positive number"))
	}
	return allErrs
}
1256707
func (k *Kite) HandleHTTPFunc(pattern string, handler func(http.ResponseWriter, *http.Request)) {
	k.muxer.HandleFunc(pattern, handler)
}
922958
func (rh *runHook) afterHook(state State) (_ bool, err error) {
	defer func() {
		if err != nil {
			logger.Errorf("error updating workload status after %v hook: %v", rh.info.Kind, err)
		}
	}()

	ctx := rh.runner.Context()
	hasRunStatusSet := ctx.HasExecutionSetUnitStatus() || state.StatusSet
	switch rh.info.Kind {
	case hooks.Stop:
		// Charm is no longer of this world.
		err = ctx.SetUnitStatus(jujuc.StatusInfo{
			Status: string(status.Terminated),
		})
	case hooks.Start:
		if hasRunStatusSet {
			break
		}
		logger.Debugf("unit %v has started but has not yet set status", ctx.UnitName())
		// We've finished the start hook and the charm has not updated its
		// own status so we'll set it to unknown.
		err = ctx.SetUnitStatus(jujuc.StatusInfo{
			Status: string(status.Unknown),
		})
	case hooks.RelationBroken:
		var isLeader bool
		isLeader, err = ctx.IsLeader()
		if !isLeader || err != nil {
			return hasRunStatusSet && err == nil, err
		}
		rel, rErr := ctx.Relation(rh.info.RelationId)
		if rErr == nil && rel.Suspended() {
			err = rel.SetStatus(relation.Suspended)
		}
	}
	return hasRunStatusSet && err == nil, err
}
521804
func defaultErrorHandler(ctx *Context, data ...map[string]interface{}) {
	var renderData map[string]interface{}
	if len(data) == 0 {
		renderData = make(map[string]interface{})
		renderData["Code"] = ctx.statusCode
		renderData["Title"] = http.StatusText(ctx.statusCode)
		renderData["Message"] = http.StatusText(ctx.statusCode)
	} else {
		renderData = data[0]
	}
	if _, ok := renderData["Code"]; !ok {
		renderData["Code"] = ctx.statusCode
	}
	if _, ok := renderData["Title"]; !ok {
		renderData["Title"] = http.StatusText(ctx.statusCode)
	}
	if _, ok := renderData["Message"]; !ok {
		renderData["Message"] = http.StatusText(ctx.statusCode)
	}
	httpRequest, _ := httputil.DumpRequest(ctx.Request, true)
	renderData["HTTPRequest"] = string(httpRequest)
	var buf bytes.Buffer
	tmpl.Parse(errorTemplate)
	tmpl.Execute(&buf, renderData)
	ctx.Send(&buf)
}
619919
func globalErrorCallback(err C.virErrorPtr) {
	globalErrorMutex.RLock()
	defer globalErrorMutex.RUnlock()
	if globalErrorContext.cb != nil {
		globalErrorContext.cb(newError(err), globalErrorContext.f)
	}
}
741920
func errorFunc(server string, w dns.ResponseWriter, r *dns.Msg, rc int) {
	state := request.Request{W: w, Req: r}

	answer := new(dns.Msg)
	answer.SetRcode(r, rc)
	state.SizeAndDo(answer)

	w.WriteMsg(answer)
}