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