/
state.go
345 lines (281 loc) · 9.23 KB
/
state.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
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
// Copyright 2018 Istio 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 runtime
import (
"bytes"
"fmt"
"sort"
"strings"
"sync"
"time"
"github.com/gogo/protobuf/types"
mcp "istio.io/api/mcp/v1alpha1"
"istio.io/istio/galley/pkg/metadata"
"istio.io/istio/galley/pkg/runtime/conversions"
"istio.io/istio/galley/pkg/runtime/log"
"istio.io/istio/galley/pkg/runtime/monitoring"
"istio.io/istio/galley/pkg/runtime/processing"
"istio.io/istio/galley/pkg/runtime/publish"
"istio.io/istio/galley/pkg/runtime/resource"
"istio.io/istio/pkg/mcp/snapshot"
)
var _ processing.Handler = &State{}
// State is the in-memory state of Galley.
type State struct {
name string
schema *resource.Schema
distribute bool
strategy *publish.Strategy
distributor publish.Distributor
config *Config
// version counter is a nonce that generates unique ids for each updated view of State.
versionCounter int64
// entries for per-message-type State.
entriesLock sync.Mutex
entries map[resource.Collection]*resourceTypeState
// Virtual version numbers for Gateways & VirtualServices for Ingress projected ones
ingressGWVersion int64
ingressVSVersion int64
lastIngressVersion int64
// pendingEvents counts the number of events awaiting publishing.
pendingEvents int64
// lastSnapshotTime records the last time a snapshot was published.
lastSnapshotTime time.Time
}
// per-resource-type State.
type resourceTypeState struct {
// The version number for the current State of the object. Every time entries or versions change,
// the version number also change
version int64
entries map[resource.FullName]*mcp.Resource
versions map[resource.FullName]resource.Version
}
func newState(name string, schema *resource.Schema, cfg *Config, strategy *publish.Strategy,
distributor publish.Distributor) *State {
now := time.Now()
s := &State{
name: name,
schema: schema,
strategy: strategy,
distributor: distributor,
config: cfg,
entries: make(map[resource.Collection]*resourceTypeState),
lastSnapshotTime: now,
}
// pre-populate state for all known types so that built snapshots
// includes valid default version for empty resource collections.
for _, info := range schema.All() {
s.entries[info.Collection] = &resourceTypeState{
entries: make(map[resource.FullName]*mcp.Resource),
versions: make(map[resource.FullName]resource.Version),
}
}
return s
}
func (s *State) close() {
s.strategy.Reset()
}
func (s *State) publish() {
now := time.Now()
monitoring.RecordProcessorSnapshotPublished(s.pendingEvents, now.Sub(s.lastSnapshotTime))
s.lastSnapshotTime = now
sn := s.buildSnapshot()
s.distributor.SetSnapshot(s.name, sn)
s.pendingEvents = 0
}
func (s *State) onFullSync() {
s.distribute = true
s.strategy.OnChange()
}
// Handle implements the processing.Handler interface.
func (s *State) Handle(event resource.Event) {
pks, found := s.getResourceTypeState(event.Entry.ID.Collection)
if !found {
return
}
switch event.Kind {
case resource.Added, resource.Updated:
// Check to see if the version has changed.
if curVersion := pks.versions[event.Entry.ID.FullName]; curVersion == event.Entry.ID.Version {
log.Scope.Debugf("Received event for the current, known version: %v", event)
return
}
// TODO: Check for content-wise equality
entry, ok := s.toResource(event.Entry)
if !ok {
return
}
pks.entries[event.Entry.ID.FullName] = entry
pks.versions[event.Entry.ID.FullName] = event.Entry.ID.Version
monitoring.RecordStateTypeCount(event.Entry.ID.Collection.String(), len(pks.entries))
case resource.Deleted:
delete(pks.entries, event.Entry.ID.FullName)
delete(pks.versions, event.Entry.ID.FullName)
monitoring.RecordStateTypeCount(event.Entry.ID.Collection.String(), len(pks.entries))
default:
log.Scope.Errorf("Unknown event kind: %v", event.Kind)
return
}
s.versionCounter++
pks.version = s.versionCounter
log.Scope.Debugf("In-memory State has changed:\n%v\n", s)
s.pendingEvents++
if s.distribute {
s.strategy.OnChange()
}
}
func (s *State) getResourceTypeState(name resource.Collection) (*resourceTypeState, bool) {
s.entriesLock.Lock()
defer s.entriesLock.Unlock()
pks, found := s.entries[name]
return pks, found
}
func (s *State) buildSnapshot() snapshot.Snapshot {
s.entriesLock.Lock()
defer s.entriesLock.Unlock()
b := snapshot.NewInMemoryBuilder()
for collection, state := range s.entries {
entries := make([]*mcp.Resource, 0, len(state.entries))
for _, entry := range state.entries {
entries = append(entries, entry)
}
version := fmt.Sprintf("%d", state.version)
b.Set(collection.String(), version, entries)
}
// Build entities that are derived from existing ones.
s.buildProjections(b)
return b.Build()
}
func (s *State) buildProjections(b *snapshot.InMemoryBuilder) {
s.buildIngressProjectionResources(b)
}
func (s *State) buildIngressProjectionResources(b *snapshot.InMemoryBuilder) {
ingressByHost := make(map[string]resource.Entry)
// Build ingress projections
state := s.entries[metadata.K8sExtensionsV1beta1Ingresses.Collection]
if state == nil || len(state.entries) == 0 {
return
}
if s.lastIngressVersion != state.version {
// Ingresses has changed
s.versionCounter++
s.ingressGWVersion = s.versionCounter
s.versionCounter++
s.ingressVSVersion = s.versionCounter
s.lastIngressVersion = state.version
}
versionStr := fmt.Sprintf("%d_%d",
s.entries[metadata.IstioNetworkingV1alpha3Gateways.Collection].version, s.ingressGWVersion)
b.SetVersion(metadata.IstioNetworkingV1alpha3Gateways.Collection.String(), versionStr)
versionStr = fmt.Sprintf("%d_%d",
s.entries[metadata.IstioNetworkingV1alpha3Virtualservices.Collection].version, s.ingressVSVersion)
b.SetVersion(metadata.IstioNetworkingV1alpha3Virtualservices.Collection.String(), versionStr)
// Order names for stable generation.
var orderedNames []resource.FullName
for name := range state.entries {
orderedNames = append(orderedNames, name)
}
sort.Slice(orderedNames, func(i, j int) bool {
return strings.Compare(orderedNames[i].String(), orderedNames[j].String()) < 0
})
for _, name := range orderedNames {
entry := state.entries[name]
ingress, err := conversions.ToIngressSpec(entry)
if err != nil {
// Shouldn't happen
log.Scope.Errorf("error during ingress projection: %v", err)
continue
}
key := extractKey(name, state.versions[name])
meta := extractMetadata(entry)
conversions.IngressToVirtualService(key, meta, ingress, s.config.DomainSuffix, ingressByHost)
gw := conversions.IngressToGateway(key, meta, ingress)
err = b.SetEntry(
metadata.IstioNetworkingV1alpha3Gateways.Collection.String(),
gw.ID.FullName.String(),
string(gw.ID.Version),
gw.Metadata.CreateTime,
nil,
nil,
gw.Item)
if err != nil {
log.Scope.Errorf("Unable to set gateway entry: %v", err)
}
}
for _, e := range ingressByHost {
err := b.SetEntry(
metadata.IstioNetworkingV1alpha3Virtualservices.Collection.String(),
e.ID.FullName.String(),
string(e.ID.Version),
e.Metadata.CreateTime,
nil,
nil,
e.Item)
if err != nil {
log.Scope.Errorf("Unable to set virtualservice entry: %v", err)
}
}
}
func extractKey(name resource.FullName, version resource.Version) resource.VersionedKey {
return resource.VersionedKey{
Key: resource.Key{
Collection: metadata.K8sExtensionsV1beta1Ingresses.Collection,
FullName: name,
},
Version: version,
}
}
func extractMetadata(entry *mcp.Resource) resource.Metadata {
ts, err := types.TimestampFromProto(entry.Metadata.CreateTime)
if err != nil {
// It is an invalid timestamp. This shouldn't happen.
log.Scope.Errorf("Error converting proto timestamp to time.Time: %v", err)
}
return resource.Metadata{
CreateTime: ts,
Labels: entry.Metadata.GetLabels(),
Annotations: entry.Metadata.GetAnnotations(),
}
}
func (s *State) toResource(e resource.Entry) (*mcp.Resource, bool) {
body, err := types.MarshalAny(e.Item)
if err != nil {
log.Scope.Errorf("Error serializing proto from source e: %v:", e)
return nil, false
}
createTime, err := types.TimestampProto(e.Metadata.CreateTime)
if err != nil {
log.Scope.Errorf("Error parsing resource create_time for event (%v): %v", e, err)
return nil, false
}
entry := &mcp.Resource{
Metadata: &mcp.Metadata{
Name: e.ID.FullName.String(),
CreateTime: createTime,
Version: string(e.ID.Version),
Labels: e.Metadata.Labels,
Annotations: e.Metadata.Annotations,
},
Body: body,
}
return entry, true
}
// String implements fmt.Stringer
func (s *State) String() string {
var b bytes.Buffer
_, _ = fmt.Fprintf(&b, "[State @%v]\n", s.versionCounter)
sn := s.buildSnapshot().(*snapshot.InMemory)
_, _ = fmt.Fprintf(&b, "%v", sn)
return b.String()
}