blob: 185a8e8833faa581c366b84d2869ab0ed7b66533 [file] [log] [blame]
khenaidoo1ce37ad2019-03-24 22:07:24 -04001/*
2 * Copyright 2018-present Open Networking Foundation
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
npujar1d86a522019-11-14 17:11:16 +053016
khenaidoo1ce37ad2019-03-24 22:07:24 -040017package utils
18
khenaidoo2c6a0992019-04-29 13:46:56 -040019import (
khenaidoo442e7c72020-03-10 16:13:48 -040020 "context"
khenaidoo631fe542019-05-31 15:44:43 -040021 "os"
khenaidoo442e7c72020-03-10 16:13:48 -040022 "sync"
khenaidoo2c6a0992019-04-29 13:46:56 -040023 "time"
npujar1d86a522019-11-14 17:11:16 +053024
25 "google.golang.org/grpc/codes"
26 "google.golang.org/grpc/status"
khenaidoo2c6a0992019-04-29 13:46:56 -040027)
28
khenaidoo442e7c72020-03-10 16:13:48 -040029// ResponseCallback is the function signature for callbacks to execute after a response is received.
30type ResponseCallback func(rpc string, response interface{}, reqArgs ...interface{})
31
npujar1d86a522019-11-14 17:11:16 +053032// DeviceID represent device id attribute
khenaidoo1ce37ad2019-03-24 22:07:24 -040033type DeviceID struct {
npujar1d86a522019-11-14 17:11:16 +053034 ID string
khenaidoo1ce37ad2019-03-24 22:07:24 -040035}
36
npujar1d86a522019-11-14 17:11:16 +053037// LogicalDeviceID rpresent logical device id attribute
khenaidoo1ce37ad2019-03-24 22:07:24 -040038type LogicalDeviceID struct {
npujar1d86a522019-11-14 17:11:16 +053039 ID string
khenaidoo1ce37ad2019-03-24 22:07:24 -040040}
khenaidoo2c6a0992019-04-29 13:46:56 -040041
npujar1d86a522019-11-14 17:11:16 +053042// GetHostName returns host name
khenaidoo631fe542019-05-31 15:44:43 -040043func GetHostName() string {
44 return os.Getenv("HOSTNAME")
45}
46
khenaidoo442e7c72020-03-10 16:13:48 -040047type request struct {
Kent Hagerman730cbdf2020-03-31 12:22:08 -040048 prev, next *request
49 notifyOnComplete chan<- struct{}
khenaidoo442e7c72020-03-10 16:13:48 -040050}
51
52// RequestQueue represents a request processing queue where each request is processed to completion before another
53// request is given the green light to proceed.
54type RequestQueue struct {
Kent Hagerman730cbdf2020-03-31 12:22:08 -040055 mutex sync.Mutex
56
57 last, current *request
58 lastCompleteCh <-chan struct{}
khenaidoo442e7c72020-03-10 16:13:48 -040059}
60
Kent Hagerman730cbdf2020-03-31 12:22:08 -040061// NewRequestQueue creates a new request queue
62func NewRequestQueue() *RequestQueue {
63 ch := make(chan struct{})
64 close(ch) // assume the "current" request is already complete
65 return &RequestQueue{lastCompleteCh: ch}
khenaidoo442e7c72020-03-10 16:13:48 -040066}
67
68// WaitForGreenLight is invoked by a function processing a request to receive the green light before
69// proceeding. The caller can also provide a context with timeout. The timeout will be triggered if the wait is
70// too long (previous requests taking too long)
71func (rq *RequestQueue) WaitForGreenLight(ctx context.Context) error {
Kent Hagerman730cbdf2020-03-31 12:22:08 -040072 // add ourselves to the end of the queue
73 rq.mutex.Lock()
74 waitingOn := rq.lastCompleteCh
75
76 ch := make(chan struct{})
77 rq.lastCompleteCh = ch
78 r := &request{notifyOnComplete: ch}
79
80 if rq.last != nil {
81 rq.last.next, r.prev = r, rq.last
khenaidoo442e7c72020-03-10 16:13:48 -040082 }
Kent Hagerman730cbdf2020-03-31 12:22:08 -040083 rq.last = r
84 rq.mutex.Unlock()
85
86 // wait for our turn
khenaidoo442e7c72020-03-10 16:13:48 -040087 select {
khenaidoo442e7c72020-03-10 16:13:48 -040088 case <-ctx.Done():
Kent Hagerman730cbdf2020-03-31 12:22:08 -040089 // canceled, so cleanup
90 rq.mutex.Lock()
91 defer rq.mutex.Unlock()
92
93 if _, notified := <-waitingOn; !notified {
94 // on abort, skip our position in the queue
95 r.prev.notifyOnComplete = r.notifyOnComplete
96 // and remove ourselves from the queue
97 if r.next != nil { // if we are somewhere in the middle of the queue
98 r.prev.next = r.next
99 r.next.prev = r.prev
100 } else { // if we are at the end of the queue
101 rq.last = r.prev
102 r.prev.next = nil
103 }
104
105 } else {
106 // context is canceled, but lock has been acquired, so just release the lock immediately
107 rq.current = r
108 rq.releaseWithoutLock()
109 }
khenaidoo442e7c72020-03-10 16:13:48 -0400110 return ctx.Err()
Kent Hagerman730cbdf2020-03-31 12:22:08 -0400111
112 case <-waitingOn:
113 // lock is acquired
114 rq.current = r
115 return nil
khenaidoo442e7c72020-03-10 16:13:48 -0400116 }
117}
118
119// RequestComplete must be invoked by a process when it completes processing the request. That process must have
120// invoked WaitForGreenLight() before.
121func (rq *RequestQueue) RequestComplete() {
Kent Hagerman730cbdf2020-03-31 12:22:08 -0400122 rq.mutex.Lock()
123 defer rq.mutex.Unlock()
124
125 rq.releaseWithoutLock()
khenaidoo442e7c72020-03-10 16:13:48 -0400126}
127
Kent Hagerman730cbdf2020-03-31 12:22:08 -0400128func (rq *RequestQueue) releaseWithoutLock() {
129 // Notify the next waiting request. This will panic if the lock is released more than once.
130 close(rq.current.notifyOnComplete)
131
132 if rq.current.next != nil {
133 rq.current.next.prev = nil
134 }
khenaidoo442e7c72020-03-10 16:13:48 -0400135}
136
npujar1d86a522019-11-14 17:11:16 +0530137// Response -
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500138type Response struct {
139 *response
140}
141type response struct {
142 err error
143 ch chan struct{}
144 done bool
145}
146
npujar1d86a522019-11-14 17:11:16 +0530147// NewResponse -
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500148func NewResponse() Response {
149 return Response{
150 &response{
151 ch: make(chan struct{}),
152 },
153 }
154}
155
A R Karthick5c28f552019-12-11 22:47:44 -0800156// Fake a completed response.
157func DoneResponse() Response {
158 r := Response{
159 &response{
160 err: nil,
161 ch: make(chan struct{}),
162 done: true,
163 },
164 }
165 close(r.ch)
166 return r
167}
168
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500169// Error sends a response with the given error. It may only be called once.
170func (r Response) Error(err error) {
171 // if this is called twice, it will panic; this is intentional
172 r.err = err
173 r.done = true
174 close(r.ch)
175}
176
177// Done sends a non-error response unless Error has already been called, in which case this is a no-op.
178func (r Response) Done() {
179 if !r.done {
180 close(r.ch)
181 }
182}
183
khenaidoo2c6a0992019-04-29 13:46:56 -0400184//WaitForNilOrErrorResponses waits on a variadic number of channels for either a nil response or an error
185//response. If an error is received from a given channel then the returned error array will contain that error.
186//The error will be at the index corresponding to the order in which the channel appear in the parameter list.
187//If no errors is found then nil is returned. This method also takes in a timeout in milliseconds. If a
188//timeout is obtained then this function will stop waiting for the remaining responses and abort.
khenaidoo442e7c72020-03-10 16:13:48 -0400189func WaitForNilOrErrorResponses(timeout time.Duration, responses ...Response) []error {
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500190 timedOut := make(chan struct{})
khenaidoo442e7c72020-03-10 16:13:48 -0400191 timer := time.AfterFunc(timeout, func() { close(timedOut) })
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500192 defer timer.Stop()
khenaidoo2c6a0992019-04-29 13:46:56 -0400193
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500194 gotError := false
195 errors := make([]error, 0, len(responses))
196 for _, response := range responses {
197 var err error
198 select {
199 case <-response.ch:
200 // if a response is already available, use it
201 err = response.err
202 default:
203 // otherwise, wait for either a response or a timeout
204 select {
205 case <-response.ch:
206 err = response.err
207 case <-timedOut:
208 err = status.Error(codes.Aborted, "timeout")
khenaidoo2c6a0992019-04-29 13:46:56 -0400209 }
khenaidoo2c6a0992019-04-29 13:46:56 -0400210 }
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500211 gotError = gotError || err != nil
212 errors = append(errors, err)
khenaidoo2c6a0992019-04-29 13:46:56 -0400213 }
214
Kent Hagerman8da2f1e2019-11-25 17:28:09 -0500215 if gotError {
khenaidoo2c6a0992019-04-29 13:46:56 -0400216 return errors
217 }
218 return nil
219}