/
client_tcert_pool_mt.go
335 lines (284 loc) · 9.73 KB
/
client_tcert_pool_mt.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
/*
Copyright IBM Corp. 2016 All Rights Reserved.
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 crypto
import (
"errors"
"runtime"
"strings"
"sync"
"time"
)
type tCertPoolEntry struct {
attributes []string
tCertChannel chan *TCertBlock
tCertChannelFeedback chan struct{}
done chan struct{}
client *clientImpl
tCertBlock *TCertBlock
}
//NewTCertPoolEntry creates a new tcert pool entry
func newTCertPoolEntry(client *clientImpl, attributes []string) *tCertPoolEntry {
tCertChannel := make(chan *TCertBlock, client.conf.getTCertBatchSize()*2)
tCertChannelFeedback := make(chan struct{}, client.conf.getTCertBatchSize()*2)
done := make(chan struct{}, 1)
return &tCertPoolEntry{attributes, tCertChannel, tCertChannelFeedback, done, client, nil}
}
//Start starts the pool entry filler loop.
func (tCertPoolEntry *tCertPoolEntry) Start() (err error) {
// Start the filler
go tCertPoolEntry.filler()
return
}
//Stop stops the pool entry filler loop.
func (tCertPoolEntry *tCertPoolEntry) Stop() (err error) {
// Stop the filler
tCertPoolEntry.done <- struct{}{}
// Store unused TCert
tCertPoolEntry.client.Debug("Store unused TCerts...")
tCerts := make([]*TCertBlock, 0)
for {
if len(tCertPoolEntry.tCertChannel) > 0 {
tCerts = append(tCerts, <-tCertPoolEntry.tCertChannel)
} else {
break
}
}
tCertPoolEntry.client.Debugf("Found %d unused TCerts...", len(tCerts))
tCertPoolEntry.client.ks.storeUnusedTCerts(tCerts)
tCertPoolEntry.client.Debug("Store unused TCerts...done!")
return
}
//AddTCert add a tcert to the poolEntry.
func (tCertPoolEntry *tCertPoolEntry) AddTCert(tCertBlock *TCertBlock) (err error) {
tCertPoolEntry.tCertChannel <- tCertBlock
return
}
//GetNextTCert gets the next tcert of the pool.
func (tCertPoolEntry *tCertPoolEntry) GetNextTCert(attributes ...string) (tCertBlock *TCertBlock, err error) {
for i := 0; i < 3; i++ {
tCertPoolEntry.client.Debugf("Getting next TCert... %d out of 3", i)
select {
case tCertPoolEntry.tCertBlock = <-tCertPoolEntry.tCertChannel:
break
case <-time.After(30 * time.Second):
tCertPoolEntry.client.Error("Failed getting a new TCert. Buffer is empty!")
}
if tCertPoolEntry.tCertBlock != nil {
// Send feedback to the filler
tCertPoolEntry.client.Debug("Send feedback")
tCertPoolEntry.tCertChannelFeedback <- struct{}{}
break
}
}
if tCertPoolEntry.tCertBlock == nil {
// TODO: change error here
return nil, errors.New("Failed getting a new TCert. Buffer is empty!")
}
tCertBlock = tCertPoolEntry.tCertBlock
tCertPoolEntry.client.Debugf("Cert [% x].", tCertBlock.tCert.GetCertificate().Raw)
// Store the TCert permanently
tCertPoolEntry.client.ks.storeUsedTCert(tCertBlock)
tCertPoolEntry.client.Debug("Getting next TCert...done!")
return
}
func (tCertPoolEntry *tCertPoolEntry) filler() {
// Load unused TCerts
stop := false
full := false
tCertPoolEntry.client.Debug("Filler()")
attributeHash := calculateAttributesHash(tCertPoolEntry.attributes)
for {
// Check if Stop was called
select {
case <-tCertPoolEntry.done:
tCertPoolEntry.client.Debug("Force stop!")
stop = true
default:
}
if stop {
break
}
tCertDBBlocks, err := tCertPoolEntry.client.ks.loadUnusedTCerts()
if err != nil {
tCertPoolEntry.client.Errorf("Failed loading TCert: [%s]", err)
break
}
if tCertDBBlocks == nil {
tCertPoolEntry.client.Debug("No more TCerts in cache!")
break
}
var tCert *TCertBlock
for _, tCertDBBlock := range tCertDBBlocks {
if strings.Compare(attributeHash, tCertDBBlock.attributesHash) == 0 {
tCertBlock, err := tCertPoolEntry.client.getTCertFromDER(tCertDBBlock)
if err != nil {
tCertPoolEntry.client.Errorf("Failed paring TCert [% x]: [%s]", tCertDBBlock.tCertDER, err)
continue
}
tCert = tCertBlock
}
}
if tCert != nil {
// Try to send the tCert to the channel if not full
select {
case tCertPoolEntry.tCertChannel <- tCert:
tCertPoolEntry.client.Debug("TCert send to the channel!")
default:
tCertPoolEntry.client.Debug("Channell Full!")
full = true
}
if full {
break
}
} else {
tCertPoolEntry.client.Debug("No more TCerts in cache!")
break
}
}
tCertPoolEntry.client.Debug("Load unused TCerts...done!")
if !stop {
ticker := time.NewTicker(1 * time.Second)
for {
select {
case <-tCertPoolEntry.done:
stop = true
tCertPoolEntry.client.Debug("Done signal.")
case <-tCertPoolEntry.tCertChannelFeedback:
tCertPoolEntry.client.Debug("Feedback received. Time to check for tcerts")
case <-ticker.C:
tCertPoolEntry.client.Debug("Time elapsed. Time to check for tcerts")
}
if stop {
tCertPoolEntry.client.Debug("Quitting filler...")
break
}
if len(tCertPoolEntry.tCertChannel) < tCertPoolEntry.client.conf.getTCertBatchSize() {
tCertPoolEntry.client.Debugf("Refill TCert Pool. Current size [%d].",
len(tCertPoolEntry.tCertChannel),
)
var numTCerts = cap(tCertPoolEntry.tCertChannel) - len(tCertPoolEntry.tCertChannel)
if len(tCertPoolEntry.tCertChannel) == 0 {
numTCerts = cap(tCertPoolEntry.tCertChannel) / 10
if numTCerts < 1 {
numTCerts = 1
}
}
tCertPoolEntry.client.Infof("Refilling [%d] TCerts.", numTCerts)
err := tCertPoolEntry.client.getTCertsFromTCA(calculateAttributesHash(tCertPoolEntry.attributes), tCertPoolEntry.attributes, numTCerts)
if err != nil {
tCertPoolEntry.client.Errorf("Failed getting TCerts from the TCA: [%s]", err)
break
}
}
}
}
tCertPoolEntry.client.Debug("TCert filler stopped.")
}
// The Multi-threaded tCertPool is currently not used.
// It plays only a role in testing.
type tCertPoolMultithreadingImpl struct {
client *clientImpl
poolEntries map[string]*tCertPoolEntry
entriesMutex *sync.Mutex
}
//Start starts the pool processing.
func (tCertPool *tCertPoolMultithreadingImpl) Start() (err error) {
// Start the filler, initializes a poolEntry without attributes.
var attributes []string
poolEntry, err := tCertPool.getPoolEntry(attributes)
if err != nil {
return err
}
return poolEntry.Start()
}
func (tCertPool *tCertPoolMultithreadingImpl) lockEntries() {
tCertPool.entriesMutex.Lock()
}
func (tCertPool *tCertPoolMultithreadingImpl) releaseEntries() {
tCertPool.entriesMutex.Unlock()
runtime.Gosched()
}
//Stop stops the pool.
func (tCertPool *tCertPoolMultithreadingImpl) Stop() (err error) {
// Stop the filler
tCertPool.lockEntries()
defer tCertPool.releaseEntries()
for _, entry := range tCertPool.poolEntries {
err := entry.Stop()
if err != nil {
return err
}
}
return
}
//Returns a tCertPoolEntry for the attributes "attributes", if the tCertPoolEntry doesn't exists a new tCertPoolEntry will be create for that attributes.
func (tCertPool *tCertPoolMultithreadingImpl) getPoolEntryFromHash(attributeHash string) *tCertPoolEntry {
tCertPool.lockEntries()
defer tCertPool.releaseEntries()
poolEntry := tCertPool.poolEntries[attributeHash]
return poolEntry
}
//Returns a tCertPoolEntry for the attributes "attributes", if the tCertPoolEntry doesn't exists a new tCertPoolEntry will be create for that attributes.
func (tCertPool *tCertPoolMultithreadingImpl) getPoolEntry(attributes []string) (*tCertPoolEntry, error) {
tCertPool.client.Debug("Getting pool entry %v \n", attributes)
attributeHash := calculateAttributesHash(attributes)
tCertPool.lockEntries()
defer tCertPool.releaseEntries()
poolEntry := tCertPool.poolEntries[attributeHash]
if poolEntry == nil {
tCertPool.client.Debugf("New pool entry %v \n", attributes)
poolEntry = newTCertPoolEntry(tCertPool.client, attributes)
tCertPool.poolEntries[attributeHash] = poolEntry
if err := poolEntry.Start(); err != nil {
return nil, err
}
tCertPool.client.Debugf("Pool entry started %v \n", attributes)
}
return poolEntry, nil
}
//GetNextTCert returns a TCert from the pool valid to the passed attributes. If no TCert is available TCA is invoked to generate it.
func (tCertPool *tCertPoolMultithreadingImpl) GetNextTCerts(nCerts int, attributes ...string) ([]*TCertBlock, error) {
blocks := make([]*TCertBlock, nCerts)
for i := 0; i < nCerts; i++ {
block, err := tCertPool.getNextTCert(attributes...)
if err != nil {
return nil, err
}
blocks[i] = block
}
return blocks, nil
}
func (tCertPool *tCertPoolMultithreadingImpl) getNextTCert(attributes ...string) (tCertBlock *TCertBlock, err error) {
poolEntry, err := tCertPool.getPoolEntry(attributes)
if err != nil {
return nil, err
}
tCertPool.client.Debugf("Requesting tcert to the pool entry. %v", calculateAttributesHash(attributes))
return poolEntry.GetNextTCert(attributes...)
}
//AddTCert adds a TCert into the pool is invoked by the client after TCA is called.
func (tCertPool *tCertPoolMultithreadingImpl) AddTCert(tCertBlock *TCertBlock) (err error) {
poolEntry := tCertPool.getPoolEntryFromHash(tCertBlock.attributesHash)
if poolEntry == nil {
return errors.New("No pool entry found for that attributes.")
}
tCertPool.client.Debugf("Adding %v \n.", tCertBlock.attributesHash)
poolEntry.AddTCert(tCertBlock)
return
}
func (tCertPool *tCertPoolMultithreadingImpl) init(client *clientImpl) (err error) {
tCertPool.client = client
tCertPool.poolEntries = make(map[string]*tCertPoolEntry)
tCertPool.entriesMutex = &sync.Mutex{}
return
}