github.com/mook-as/cf-cli@v7.0.0-beta.28.0.20200120190804-b91c115fae48+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 "cell_id", 73 "instance", 74 "exit_description", 75 "exit_status", 76 "recursive", 77 "disk_quota", 78 "instances", 79 "memory", 80 "state", 81 "command", 82 "environment_json", 83 } 84 85 func formatDescription(metadata generic.Map, keys []string) string { 86 parts := []string{} 87 for _, key := range keys { 88 value := metadata.Get(key) 89 if value != nil { 90 parts = append(parts, fmt.Sprintf("%s: %s", key, formatDescriptionPart(value))) 91 } 92 } 93 return strings.Join(parts, ", ") 94 } 95 96 func formatDescriptionPart(val interface{}) string { 97 switch val := val.(type) { 98 case string: 99 return val 100 case float64: 101 return strconv.FormatFloat(val, byte('f'), -1, 64) 102 case bool: 103 if val { 104 return "true" 105 } 106 return "false" 107 default: 108 return fmt.Sprintf("%s", val) 109 } 110 }