zrok/controller/metrics/websocketSource.go

158 lines
4.1 KiB
Go
Raw Normal View History

2023-03-03 19:31:57 +01:00
package metrics
2023-03-06 21:51:23 +01:00
import (
"crypto/tls"
"crypto/x509"
"encoding/json"
"github.com/gorilla/websocket"
"github.com/michaelquigley/cf"
"github.com/openziti/channel/v3"
"github.com/openziti/channel/v3/websockets"
2023-05-25 17:50:38 +02:00
"github.com/openziti/edge-api/rest_util"
2023-03-06 21:51:23 +01:00
"github.com/openziti/identity"
"github.com/openziti/ziti/common/pb/mgmt_pb"
"github.com/openziti/ziti/controller/event"
"github.com/openziti/zrok/controller/env"
2023-03-06 21:51:23 +01:00
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
"io"
"net/http"
"net/url"
"time"
2023-03-06 21:51:23 +01:00
)
2023-03-03 19:31:57 +01:00
2023-05-25 17:50:38 +02:00
const ZitiSession = "zt-session"
func init() {
2023-03-15 21:14:06 +01:00
env.GetCfOptions().AddFlexibleSetter("websocketSource", loadWebsocketSourceConfig)
}
2023-03-03 19:31:57 +01:00
type WebsocketSourceConfig struct {
WebsocketEndpoint string // wss://127.0.0.1:1280/fabric/v1/ws-api
ApiEndpoint string // https://127.0.0.1:1280
2023-03-06 21:51:23 +01:00
Username string
2023-03-15 21:14:06 +01:00
Password string `cf:"+secret"`
2023-03-03 19:31:57 +01:00
}
2023-03-06 21:51:23 +01:00
func loadWebsocketSourceConfig(v interface{}, _ *cf.Options) (interface{}, error) {
if submap, ok := v.(map[string]interface{}); ok {
cfg := &WebsocketSourceConfig{}
if err := cf.Bind(cfg, submap, cf.DefaultOptions()); err != nil {
return nil, err
}
return &websocketSource{cfg: cfg}, nil
}
return nil, errors.New("invalid config structure for 'websocketSource'")
2023-03-03 19:31:57 +01:00
}
2023-03-06 21:51:23 +01:00
type websocketSource struct {
cfg *WebsocketSourceConfig
ch channel.Channel
2023-05-01 20:45:45 +02:00
events chan ZitiEventMsg
2023-03-06 21:51:23 +01:00
join chan struct{}
}
2023-03-03 19:31:57 +01:00
2023-05-01 20:45:45 +02:00
func (s *websocketSource) Start(events chan ZitiEventMsg) (join chan struct{}, err error) {
2023-03-06 21:51:23 +01:00
caCerts, err := rest_util.GetControllerWellKnownCas(s.cfg.ApiEndpoint)
if err != nil {
return nil, err
}
caPool := x509.NewCertPool()
for _, ca := range caCerts {
caPool.AddCert(ca)
}
authenticator := rest_util.NewAuthenticatorUpdb(s.cfg.Username, s.cfg.Password)
authenticator.RootCas = caPool
apiEndpointUrl, err := url.Parse(s.cfg.ApiEndpoint)
if err != nil {
return nil, err
}
apiSession, err := authenticator.Authenticate(apiEndpointUrl)
if err != nil {
return nil, err
}
dialer := &websocket.Dialer{
TLSClientConfig: &tls.Config{
RootCAs: caPool,
},
HandshakeTimeout: 5 * time.Second,
}
2023-05-25 17:50:38 +02:00
conn, resp, err := dialer.Dial(s.cfg.WebsocketEndpoint, http.Header{ZitiSession: []string{*apiSession.Token}})
2023-03-06 21:51:23 +01:00
if err != nil {
if resp != nil {
if body, rerr := io.ReadAll(resp.Body); rerr == nil {
logrus.Errorf("response body '%v': %v", string(body), err)
}
} else {
logrus.Errorf("no response from websocket dial: %v", err)
}
}
id := &identity.TokenId{Token: "mgmt"}
underlayFactory := websockets.NewUnderlayFactory(id, conn, nil)
s.join = make(chan struct{})
s.events = events
bindHandler := func(binding channel.Binding) error {
binding.AddReceiveHandler(int32(mgmt_pb.ContentType_StreamEventsEventType), s)
binding.AddCloseHandler(channel.CloseHandlerF(func(ch channel.Channel) {
close(s.join)
}))
return nil
}
s.ch, err = channel.NewChannel("mgmt", underlayFactory, channel.BindHandlerF(bindHandler), nil)
if err != nil {
return nil, err
}
streamEventsRequest := map[string]interface{}{}
streamEventsRequest["format"] = "json"
streamEventsRequest["subscriptions"] = []*event.Subscription{
{
Type: "fabric.usage",
Options: map[string]interface{}{
"version": uint8(3),
},
},
}
msgBytes, err := json.Marshal(streamEventsRequest)
if err != nil {
return nil, err
}
requestMsg := channel.NewMessage(int32(mgmt_pb.ContentType_StreamEventsRequestType), msgBytes)
responseMsg, err := requestMsg.WithTimeout(5 * time.Second).SendForReply(s.ch)
if err != nil {
return nil, err
}
if responseMsg.ContentType == channel.ContentTypeResultType {
result := channel.UnmarshalResult(responseMsg)
if result.Success {
logrus.Infof("event stream started: %v", result.Message)
} else {
return nil, errors.Wrap(err, "error starting event streaming")
}
} else {
return nil, errors.Errorf("unexpected response type %v", responseMsg.ContentType)
}
return s.join, nil
2023-03-03 19:31:57 +01:00
}
func (s *websocketSource) Stop() {
2023-03-06 21:51:23 +01:00
_ = s.ch.Close()
}
func (s *websocketSource) HandleReceive(msg *channel.Message, _ channel.Channel) {
2023-05-01 20:45:45 +02:00
s.events <- &ZitiEventJsonMsg{
data: ZitiEventJson(msg.Body),
}
}