This repository has been archived by the owner on Nov 28, 2022. It is now read-only.
forked from knative/eventing
/
receiver.go
207 lines (179 loc) · 6.74 KB
/
receiver.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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
/*
* Copyright 2018 The Knative Authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package receiver
import (
"context"
"errors"
"fmt"
"sync"
"sync/atomic"
"cloud.google.com/go/pubsub"
"github.com/knative/eventing/contrib/gcppubsub/pkg/controller/channel"
"github.com/knative/eventing/contrib/gcppubsub/pkg/dispatcher/receiver/cache"
"github.com/knative/eventing/contrib/gcppubsub/pkg/util"
eventingv1alpha1 "github.com/knative/eventing/pkg/apis/eventing/v1alpha1"
"github.com/knative/eventing/pkg/channelwatcher"
"github.com/knative/eventing/pkg/logging"
"github.com/knative/eventing/pkg/provisioners"
"go.uber.org/zap"
"k8s.io/apimachinery/pkg/types"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/manager"
)
// Receiver parses Cloud Events and sends them to GCP PubSub.
type Receiver struct {
logger *zap.Logger
client client.Client
pubSubClientCreator util.PubSubClientCreator
cache *cache.TTL
hostToChannelMapMutex sync.Mutex
hostToChannelMap atomic.Value
}
// New creates a new Receiver and its associated MessageReceiver. The caller is responsible for
// Start()ing the returned MessageReceiver.
func New(logger *zap.Logger, client client.Client, pubSubClientCreator util.PubSubClientCreator) (*Receiver, []manager.Runnable, error) {
r := &Receiver{
logger: logger,
client: client,
pubSubClientCreator: pubSubClientCreator,
cache: cache.NewTTL(),
}
r.setHostToChannelMap(map[string]provisioners.ChannelReference{})
receiver, err := r.newMessageReceiver()
if err != nil {
return nil, nil, err
}
return r, []manager.Runnable{receiver, r.cache}, nil
}
func (r *Receiver) newMessageReceiver() (*provisioners.MessageReceiver, error) {
return provisioners.NewMessageReceiver(
r.sendEventToTopic,
r.logger.Sugar(),
provisioners.ResolveChannelFromHostHeader(r.getChannelReferenceFromHost))
}
func (r *Receiver) getChannelReferenceFromHost(host string) (provisioners.ChannelReference, error) {
chMap := r.getHostToChannelMap()
cr, ok := chMap[host]
if !ok {
return cr, fmt.Errorf("Invalid HostName:%q. HostName not found in any of the watched gcp-pubsub channels", host)
}
return cr, nil
}
// sendEventToTopic sends a message to the Cloud Pub/Sub Topic backing the Channel.
func (r *Receiver) sendEventToTopic(channel provisioners.ChannelReference, message *provisioners.Message) error {
r.logger.Debug("received message")
ctx := context.Background()
c, err := r.getChannel(ctx, channel)
if err != nil {
logging.FromContext(ctx).Info("Unable to get the Channel", zap.Error(err), zap.Any("channelRef", channel))
return err
}
pcs, err := util.GetInternalStatus(c)
if err != nil {
logging.FromContext(ctx).Error("Unable to read status.internal", zap.Error(err), zap.Any("channel", c))
return err
} else if pcs.IsEmpty() {
logging.FromContext(ctx).Info("status.internal is blank")
return errors.New("status.internal is blank")
}
cached := r.cache.Get(pcs.Topic)
if cached == nil {
cached, err = r.createPubSubReceiver(ctx, pcs)
if err != nil {
logging.FromContext(ctx).Info("Unable to create pubSubReceiver", zap.Error(err))
return err
}
}
psr, ok := cached.(*pubSubReceiver)
if !ok {
r.cache.DeleteIfPresent(pcs.Topic, psr)
return fmt.Errorf("unexpected type in the cache[%s] - %T", pcs.Topic, cached)
}
result := psr.topic.Publish(ctx, &pubsub.Message{
Data: message.Payload,
Attributes: message.Headers,
})
id, err := result.Get(ctx)
if err != nil {
return err
}
r.logger.Debug("Published a message", zap.String("topicName", pcs.Topic), zap.String("pubSubMessageId", id))
return nil
}
func (r *Receiver) createPubSubReceiver(ctx context.Context, pcs *util.GcpPubSubChannelStatus) (cache.Stoppable, error) {
creds, err := util.GetCredentials(ctx, r.client, pcs.Secret, pcs.SecretKey)
if err != nil {
r.logger.Info("Failed to extract creds", zap.Error(err))
return nil, err
}
psc, err := r.pubSubClientCreator(ctx, creds, pcs.GCPProject)
if err != nil {
r.logger.Info("Failed to create PubSub client", zap.Error(err))
return nil, err
}
// Note that creating topic does not actually start any background work. So this struct can be
// discarded without any problems. Once topic.Publish is called, then background work starts and
// topic.Stop must be called eventually.
topic := psc.Topic(pcs.Topic)
psr := r.cache.Insert(pcs.Topic, &pubSubReceiver{
topic: topic,
})
return psr, nil
}
type pubSubReceiver struct {
topic util.PubSubTopic
}
func (psr *pubSubReceiver) Stop() {
psr.topic.Stop()
}
func (r *Receiver) getChannel(ctx context.Context, ref provisioners.ChannelReference) (*eventingv1alpha1.Channel, error) {
c := &eventingv1alpha1.Channel{}
err := r.client.Get(ctx,
types.NamespacedName{
Namespace: ref.Namespace,
Name: ref.Name,
},
c)
return c, err
}
func (r *Receiver) getHostToChannelMap() map[string]provisioners.ChannelReference {
return r.hostToChannelMap.Load().(map[string]provisioners.ChannelReference)
}
func (r *Receiver) setHostToChannelMap(hcMap map[string]provisioners.ChannelReference) {
r.hostToChannelMap.Store(hcMap)
}
// UpdateHostToChannelMap will be called from the controller that watches gcp-pubsub channels.
// It will update internal hostToChannelMap which is used to resolve the hostHeader of the
// incoming request to the correct ChannelReference in the receiver function.
func (r *Receiver) UpdateHostToChannelMap(ctx context.Context) error {
logging.FromContext(ctx).Debug("UpdateHostToChannelMap: Acquiring mutex lock")
r.hostToChannelMapMutex.Lock()
defer r.hostToChannelMapMutex.Unlock()
logging.FromContext(ctx).Debug("UpdateHostToChannelMap: Acquired mutex lock. Updating internal map")
chanList, err := channelwatcher.ListAllChannels(ctx, r.client, channel.ShouldReconcile)
if err != nil {
logging.FromContext(ctx).Error("UpdateHostToChannelMap: Failed to list all channels.", zap.Error(err))
return err
}
hostToChanMap, err := provisioners.NewHostNameToChannelRefMap(chanList)
if err != nil {
logging.FromContext(ctx).Error("UpdateHostToChannelMap: Error occurred when creating the new hostToChannel map.", zap.Error(err))
return err
}
r.setHostToChannelMap(hostToChanMap)
logging.FromContext(ctx).Info("UpdateHostToChannelMap: Update successful.")
return nil
}