github.com/loggregator/cli@v6.33.1-0.20180224010324-82334f081791+incompatible/cf/api/resources/events.go (about) 1 package resources 2 3 import ( 4 "fmt" 5 "strconv" 6 "strings" 7 "time" 8 9 . "code.cloudfoundry.org/cli/cf/i18n" 10 "code.cloudfoundry.org/cli/cf/models" 11 "code.cloudfoundry.org/cli/util/generic" 12 ) 13 14 type EventResource interface { 15 ToFields() models.EventFields 16 } 17 18 type EventResourceNewV2 struct { 19 Resource 20 Entity struct { 21 Timestamp time.Time 22 Type string 23 Actor string `json:"actor"` 24 ActorName string `json:"actor_name"` 25 Metadata map[string]interface{} 26 } 27 } 28 29 type EventResourceOldV2 struct { 30 Resource 31 Entity struct { 32 Timestamp time.Time 33 ExitDescription string `json:"exit_description"` 34 ExitStatus int `json:"exit_status"` 35 InstanceIndex int `json:"instance_index"` 36 } 37 } 38 39 func (resource EventResourceNewV2) ToFields() models.EventFields { 40 metadata := generic.NewMap(resource.Entity.Metadata) 41 if metadata.Has("request") { 42 metadata = generic.NewMap(metadata.Get("request")) 43 } 44 45 return models.EventFields{ 46 GUID: resource.Metadata.GUID, 47 Name: resource.Entity.Type, 48 Timestamp: resource.Entity.Timestamp, 49 Description: formatDescription(metadata, knownMetadataKeys), 50 Actor: resource.Entity.Actor, 51 ActorName: resource.Entity.ActorName, 52 } 53 } 54 55 func (resource EventResourceOldV2) ToFields() models.EventFields { 56 return models.EventFields{ 57 GUID: resource.Metadata.GUID, 58 Name: T("app crashed"), 59 Timestamp: resource.Entity.Timestamp, 60 Description: fmt.Sprintf(T("instance: {{.InstanceIndex}}, reason: {{.ExitDescription}}, exit_status: {{.ExitStatus}}", 61 map[string]interface{}{ 62 "InstanceIndex": resource.Entity.InstanceIndex, 63 "ExitDescription": resource.Entity.ExitDescription, 64 "ExitStatus": strconv.Itoa(resource.Entity.ExitStatus), 65 })), 66 } 67 } 68 69 var knownMetadataKeys = []string{ 70 "index", 71 "reason", 72 "exit_description", 73 "exit_status", 74 "recursive", 75 "disk_quota", 76 "instances", 77 "memory", 78 "state", 79 "command", 80 "environment_json", 81 } 82 83 func formatDescription(metadata generic.Map, keys []string) string { 84 parts := []string{} 85 for _, key := range keys { 86 value := metadata.Get(key) 87 if value != nil { 88 parts = append(parts, fmt.Sprintf("%s: %s", key, formatDescriptionPart(value))) 89 } 90 } 91 return strings.Join(parts, ", ") 92 } 93 94 func formatDescriptionPart(val interface{}) string { 95 switch val := val.(type) { 96 case string: 97 return val 98 case float64: 99 return strconv.FormatFloat(val, byte('f'), -1, 64) 100 case bool: 101 if val { 102 return "true" 103 } 104 return "false" 105 default: 106 return fmt.Sprintf("%s", val) 107 } 108 }