阅读 86

Knative源码阅读:eventing的mt-broker-ingress源码走读

本文基于knative/eventing v.0.23.0

个人博客

mt-broker-ingress是eventing请求的入口,主要功能是监听端口,获取事件,将事件转发给Channel。主要方法在pkg/broker/ingress/ingress_handler.go:

func (h *Handler) ServeHTTP(writer http.ResponseWriter, request *http.Request)
复制代码
  • 首先是请求的校验:

        // validate request method
        if request.Method != http.MethodPost {
            h.Logger.Warn("unexpected request method", zap.String("method", request.Method))
            writer.WriteHeader(http.StatusMethodNotAllowed)
            return
        }
    
        // validate request URI
        if request.RequestURI == "/" {
            writer.WriteHeader(http.StatusNotFound)
            return
        }
    复制代码
  • 从请求的url中获取Broker的信息

        nsBrokerName := strings.Split(request.RequestURI, "/")
        if len(nsBrokerName) != 3 {
            h.Logger.Info("Malformed uri", zap.String("URI", request.RequestURI))
            writer.WriteHeader(http.StatusBadRequest)
            return
        }
    复制代码
  • 将req转为message,再将message转为Cloud Event格式的event并校验

        ctx := request.Context()
    
        message := cehttp.NewMessageFromHttpRequest(request)
        defer message.Finish(nil)
    
        event, err := binding.ToEvent(ctx, message)
        if err != nil {
            h.Logger.Warn("failed to extract event from request", zap.Error(err))
            writer.WriteHeader(http.StatusBadRequest)
            return
        }
    
        // run validation for the extracted event
        validationErr := event.Validate()
        if validationErr != nil {
            h.Logger.Warn("failed to validate extractd event", zap.Error(validationErr))
            writer.WriteHeader(http.StatusBadRequest)
            return
        }
    复制代码
  • 打印trace信息

    	ctx, span := trace.StartSpan(ctx, tracing.BrokerMessagingDestination(brokerNamespacedName))
      defer span.End()
    
      if span.IsRecordingEvents() {
      	span.AddAttributes(
      		tracing.MessagingSystemAttribute,
      		tracing.MessagingProtocolHTTP,
      		tracing.BrokerMessagingDestinationAttribute(brokerNamespacedName),
      		tracing.MessagingMessageIDAttribute(event.ID()),
      	)
      	span.AddAttributes(opencensusclient.EventTraceAttributes(event)...)
      }
    复制代码
  • 从Broker的status.annotations.knative.dev/channelAddress中获取Channel地址,将event发送给Channel

    statusCode, dispatchTime := h.receive(ctx, request.Header, event, brokerNamespace, brokerName)
    复制代码
文章分类
后端
文章标签