/
action_route.go
98 lines (86 loc) · 2.57 KB
/
action_route.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
96
97
98
package action
import (
"context"
"sigs.k8s.io/controller-runtime/pkg/client"
"github.com/atlasmap/atlasmap-operator/api/v1alpha1"
"github.com/go-logr/logr"
routev1 "github.com/openshift/api/route/v1"
"k8s.io/apimachinery/pkg/api/errors"
v1 "k8s.io/apimachinery/pkg/apis/meta/v1"
"k8s.io/apimachinery/pkg/runtime/schema"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
type routeAction struct {
baseAction
}
func newRouteAction(log logr.Logger, mgr manager.Manager) Action {
return &routeAction{
newBaseAction(log, mgr, "Route"),
}
}
func (action *routeAction) Handle(ctx context.Context, atlasMap *v1alpha1.AtlasMap) error {
route := &routev1.Route{}
err := action.client.Get(ctx, types.NamespacedName{Name: atlasMap.Name, Namespace: atlasMap.Namespace}, route)
if err != nil && errors.IsNotFound(err) {
route = createAtlasMapRoute(atlasMap)
err := action.deployResource(ctx, atlasMap, route)
// Route can take a while to create so there's a chance of an 'already exists' error occurring
if err != nil && !errors.IsAlreadyExists(err) {
return err
}
} else if err == nil && route != nil {
if err := reconcileRoute(ctx, atlasMap, route, action.client); err != nil {
return err
}
} else {
return err
}
return nil
}
func reconcileRoute(ctx context.Context, atlasMap *v1alpha1.AtlasMap, route *routev1.Route, client client.Client) error {
if atlasMap.Spec.RouteHostName != route.Spec.Host {
route.Spec.Host = atlasMap.Spec.RouteHostName
if err := client.Update(ctx, route); err != nil {
return err
}
}
url := "https://" + route.Spec.Host
if atlasMap.Status.URL != url {
atlasMap.Status.URL = url
if err := client.Status().Update(ctx, atlasMap); err != nil {
return err
}
}
return nil
}
func createAtlasMapRoute(atlasMap *v1alpha1.AtlasMap) *routev1.Route {
return &routev1.Route{
TypeMeta: v1.TypeMeta{
Kind: "Route",
APIVersion: routev1.GroupVersion.String(),
},
ObjectMeta: v1.ObjectMeta{
Name: atlasMap.Name,
Namespace: atlasMap.Namespace,
Labels: atlasMapLabels(atlasMap),
OwnerReferences: []v1.OwnerReference{
*v1.NewControllerRef(atlasMap, schema.GroupVersionKind{
Group: v1alpha1.SchemeBuilder.GroupVersion.Group,
Version: v1alpha1.SchemeBuilder.GroupVersion.Version,
Kind: atlasMap.Kind,
}),
},
},
Spec: routev1.RouteSpec{
Host: atlasMap.Spec.RouteHostName,
To: routev1.RouteTargetReference{
Kind: "Service",
Name: atlasMap.Name,
},
TLS: &routev1.TLSConfig{
Termination: routev1.TLSTerminationEdge,
},
},
}
}