-
Notifications
You must be signed in to change notification settings - Fork 12
/
source.go
95 lines (82 loc) · 2.75 KB
/
source.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
package resource
import (
"encoding/base32"
"encoding/binary"
"hash/crc32"
"strings"
"time"
log "github.com/sirupsen/logrus"
corev1 "k8s.io/api/core/v1"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
nais_io_v1 "github.com/nais/liberator/pkg/apis/nais.io/v1"
"github.com/nais/liberator/pkg/stringutil"
)
type Source interface {
client.Object
metav1.ObjectMetaAccessor
metav1.Common
SetStatus(*nais_io_v1.Status)
GetStatus() *nais_io_v1.Status
GetObjectReference() corev1.ObjectReference
GetOwnerReference() metav1.OwnerReference
GetGCP() *nais_io_v1.GCP
CorrelationID() string
SkipDeploymentMessage() bool
LogFields() log.Fields
ApplyDefaults() error
Hash() (string, error)
}
func CreateObjectMeta(source Source) metav1.ObjectMeta {
labels := map[string]string{}
for k, v := range source.GetLabels() {
labels[k] = v
}
labels["app"] = source.GetName()
return metav1.ObjectMeta{
Name: source.GetName(),
Namespace: source.GetNamespace(),
Labels: labels,
Annotations: map[string]string{
nais_io_v1.DeploymentCorrelationIDAnnotation: source.CorrelationID(),
},
OwnerReferences: []metav1.OwnerReference{source.GetOwnerReference()},
}
}
// We concatenate name, namespace and add a hash in order to avoid duplicate names when creating service accounts in common service accounts namespace.
// Also making sure to not exceed name length restrictions of 30 characters
func CreateAppNamespaceHash(source Source) string {
name := source.GetName()
namespace := source.GetNamespace()
if len(name) > 11 {
name = source.GetName()[:11]
}
if len(namespace) > 10 {
namespace = source.GetNamespace()[:10]
}
appNameSpace := name + "-" + namespace
checksum := crc32.ChecksumIEEE([]byte(source.GetName() + "-" + source.GetNamespace()))
bs := make([]byte, 4)
binary.LittleEndian.PutUint32(bs, checksum)
return appNameSpace + "-" + strings.ToLower(base32.StdEncoding.WithPadding(base32.NoPadding).EncodeToString(bs))
}
func CreateEvent(source Source, reason, message, typeStr string) *corev1.Event {
objectMeta := CreateObjectMeta(source)
objectMeta.GenerateName = "naiserator-event-"
objectMeta.Name = ""
return &corev1.Event{
ObjectMeta: objectMeta,
ReportingController: "naiserator",
ReportingInstance: "naiserator",
Action: reason,
Reason: reason,
InvolvedObject: source.GetObjectReference(),
Source: corev1.EventSource{Component: "naiserator"},
Message: stringutil.StrTrimMiddle(message, 1024),
EventTime: metav1.MicroTime{Time: time.Now()},
FirstTimestamp: metav1.Time{Time: time.Now()},
LastTimestamp: metav1.Time{Time: time.Now()},
Type: typeStr,
Count: 1,
}
}