// See also: https://docs.aws.amazon.com/AmazonCloudWatchEvents/latest/APIReference/API_DescribeEventBus.html
486680
func resourceAwsCloudWatchEventPermissionRead(d *schema.ResourceData, meta interface{}) error {
	conn := meta.(*AWSClient).cloudwatcheventsconn
	input := events.DescribeEventBusInput{}
	var policyDoc CloudWatchEventPermissionPolicyDoc
	var policyStatement *CloudWatchEventPermissionPolicyStatement

	// Especially with concurrent PutPermission calls there can be a slight delay
	err := resource.Retry(1*time.Minute, func() *resource.RetryError {
		log.Printf("[DEBUG] Reading CloudWatch Events bus: %s", input)
		debo, err := conn.DescribeEventBus(&input)
		if err != nil {
			return resource.NonRetryableError(fmt.Errorf("Reading CloudWatch Events permission '%s' failed: %s", d.Id(), err.Error()))
		}

		if debo.Policy == nil {
			return resource.RetryableError(fmt.Errorf("CloudWatch Events permission %q not found", d.Id()))
		}

		err = json.Unmarshal([]byte(*debo.Policy), &policyDoc)
		if err != nil {
			return resource.NonRetryableError(fmt.Errorf("Reading CloudWatch Events permission '%s' failed: %s", d.Id(), err.Error()))
		}

		policyStatement, err = findCloudWatchEventPermissionPolicyStatementByID(&policyDoc, d.Id())
		return resource.RetryableError(err)
	})
	if err != nil {
		// Missing statement inside valid policy
		if nfErr, ok := err.(*resource.NotFoundError); ok {
			log.Printf("[WARN] %s", nfErr)
			d.SetId("")
			return nil
		}

		return err
	}

	d.Set("action", policyStatement.Action)

	if err := d.Set("condition", flattenCloudWatchEventPermissionPolicyStatementCondition(policyStatement.Condition)); err != nil {
		return fmt.Errorf("error setting condition: %s", err)
	}

	principalString, ok := policyStatement.Principal.(string)
	if ok && (principalString == "*") {
		d.Set("principal", "*")
	} else {
		principalMap := policyStatement.Principal.(map[string]interface{})
		policyARN, err := arn.Parse(principalMap["AWS"].(string))
		if err != nil {
			return fmt.Errorf("Reading CloudWatch Events permission '%s' failed: %s", d.Id(), err.Error())
		}
		d.Set("principal", policyARN.AccountID)
	}
	d.Set("statement_id", policyStatement.Sid)

	return nil
}
1284815
func (s *peerRESTServer) SendEventHandler(w http.ResponseWriter, r *http.Request) {
	if !s.IsValid(w, r) {
		s.writeErrorResponse(w, errors.New("Invalid request"))
		return
	}

	ctx := newContext(r, w, "SendEvent")

	vars := mux.Vars(r)
	bucketName := vars[peerRESTBucket]
	if bucketName == "" {
		s.writeErrorResponse(w, errors.New("Bucket name is missing"))
		return
	}
	var eventReq sendEventRequest
	if r.ContentLength <= 0 {
		s.writeErrorResponse(w, errInvalidArgument)
		return
	}

	err := gob.NewDecoder(r.Body).Decode(&eventReq)
	if err != nil {
		s.writeErrorResponse(w, err)
		return
	}

	var eventResp sendEventResp
	eventResp.Success = true
	errs := globalNotificationSys.send(bucketName, eventReq.Event, eventReq.TargetID)

	for i := range errs {
		reqInfo := (&logger.ReqInfo{}).AppendTags("Event", eventReq.Event.EventName.String())
		reqInfo.AppendTags("targetName", eventReq.TargetID.Name)
		ctx := logger.SetReqInfo(context.Background(), reqInfo)
		logger.LogIf(ctx, errs[i].Err)

		eventResp.Success = false
		s.writeErrorResponse(w, errs[i].Err)
		return
	}
	logger.LogIf(ctx, gob.NewEncoder(w).Encode(&eventResp))
	w.(http.Flusher).Flush()
}
933106
func (c *awsCloudImplementation) DescribeInstance(instanceID string) (*ec2.Instance, error) {
	glog.V(2).Infof("Calling DescribeInstances for instance %q", instanceID)
	request := &ec2.DescribeInstancesInput{
		InstanceIds: []*string{&instanceID},
	}

	response, err := c.EC2().DescribeInstances(request)
	if err != nil {
		return nil, fmt.Errorf("error listing Instances: %v", err)
	}
	if response == nil || len(response.Reservations) == 0 {
		return nil, nil
	}
	if len(response.Reservations) != 1 {
		glog.Fatalf("found multiple Reservations for %q", instanceID)
	}

	reservation := response.Reservations[0]
	if len(reservation.Instances) == 0 {
		return nil, nil
	}

	if len(reservation.Instances) != 1 {
		return nil, fmt.Errorf("found multiple Instances for %q", instanceID)
	}

	instance := reservation.Instances[0]
	return instance, nil
}
1215978
func (d *ClusterNetworkDescriber) Describe(namespace, name string, settings describe.DescriberSettings) (string, error) {
	cn, err := d.c.ClusterNetworks().Get(name, metav1.GetOptions{})
	if err != nil {
		return "", err
	}
	return tabbedString(func(out *tabwriter.Writer) error {
		formatMeta(out, cn.ObjectMeta)
		formatString(out, "Service Network", cn.ServiceNetwork)
		formatString(out, "Plugin Name", cn.PluginName)
		fmt.Fprintf(out, "ClusterNetworks:\n")
		fmt.Fprintf(out, "CIDR\tHost Subnet Length\n")
		fmt.Fprintf(out, "----\t------------------\n")
		for _, clusterNetwork := range cn.ClusterNetworks {
			fmt.Fprintf(out, "%s\t%d\n", clusterNetwork.CIDR, clusterNetwork.HostSubnetLength)
		}
		return nil
	})
}
741265
func (c *Cloud) DescribeInstanceGroup(instanceGroupName string) (InstanceGroupInfo, error) {
	return DescribeInstanceGroup(c.asg, instanceGroupName)
}
188116
func (l *Forwarder) EmitAuditEvent(event Event, fields EventFields) error {
	err := UpdateEventFields(event, fields, l.Clock, l.UID)
	if err != nil {
		return trace.Wrap(err)
	}
	data, err := json.Marshal(fields)
	if err != nil {
		return trace.Wrap(err)
	}
	chunks := []*SessionChunk{
		{
			EventType: event.Name,
			Data:      data,
			Time:      time.Now().UTC().UnixNano(),
		},
	}
	return l.PostSessionSlice(SessionSlice{
		Namespace: l.Namespace,
		SessionID: string(l.SessionID),
		Version:   V3,
		Chunks:    chunks,
	})
}
681200
func (c *DefaultClient) PublishDeviceEvent(appID string, devID string, eventType types.EventType, payload interface{}) Token {
	topic := DeviceTopic{appID, devID, DeviceEvents, string(eventType)}
	msg, err := json.Marshal(payload)
	if err != nil {
		return &simpleToken{fmt.Errorf("Unable to marshal the message payload: %s", err)}
	}
	return c.publish(topic.String(), msg)
}
474228
func (s *Event) SetCloudTrailEvent(v string) *Event {
	s.CloudTrailEvent = &v
	return s
}
1085733
func ProtocolBuffersToEvents(pbEvents []*proto.Event) []Event {
	var events []Event
	for _, event := range pbEvents {
		e := Event{
			State:       event.GetState(),
			Service:     event.GetService(),
			Host:        event.GetHost(),
			Description: event.GetDescription(),
			TTL:         time.Duration(event.GetTtl()) * time.Second,
			Tags:        event.GetTags(),
		}
		if event.TimeMicros != nil {
			e.Time = time.Unix(0, event.GetTimeMicros()*int64(time.Microsecond))
		} else if event.Time != nil {
			e.Time = time.Unix(event.GetTime(), 0)
		}
		if event.MetricF != nil {
			e.Metric = event.GetMetricF()
		} else if event.MetricD != nil {
			e.Metric = event.GetMetricD()
		} else {
			e.Metric = event.GetMetricSint64()
		}
		if event.Attributes != nil {
			e.Attributes = make(map[string]string, len(event.GetAttributes()))
			for _, attr := range event.GetAttributes() {
				e.Attributes[attr.GetKey()] = attr.GetValue()
			}
		}
		events = append(events, e)
	}
	return events
}
884809
func SendServiceEvent(service string, title string, text string, sev severity, duration time.Duration) {
	sendEvent(&EventData{
		Title:    title,
		Text:     text,
		Severity: int(sev),
		Plugin:   ServicePlugin,
		ID:       service,
		Host:     ServiceHost,
		Duration: int(duration / time.Millisecond),
	})
}
208673
func DescribePlugins() string {
	pl := ListPlugins()

	str := "Server types:\n"
	for _, name := range pl["server_types"] {
		str += "  " + name + "\n"
	}

	str += "\nCaddyfile loaders:\n"
	for _, name := range pl["caddyfile_loaders"] {
		str += "  " + name + "\n"
	}

	if len(pl["event_hooks"]) > 0 {
		str += "\nEvent hook plugins:\n"
		for _, name := range pl["event_hooks"] {
			str += "  hook." + name + "\n"
		}
	}

	if len(pl["clustering"]) > 0 {
		str += "\nClustering plugins:\n"
		for _, name := range pl["clustering"] {
			str += "  " + name + "\n"
		}
	}

	str += "\nOther plugins:\n"
	for _, name := range pl["others"] {
		str += "  " + name + "\n"
	}

	return str
}
1278876
func (t *Template) GetAllAWSCloudWatchDashboardResources() map[string]*resources.AWSCloudWatchDashboard {
	results := map[string]*resources.AWSCloudWatchDashboard{}
	for name, untyped := range t.Resources {
		switch resource := untyped.(type) {
		case *resources.AWSCloudWatchDashboard:
			results[name] = resource
		}
	}
	return results
}
54199
func streamEventCallback(st C.virStreamPtr, events int, callbackID int) {
	callbackFunc := getCallbackId(callbackID)

	callback, ok := callbackFunc.(StreamEventCallback)
	if !ok {
		panic("Incorrect stream event func callback")
	}

	callback(&Stream{ptr: st}, StreamEventType(events))
}
497783
func (cgi *ConsumergroupInstance) marshalSubscription(topics []string) ([]byte, error) {
	subscription := make(map[string]int)
	for _, topic := range topics {
		subscription[topic] = 1
	}
	data, err := json.Marshal(&Registration{
		Pattern:      RegPatternStatic,
		Subscription: subscription,
		Timestamp:    time.Now().Unix(),
		Version:      RegDefaultVersion,
	})
	if err != nil {
		return nil, err
	}
	return data, nil
}
219378
func (v JSONEventV2) MarshalJSON() ([]byte, error) {
	w := jwriter.Writer{}
	easyjson3b0ebf6aEncodeGithubComSignalfxGatewayProtocolSignalfxFormat(&w, v)
	return w.Buffer.BuildBytes(), w.Error
}
429580
func (v *azureVolumeSource) DescribeVolumes(ctx context.ProviderCallContext, volumeIds []string) ([]storage.DescribeVolumesResult, error) {
	if v.maybeStorageClient == nil {
		return v.describeManagedDiskVolumes(ctx, volumeIds)
	}
	return v.describeUnmanagedDiskVolumes(ctx, volumeIds)
}
1103198
func (d *BuildDescriber) Describe(namespace, name string, settings describe.DescriberSettings) (string, error) {
	c := d.buildClient.Builds(namespace)
	buildObj, err := c.Get(name, metav1.GetOptions{})
	if err != nil {
		return "", err
	}
	events, _ := d.kubeClient.CoreV1().Events(namespace).Search(legacyscheme.Scheme, buildObj)
	if events == nil {
		events = &corev1.EventList{}
	}
	// get also pod events and merge it all into one list for describe
	if pod, err := d.kubeClient.CoreV1().Pods(namespace).Get(buildutil.GetBuildPodName(buildObj), metav1.GetOptions{}); err == nil {
		if podEvents, _ := d.kubeClient.CoreV1().Events(namespace).Search(legacyscheme.Scheme, pod); podEvents != nil {
			events.Items = append(events.Items, podEvents.Items...)
		}
	}
	return tabbedString(func(out *tabwriter.Writer) error {
		formatMeta(out, buildObj.ObjectMeta)

		fmt.Fprintln(out, "")

		status := bold(buildObj.Status.Phase)
		if buildObj.Status.Message != "" {
			status += " (" + buildObj.Status.Message + ")"
		}
		formatString(out, "Status", status)

		if buildObj.Status.StartTimestamp != nil && !buildObj.Status.StartTimestamp.IsZero() {
			formatString(out, "Started", buildObj.Status.StartTimestamp.Time.Format(time.RFC1123))
		}

		// Create the time object with second-level precision so we don't get
		// output like "duration: 1.2724395728934s"
		formatString(out, "Duration", describeBuildDuration(buildObj))

		for _, stage := range buildObj.Status.Stages {
			duration := stage.StartTime.Time.Add(time.Duration(stage.DurationMilliseconds * int64(time.Millisecond))).Round(time.Second).Sub(stage.StartTime.Time.Round(time.Second))
			formatString(out, fmt.Sprintf("  %v", stage.Name), fmt.Sprintf("  %v", duration))
		}

		fmt.Fprintln(out, "")

		if buildObj.Status.Config != nil {
			formatString(out, "Build Config", buildObj.Status.Config.Name)
		}
		formatString(out, "Build Pod", buildutil.GetBuildPodName(buildObj))

		if buildObj.Status.Output.To != nil && len(buildObj.Status.Output.To.ImageDigest) > 0 {
			formatString(out, "Image Digest", buildObj.Status.Output.To.ImageDigest)
		}

		describeCommonSpec(buildObj.Spec.CommonSpec, out)
		describeBuildTriggerCauses(buildObj.Spec.TriggeredBy, out)
		if len(buildObj.Status.LogSnippet) != 0 {
			formatString(out, "Log Tail", buildObj.Status.LogSnippet)
		}
		if settings.ShowEvents {
			versioned.DescribeEvents(events, versioned.NewPrefixWriter(out))
		}

		return nil
	})
}