forked from contiv/vpp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
txn.go
83 lines (71 loc) · 2.41 KB
/
txn.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
// Copyright (c) 2018 Cisco and/or its affiliates.
//
// 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 controller
import (
"context"
"fmt"
"github.com/golang/protobuf/proto"
"github.com/americanbinary/vpp/plugins/controller/api"
scheduler_api "go.ligato.io/vpp-agent/v3/plugins/kvscheduler/api"
)
// kvSchedulerTxn implements Transaction interface for KVScheduler.
type kvSchedulerTxn struct {
kvScheduler scheduler_api.KVScheduler
// values set via Put or Delete
values api.KeyValuePairs
// injected by Controller to merge external with internal configuration
merged api.KeyValuePairs
}
// newTransaction creates new transaction to be executed via KVScheduler.
func newTransaction(kvScheduler scheduler_api.KVScheduler) *kvSchedulerTxn {
return &kvSchedulerTxn{
kvScheduler: kvScheduler,
values: make(api.KeyValuePairs),
merged: make(api.KeyValuePairs),
}
}
// Commit applies the requested transaction changes.
func (txn *kvSchedulerTxn) Commit(ctx context.Context) (seqNum uint64, err error) {
schedTxn := txn.kvScheduler.StartNBTransaction()
for key, value := range txn.values {
if value != nil {
// put
schedTxn.SetValue(key, value)
} else {
// delete
schedTxn.SetValue(key, nil)
}
}
for key, value := range txn.merged {
schedTxn.SetValue(key, value)
}
return schedTxn.Commit(ctx)
}
// Put add request to the transaction to add or modify a value.
// <value> cannot be nil.
func (txn *kvSchedulerTxn) Put(key string, value proto.Message) {
if value == nil {
panic(fmt.Sprintf("Put nil value for key '%s'", key))
}
txn.values[key] = value
}
func (txn *kvSchedulerTxn) Delete(key string) {
txn.values[key] = nil
}
// Get is used to obtain value already prepared to be applied by this transaction.
// Until the transaction is committed, provided values can still be changed.
func (txn *kvSchedulerTxn) Get(key string) proto.Message {
value, _ := txn.values[key]
return value
}