-
Notifications
You must be signed in to change notification settings - Fork 1.3k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add watch to in-memory server multiplexer
Signed-off-by: killianmuldoon <kmuldoon@vmware.com>
- Loading branch information
1 parent
6173c33
commit e9cf72f
Showing
10 changed files
with
363 additions
and
10 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
191 changes: 191 additions & 0 deletions
191
test/infrastructure/inmemory/internal/server/api/watch.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,191 @@ | ||
/* | ||
Copyright 2023 The Kubernetes 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 api | ||
|
||
import ( | ||
"context" | ||
"fmt" | ||
"net/http" | ||
"time" | ||
|
||
"github.com/emicklei/go-restful/v3" | ||
"github.com/pkg/errors" | ||
"k8s.io/apimachinery/pkg/runtime" | ||
"k8s.io/apimachinery/pkg/runtime/schema" | ||
"k8s.io/apimachinery/pkg/watch" | ||
"sigs.k8s.io/controller-runtime/pkg/client" | ||
) | ||
|
||
// Event records a lifecycle event for a Kubernetes object. | ||
type Event struct { | ||
Type watch.EventType `json:"type,omitempty"` | ||
Object runtime.Object `json:"object,omitempty"` | ||
} | ||
|
||
// WatchEventDispatcher dispatches events for a single resourceGroup. | ||
type WatchEventDispatcher struct { | ||
resourceGroup string | ||
events chan (*Event) | ||
} | ||
|
||
// OnCreate dispatches Create events. | ||
func (m *WatchEventDispatcher) OnCreate(resourceGroup string, o client.Object) { | ||
if resourceGroup != m.resourceGroup { | ||
return | ||
} | ||
m.events <- &Event{ | ||
Type: watch.Added, | ||
Object: o, | ||
} | ||
} | ||
|
||
// OnUpdate dispatches Update events. | ||
func (m *WatchEventDispatcher) OnUpdate(resourceGroup string, _, o client.Object) { | ||
if resourceGroup != m.resourceGroup { | ||
return | ||
} | ||
m.events <- &Event{ | ||
Type: watch.Modified, | ||
Object: o, | ||
} | ||
} | ||
|
||
// OnDelete dispatches Delete events. | ||
func (m *WatchEventDispatcher) OnDelete(resourceGroup string, o client.Object) { | ||
if resourceGroup != m.resourceGroup { | ||
return | ||
} | ||
m.events <- &Event{ | ||
Type: watch.Deleted, | ||
Object: o, | ||
} | ||
} | ||
|
||
// OnGeneric dispatches Generic events. | ||
func (m *WatchEventDispatcher) OnGeneric(resourceGroup string, o client.Object) { | ||
if resourceGroup != m.resourceGroup { | ||
return | ||
} | ||
m.events <- &Event{ | ||
Type: watch.EventType("GENERIC"), | ||
Object: o, | ||
} | ||
} | ||
|
||
// isWatch is true if the request contains `watch="true"` as a query parameter. | ||
func isWatch(req *restful.Request) bool { | ||
return req.QueryParameter("watch") == "true" | ||
} | ||
|
||
func (h *apiServerHandler) watchForResource(req *restful.Request, resp *restful.Response, resourceGroup string, gvk schema.GroupVersionKind) (reterr error) { | ||
ctx := req.Request.Context() | ||
queryTimeout := req.QueryParameter("timeoutSeconds") | ||
c := h.manager.GetCache() | ||
i, err := c.GetInformerForKind(ctx, gvk) | ||
if err != nil { | ||
return err | ||
} | ||
h.log.Info(fmt.Sprintf("Serving Watch for %v", req.Request.URL)) | ||
// This needs to be a buffered channel as otherwise it can cause a deadlock. | ||
events := make(chan *Event, 10) | ||
watcher := &WatchEventDispatcher{ | ||
resourceGroup: resourceGroup, | ||
events: events, | ||
} | ||
|
||
if err := i.AddEventHandler(watcher); err != nil { | ||
return err | ||
} | ||
|
||
// Defer cleanup which removes the event handler and ensures the channel is empty of events. | ||
defer func() { | ||
reterr = i.RemoveEventHandler(watcher) | ||
// Doing this to ensure the channel is empty. | ||
L: | ||
for { | ||
select { | ||
case <-events: | ||
default: | ||
break L | ||
} | ||
} | ||
}() | ||
|
||
watcher.Run(ctx, queryTimeout, resp, h) | ||
return nil | ||
} | ||
|
||
// Run serves a series of encoded events via HTTP with Transfer-Encoding: chunked. | ||
func (m *WatchEventDispatcher) Run(ctx context.Context, timeout string, w http.ResponseWriter, h *apiServerHandler) { | ||
flusher, ok := w.(http.Flusher) | ||
if !ok { | ||
h.log.Info("Can't start Watch: can't get http.Flusher.", "flusher", w) | ||
return | ||
} | ||
resp, ok := w.(*restful.Response) | ||
if !ok { | ||
h.log.Info("Can't start Watch: can't get restful.Response.", "response", w) | ||
return | ||
} | ||
w.Header().Set("Transfer-Encoding", "chunked") | ||
w.WriteHeader(http.StatusOK) | ||
flusher.Flush() | ||
|
||
timeoutTimer, seconds, err := setTimer(timeout) | ||
if err != nil { | ||
h.log.Info(errors.Wrapf(err, "can't start Watch: could not set timeout").Error()) | ||
return | ||
} | ||
|
||
ctx, cancel := context.WithTimeout(ctx, seconds) | ||
defer cancel() | ||
defer timeoutTimer.Stop() | ||
for { | ||
select { | ||
case <-ctx.Done(): | ||
return | ||
case <-timeoutTimer.C: | ||
return | ||
case event, ok := <-m.events: | ||
if !ok { | ||
// End of results. | ||
return | ||
} | ||
if err := resp.WriteEntity(event); err != nil { | ||
_ = resp.WriteErrorString(http.StatusInternalServerError, err.Error()) | ||
} | ||
if len(m.events) == 0 { | ||
flusher.Flush() | ||
} | ||
} | ||
} | ||
} | ||
|
||
// setTimer creates a time.Timer with the passed `timeout` or a default timeout of 120 seconds if `timeout` is empty. | ||
func setTimer(timeout string) (*time.Timer, time.Duration, error) { | ||
var defaultTimeout = 120 * time.Second | ||
if timeout == "" { | ||
t := time.NewTimer(defaultTimeout) | ||
return t, defaultTimeout, nil | ||
} | ||
seconds, err := time.ParseDuration(fmt.Sprintf("%ss", timeout)) | ||
if err != nil { | ||
return nil, 0, errors.Wrapf(err, "Could not parse request timeout %s", timeout) | ||
} | ||
t := time.NewTimer(seconds) | ||
return t, seconds, nil | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.