broker.go 40 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427
  1. package sarama
  2. import (
  3. "crypto/tls"
  4. "encoding/binary"
  5. "fmt"
  6. "io"
  7. "net"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "sync"
  12. "sync/atomic"
  13. "time"
  14. metrics "github.com/rcrowley/go-metrics"
  15. )
  16. // Broker represents a single Kafka broker connection. All operations on this object are entirely concurrency-safe.
  17. type Broker struct {
  18. conf *Config
  19. rack *string
  20. id int32
  21. addr string
  22. correlationID int32
  23. conn net.Conn
  24. connErr error
  25. lock sync.Mutex
  26. opened int32
  27. responses chan responsePromise
  28. done chan bool
  29. registeredMetrics []string
  30. incomingByteRate metrics.Meter
  31. requestRate metrics.Meter
  32. requestSize metrics.Histogram
  33. requestLatency metrics.Histogram
  34. outgoingByteRate metrics.Meter
  35. responseRate metrics.Meter
  36. responseSize metrics.Histogram
  37. requestsInFlight metrics.Counter
  38. brokerIncomingByteRate metrics.Meter
  39. brokerRequestRate metrics.Meter
  40. brokerRequestSize metrics.Histogram
  41. brokerRequestLatency metrics.Histogram
  42. brokerOutgoingByteRate metrics.Meter
  43. brokerResponseRate metrics.Meter
  44. brokerResponseSize metrics.Histogram
  45. brokerRequestsInFlight metrics.Counter
  46. kerberosAuthenticator GSSAPIKerberosAuth
  47. }
  48. // SASLMechanism specifies the SASL mechanism the client uses to authenticate with the broker
  49. type SASLMechanism string
  50. const (
  51. // SASLTypeOAuth represents the SASL/OAUTHBEARER mechanism (Kafka 2.0.0+)
  52. SASLTypeOAuth = "OAUTHBEARER"
  53. // SASLTypePlaintext represents the SASL/PLAIN mechanism
  54. SASLTypePlaintext = "PLAIN"
  55. // SASLTypeSCRAMSHA256 represents the SCRAM-SHA-256 mechanism.
  56. SASLTypeSCRAMSHA256 = "SCRAM-SHA-256"
  57. // SASLTypeSCRAMSHA512 represents the SCRAM-SHA-512 mechanism.
  58. SASLTypeSCRAMSHA512 = "SCRAM-SHA-512"
  59. SASLTypeGSSAPI = "GSSAPI"
  60. // SASLHandshakeV0 is v0 of the Kafka SASL handshake protocol. Client and
  61. // server negotiate SASL auth using opaque packets.
  62. SASLHandshakeV0 = int16(0)
  63. // SASLHandshakeV1 is v1 of the Kafka SASL handshake protocol. Client and
  64. // server negotiate SASL by wrapping tokens with Kafka protocol headers.
  65. SASLHandshakeV1 = int16(1)
  66. // SASLExtKeyAuth is the reserved extension key name sent as part of the
  67. // SASL/OAUTHBEARER initial client response
  68. SASLExtKeyAuth = "auth"
  69. )
  70. // AccessToken contains an access token used to authenticate a
  71. // SASL/OAUTHBEARER client along with associated metadata.
  72. type AccessToken struct {
  73. // Token is the access token payload.
  74. Token string
  75. // Extensions is a optional map of arbitrary key-value pairs that can be
  76. // sent with the SASL/OAUTHBEARER initial client response. These values are
  77. // ignored by the SASL server if they are unexpected. This feature is only
  78. // supported by Kafka >= 2.1.0.
  79. Extensions map[string]string
  80. }
  81. // AccessTokenProvider is the interface that encapsulates how implementors
  82. // can generate access tokens for Kafka broker authentication.
  83. type AccessTokenProvider interface {
  84. // Token returns an access token. The implementation should ensure token
  85. // reuse so that multiple calls at connect time do not create multiple
  86. // tokens. The implementation should also periodically refresh the token in
  87. // order to guarantee that each call returns an unexpired token. This
  88. // method should not block indefinitely--a timeout error should be returned
  89. // after a short period of inactivity so that the broker connection logic
  90. // can log debugging information and retry.
  91. Token() (*AccessToken, error)
  92. }
  93. // SCRAMClient is a an interface to a SCRAM
  94. // client implementation.
  95. type SCRAMClient interface {
  96. // Begin prepares the client for the SCRAM exchange
  97. // with the server with a user name and a password
  98. Begin(userName, password, authzID string) error
  99. // Step steps client through the SCRAM exchange. It is
  100. // called repeatedly until it errors or `Done` returns true.
  101. Step(challenge string) (response string, err error)
  102. // Done should return true when the SCRAM conversation
  103. // is over.
  104. Done() bool
  105. }
  106. type responsePromise struct {
  107. requestTime time.Time
  108. correlationID int32
  109. headerVersion int16
  110. packets chan []byte
  111. errors chan error
  112. }
  113. // NewBroker creates and returns a Broker targeting the given host:port address.
  114. // This does not attempt to actually connect, you have to call Open() for that.
  115. func NewBroker(addr string) *Broker {
  116. return &Broker{id: -1, addr: addr}
  117. }
  118. // Open tries to connect to the Broker if it is not already connected or connecting, but does not block
  119. // waiting for the connection to complete. This means that any subsequent operations on the broker will
  120. // block waiting for the connection to succeed or fail. To get the effect of a fully synchronous Open call,
  121. // follow it by a call to Connected(). The only errors Open will return directly are ConfigurationError or
  122. // AlreadyConnected. If conf is nil, the result of NewConfig() is used.
  123. func (b *Broker) Open(conf *Config) error {
  124. if !atomic.CompareAndSwapInt32(&b.opened, 0, 1) {
  125. return ErrAlreadyConnected
  126. }
  127. if conf == nil {
  128. conf = NewConfig()
  129. }
  130. err := conf.Validate()
  131. if err != nil {
  132. return err
  133. }
  134. b.lock.Lock()
  135. go withRecover(func() {
  136. defer b.lock.Unlock()
  137. dialer := conf.getDialer()
  138. b.conn, b.connErr = dialer.Dial("tcp", b.addr)
  139. if b.connErr != nil {
  140. Logger.Printf("Failed to connect to broker %s: %s\n", b.addr, b.connErr)
  141. b.conn = nil
  142. atomic.StoreInt32(&b.opened, 0)
  143. return
  144. }
  145. if conf.Net.TLS.Enable {
  146. Logger.Printf("Using tls")
  147. b.conn = tls.Client(b.conn, conf.Net.TLS.Config)
  148. }
  149. b.conn = newBufConn(b.conn)
  150. b.conf = conf
  151. // Create or reuse the global metrics shared between brokers
  152. b.incomingByteRate = metrics.GetOrRegisterMeter("incoming-byte-rate", conf.MetricRegistry)
  153. b.requestRate = metrics.GetOrRegisterMeter("request-rate", conf.MetricRegistry)
  154. b.requestSize = getOrRegisterHistogram("request-size", conf.MetricRegistry)
  155. b.requestLatency = getOrRegisterHistogram("request-latency-in-ms", conf.MetricRegistry)
  156. b.outgoingByteRate = metrics.GetOrRegisterMeter("outgoing-byte-rate", conf.MetricRegistry)
  157. b.responseRate = metrics.GetOrRegisterMeter("response-rate", conf.MetricRegistry)
  158. b.responseSize = getOrRegisterHistogram("response-size", conf.MetricRegistry)
  159. b.requestsInFlight = metrics.GetOrRegisterCounter("requests-in-flight", conf.MetricRegistry)
  160. // Do not gather metrics for seeded broker (only used during bootstrap) because they share
  161. // the same id (-1) and are already exposed through the global metrics above
  162. if b.id >= 0 {
  163. b.registerMetrics()
  164. }
  165. if conf.Net.SASL.Enable {
  166. b.connErr = b.authenticateViaSASL()
  167. if b.connErr != nil {
  168. err = b.conn.Close()
  169. if err == nil {
  170. Logger.Printf("Closed connection to broker %s\n", b.addr)
  171. } else {
  172. Logger.Printf("Error while closing connection to broker %s: %s\n", b.addr, err)
  173. }
  174. b.conn = nil
  175. atomic.StoreInt32(&b.opened, 0)
  176. return
  177. }
  178. }
  179. b.done = make(chan bool)
  180. b.responses = make(chan responsePromise, b.conf.Net.MaxOpenRequests-1)
  181. if b.id >= 0 {
  182. Logger.Printf("Connected to broker at %s (registered as #%d)\n", b.addr, b.id)
  183. } else {
  184. Logger.Printf("Connected to broker at %s (unregistered)\n", b.addr)
  185. }
  186. go withRecover(b.responseReceiver)
  187. })
  188. return nil
  189. }
  190. // Connected returns true if the broker is connected and false otherwise. If the broker is not
  191. // connected but it had tried to connect, the error from that connection attempt is also returned.
  192. func (b *Broker) Connected() (bool, error) {
  193. b.lock.Lock()
  194. defer b.lock.Unlock()
  195. return b.conn != nil, b.connErr
  196. }
  197. //Close closes the broker resources
  198. func (b *Broker) Close() error {
  199. b.lock.Lock()
  200. defer b.lock.Unlock()
  201. if b.conn == nil {
  202. return ErrNotConnected
  203. }
  204. close(b.responses)
  205. <-b.done
  206. err := b.conn.Close()
  207. b.conn = nil
  208. b.connErr = nil
  209. b.done = nil
  210. b.responses = nil
  211. b.unregisterMetrics()
  212. if err == nil {
  213. Logger.Printf("Closed connection to broker %s\n", b.addr)
  214. } else {
  215. Logger.Printf("Error while closing connection to broker %s: %s\n", b.addr, err)
  216. }
  217. atomic.StoreInt32(&b.opened, 0)
  218. return err
  219. }
  220. // ID returns the broker ID retrieved from Kafka's metadata, or -1 if that is not known.
  221. func (b *Broker) ID() int32 {
  222. return b.id
  223. }
  224. // Addr returns the broker address as either retrieved from Kafka's metadata or passed to NewBroker.
  225. func (b *Broker) Addr() string {
  226. return b.addr
  227. }
  228. // Rack returns the broker's rack as retrieved from Kafka's metadata or the
  229. // empty string if it is not known. The returned value corresponds to the
  230. // broker's broker.rack configuration setting. Requires protocol version to be
  231. // at least v0.10.0.0.
  232. func (b *Broker) Rack() string {
  233. if b.rack == nil {
  234. return ""
  235. }
  236. return *b.rack
  237. }
  238. //GetMetadata send a metadata request and returns a metadata response or error
  239. func (b *Broker) GetMetadata(request *MetadataRequest) (*MetadataResponse, error) {
  240. response := new(MetadataResponse)
  241. err := b.sendAndReceive(request, response)
  242. if err != nil {
  243. return nil, err
  244. }
  245. return response, nil
  246. }
  247. //GetConsumerMetadata send a consumer metadata request and returns a consumer metadata response or error
  248. func (b *Broker) GetConsumerMetadata(request *ConsumerMetadataRequest) (*ConsumerMetadataResponse, error) {
  249. response := new(ConsumerMetadataResponse)
  250. err := b.sendAndReceive(request, response)
  251. if err != nil {
  252. return nil, err
  253. }
  254. return response, nil
  255. }
  256. //FindCoordinator sends a find coordinate request and returns a response or error
  257. func (b *Broker) FindCoordinator(request *FindCoordinatorRequest) (*FindCoordinatorResponse, error) {
  258. response := new(FindCoordinatorResponse)
  259. err := b.sendAndReceive(request, response)
  260. if err != nil {
  261. return nil, err
  262. }
  263. return response, nil
  264. }
  265. //GetAvailableOffsets return an offset response or error
  266. func (b *Broker) GetAvailableOffsets(request *OffsetRequest) (*OffsetResponse, error) {
  267. response := new(OffsetResponse)
  268. err := b.sendAndReceive(request, response)
  269. if err != nil {
  270. return nil, err
  271. }
  272. return response, nil
  273. }
  274. //Produce returns a produce response or error
  275. func (b *Broker) Produce(request *ProduceRequest) (*ProduceResponse, error) {
  276. var (
  277. response *ProduceResponse
  278. err error
  279. )
  280. if request.RequiredAcks == NoResponse {
  281. err = b.sendAndReceive(request, nil)
  282. } else {
  283. response = new(ProduceResponse)
  284. err = b.sendAndReceive(request, response)
  285. }
  286. if err != nil {
  287. return nil, err
  288. }
  289. return response, nil
  290. }
  291. //Fetch returns a FetchResponse or error
  292. func (b *Broker) Fetch(request *FetchRequest) (*FetchResponse, error) {
  293. response := new(FetchResponse)
  294. err := b.sendAndReceive(request, response)
  295. if err != nil {
  296. return nil, err
  297. }
  298. return response, nil
  299. }
  300. //CommitOffset return an Offset commit response or error
  301. func (b *Broker) CommitOffset(request *OffsetCommitRequest) (*OffsetCommitResponse, error) {
  302. response := new(OffsetCommitResponse)
  303. err := b.sendAndReceive(request, response)
  304. if err != nil {
  305. return nil, err
  306. }
  307. return response, nil
  308. }
  309. //FetchOffset returns an offset fetch response or error
  310. func (b *Broker) FetchOffset(request *OffsetFetchRequest) (*OffsetFetchResponse, error) {
  311. response := new(OffsetFetchResponse)
  312. err := b.sendAndReceive(request, response)
  313. if err != nil {
  314. return nil, err
  315. }
  316. return response, nil
  317. }
  318. //JoinGroup returns a join group response or error
  319. func (b *Broker) JoinGroup(request *JoinGroupRequest) (*JoinGroupResponse, error) {
  320. response := new(JoinGroupResponse)
  321. err := b.sendAndReceive(request, response)
  322. if err != nil {
  323. return nil, err
  324. }
  325. return response, nil
  326. }
  327. //SyncGroup returns a sync group response or error
  328. func (b *Broker) SyncGroup(request *SyncGroupRequest) (*SyncGroupResponse, error) {
  329. response := new(SyncGroupResponse)
  330. err := b.sendAndReceive(request, response)
  331. if err != nil {
  332. return nil, err
  333. }
  334. return response, nil
  335. }
  336. //LeaveGroup return a leave group response or error
  337. func (b *Broker) LeaveGroup(request *LeaveGroupRequest) (*LeaveGroupResponse, error) {
  338. response := new(LeaveGroupResponse)
  339. err := b.sendAndReceive(request, response)
  340. if err != nil {
  341. return nil, err
  342. }
  343. return response, nil
  344. }
  345. //Heartbeat returns a heartbeat response or error
  346. func (b *Broker) Heartbeat(request *HeartbeatRequest) (*HeartbeatResponse, error) {
  347. response := new(HeartbeatResponse)
  348. err := b.sendAndReceive(request, response)
  349. if err != nil {
  350. return nil, err
  351. }
  352. return response, nil
  353. }
  354. //ListGroups return a list group response or error
  355. func (b *Broker) ListGroups(request *ListGroupsRequest) (*ListGroupsResponse, error) {
  356. response := new(ListGroupsResponse)
  357. err := b.sendAndReceive(request, response)
  358. if err != nil {
  359. return nil, err
  360. }
  361. return response, nil
  362. }
  363. //DescribeGroups return describe group response or error
  364. func (b *Broker) DescribeGroups(request *DescribeGroupsRequest) (*DescribeGroupsResponse, error) {
  365. response := new(DescribeGroupsResponse)
  366. err := b.sendAndReceive(request, response)
  367. if err != nil {
  368. return nil, err
  369. }
  370. return response, nil
  371. }
  372. //ApiVersions return api version response or error
  373. func (b *Broker) ApiVersions(request *ApiVersionsRequest) (*ApiVersionsResponse, error) {
  374. response := new(ApiVersionsResponse)
  375. err := b.sendAndReceive(request, response)
  376. if err != nil {
  377. return nil, err
  378. }
  379. return response, nil
  380. }
  381. //CreateTopics send a create topic request and returns create topic response
  382. func (b *Broker) CreateTopics(request *CreateTopicsRequest) (*CreateTopicsResponse, error) {
  383. response := new(CreateTopicsResponse)
  384. err := b.sendAndReceive(request, response)
  385. if err != nil {
  386. return nil, err
  387. }
  388. return response, nil
  389. }
  390. //DeleteTopics sends a delete topic request and returns delete topic response
  391. func (b *Broker) DeleteTopics(request *DeleteTopicsRequest) (*DeleteTopicsResponse, error) {
  392. response := new(DeleteTopicsResponse)
  393. err := b.sendAndReceive(request, response)
  394. if err != nil {
  395. return nil, err
  396. }
  397. return response, nil
  398. }
  399. //CreatePartitions sends a create partition request and returns create
  400. //partitions response or error
  401. func (b *Broker) CreatePartitions(request *CreatePartitionsRequest) (*CreatePartitionsResponse, error) {
  402. response := new(CreatePartitionsResponse)
  403. err := b.sendAndReceive(request, response)
  404. if err != nil {
  405. return nil, err
  406. }
  407. return response, nil
  408. }
  409. //AlterPartitionReassignments sends a alter partition reassignments request and
  410. //returns alter partition reassignments response
  411. func (b *Broker) AlterPartitionReassignments(request *AlterPartitionReassignmentsRequest) (*AlterPartitionReassignmentsResponse, error) {
  412. response := new(AlterPartitionReassignmentsResponse)
  413. err := b.sendAndReceive(request, response)
  414. if err != nil {
  415. return nil, err
  416. }
  417. return response, nil
  418. }
  419. //ListPartitionReassignments sends a list partition reassignments request and
  420. //returns list partition reassignments response
  421. func (b *Broker) ListPartitionReassignments(request *ListPartitionReassignmentsRequest) (*ListPartitionReassignmentsResponse, error) {
  422. response := new(ListPartitionReassignmentsResponse)
  423. err := b.sendAndReceive(request, response)
  424. if err != nil {
  425. return nil, err
  426. }
  427. return response, nil
  428. }
  429. //DeleteRecords send a request to delete records and return delete record
  430. //response or error
  431. func (b *Broker) DeleteRecords(request *DeleteRecordsRequest) (*DeleteRecordsResponse, error) {
  432. response := new(DeleteRecordsResponse)
  433. err := b.sendAndReceive(request, response)
  434. if err != nil {
  435. return nil, err
  436. }
  437. return response, nil
  438. }
  439. //DescribeAcls sends a describe acl request and returns a response or error
  440. func (b *Broker) DescribeAcls(request *DescribeAclsRequest) (*DescribeAclsResponse, error) {
  441. response := new(DescribeAclsResponse)
  442. err := b.sendAndReceive(request, response)
  443. if err != nil {
  444. return nil, err
  445. }
  446. return response, nil
  447. }
  448. //CreateAcls sends a create acl request and returns a response or error
  449. func (b *Broker) CreateAcls(request *CreateAclsRequest) (*CreateAclsResponse, error) {
  450. response := new(CreateAclsResponse)
  451. err := b.sendAndReceive(request, response)
  452. if err != nil {
  453. return nil, err
  454. }
  455. return response, nil
  456. }
  457. //DeleteAcls sends a delete acl request and returns a response or error
  458. func (b *Broker) DeleteAcls(request *DeleteAclsRequest) (*DeleteAclsResponse, error) {
  459. response := new(DeleteAclsResponse)
  460. err := b.sendAndReceive(request, response)
  461. if err != nil {
  462. return nil, err
  463. }
  464. return response, nil
  465. }
  466. //InitProducerID sends an init producer request and returns a response or error
  467. func (b *Broker) InitProducerID(request *InitProducerIDRequest) (*InitProducerIDResponse, error) {
  468. response := new(InitProducerIDResponse)
  469. err := b.sendAndReceive(request, response)
  470. if err != nil {
  471. return nil, err
  472. }
  473. return response, nil
  474. }
  475. //AddPartitionsToTxn send a request to add partition to txn and returns
  476. //a response or error
  477. func (b *Broker) AddPartitionsToTxn(request *AddPartitionsToTxnRequest) (*AddPartitionsToTxnResponse, error) {
  478. response := new(AddPartitionsToTxnResponse)
  479. err := b.sendAndReceive(request, response)
  480. if err != nil {
  481. return nil, err
  482. }
  483. return response, nil
  484. }
  485. //AddOffsetsToTxn sends a request to add offsets to txn and returns a response
  486. //or error
  487. func (b *Broker) AddOffsetsToTxn(request *AddOffsetsToTxnRequest) (*AddOffsetsToTxnResponse, error) {
  488. response := new(AddOffsetsToTxnResponse)
  489. err := b.sendAndReceive(request, response)
  490. if err != nil {
  491. return nil, err
  492. }
  493. return response, nil
  494. }
  495. //EndTxn sends a request to end txn and returns a response or error
  496. func (b *Broker) EndTxn(request *EndTxnRequest) (*EndTxnResponse, error) {
  497. response := new(EndTxnResponse)
  498. err := b.sendAndReceive(request, response)
  499. if err != nil {
  500. return nil, err
  501. }
  502. return response, nil
  503. }
  504. //TxnOffsetCommit sends a request to commit transaction offsets and returns
  505. //a response or error
  506. func (b *Broker) TxnOffsetCommit(request *TxnOffsetCommitRequest) (*TxnOffsetCommitResponse, error) {
  507. response := new(TxnOffsetCommitResponse)
  508. err := b.sendAndReceive(request, response)
  509. if err != nil {
  510. return nil, err
  511. }
  512. return response, nil
  513. }
  514. //DescribeConfigs sends a request to describe config and returns a response or
  515. //error
  516. func (b *Broker) DescribeConfigs(request *DescribeConfigsRequest) (*DescribeConfigsResponse, error) {
  517. response := new(DescribeConfigsResponse)
  518. err := b.sendAndReceive(request, response)
  519. if err != nil {
  520. return nil, err
  521. }
  522. return response, nil
  523. }
  524. //AlterConfigs sends a request to alter config and return a response or error
  525. func (b *Broker) AlterConfigs(request *AlterConfigsRequest) (*AlterConfigsResponse, error) {
  526. response := new(AlterConfigsResponse)
  527. err := b.sendAndReceive(request, response)
  528. if err != nil {
  529. return nil, err
  530. }
  531. return response, nil
  532. }
  533. //DeleteGroups sends a request to delete groups and returns a response or error
  534. func (b *Broker) DeleteGroups(request *DeleteGroupsRequest) (*DeleteGroupsResponse, error) {
  535. response := new(DeleteGroupsResponse)
  536. if err := b.sendAndReceive(request, response); err != nil {
  537. return nil, err
  538. }
  539. return response, nil
  540. }
  541. //DescribeLogDirs sends a request to get the broker's log dir paths and sizes
  542. func (b *Broker) DescribeLogDirs(request *DescribeLogDirsRequest) (*DescribeLogDirsResponse, error) {
  543. response := new(DescribeLogDirsResponse)
  544. err := b.sendAndReceive(request, response)
  545. if err != nil {
  546. return nil, err
  547. }
  548. return response, nil
  549. }
  550. // readFull ensures the conn ReadDeadline has been setup before making a
  551. // call to io.ReadFull
  552. func (b *Broker) readFull(buf []byte) (n int, err error) {
  553. if err := b.conn.SetReadDeadline(time.Now().Add(b.conf.Net.ReadTimeout)); err != nil {
  554. return 0, err
  555. }
  556. return io.ReadFull(b.conn, buf)
  557. }
  558. // write ensures the conn WriteDeadline has been setup before making a
  559. // call to conn.Write
  560. func (b *Broker) write(buf []byte) (n int, err error) {
  561. if err := b.conn.SetWriteDeadline(time.Now().Add(b.conf.Net.WriteTimeout)); err != nil {
  562. return 0, err
  563. }
  564. return b.conn.Write(buf)
  565. }
  566. func (b *Broker) send(rb protocolBody, promiseResponse bool, responseHeaderVersion int16) (*responsePromise, error) {
  567. b.lock.Lock()
  568. defer b.lock.Unlock()
  569. if b.conn == nil {
  570. if b.connErr != nil {
  571. return nil, b.connErr
  572. }
  573. return nil, ErrNotConnected
  574. }
  575. if !b.conf.Version.IsAtLeast(rb.requiredVersion()) {
  576. return nil, ErrUnsupportedVersion
  577. }
  578. req := &request{correlationID: b.correlationID, clientID: b.conf.ClientID, body: rb}
  579. buf, err := encode(req, b.conf.MetricRegistry)
  580. if err != nil {
  581. return nil, err
  582. }
  583. requestTime := time.Now()
  584. // Will be decremented in responseReceiver (except error or request with NoResponse)
  585. b.addRequestInFlightMetrics(1)
  586. bytes, err := b.write(buf)
  587. b.updateOutgoingCommunicationMetrics(bytes)
  588. if err != nil {
  589. b.addRequestInFlightMetrics(-1)
  590. return nil, err
  591. }
  592. b.correlationID++
  593. if !promiseResponse {
  594. // Record request latency without the response
  595. b.updateRequestLatencyAndInFlightMetrics(time.Since(requestTime))
  596. return nil, nil
  597. }
  598. promise := responsePromise{requestTime, req.correlationID, responseHeaderVersion, make(chan []byte), make(chan error)}
  599. b.responses <- promise
  600. return &promise, nil
  601. }
  602. func (b *Broker) sendAndReceive(req protocolBody, res protocolBody) error {
  603. responseHeaderVersion := int16(-1)
  604. if res != nil {
  605. responseHeaderVersion = res.headerVersion()
  606. }
  607. promise, err := b.send(req, res != nil, responseHeaderVersion)
  608. if err != nil {
  609. return err
  610. }
  611. if promise == nil {
  612. return nil
  613. }
  614. select {
  615. case buf := <-promise.packets:
  616. return versionedDecode(buf, res, req.version())
  617. case err = <-promise.errors:
  618. return err
  619. }
  620. }
  621. func (b *Broker) decode(pd packetDecoder, version int16) (err error) {
  622. b.id, err = pd.getInt32()
  623. if err != nil {
  624. return err
  625. }
  626. host, err := pd.getString()
  627. if err != nil {
  628. return err
  629. }
  630. port, err := pd.getInt32()
  631. if err != nil {
  632. return err
  633. }
  634. if version >= 1 {
  635. b.rack, err = pd.getNullableString()
  636. if err != nil {
  637. return err
  638. }
  639. }
  640. b.addr = net.JoinHostPort(host, fmt.Sprint(port))
  641. if _, _, err := net.SplitHostPort(b.addr); err != nil {
  642. return err
  643. }
  644. return nil
  645. }
  646. func (b *Broker) encode(pe packetEncoder, version int16) (err error) {
  647. host, portstr, err := net.SplitHostPort(b.addr)
  648. if err != nil {
  649. return err
  650. }
  651. port, err := strconv.Atoi(portstr)
  652. if err != nil {
  653. return err
  654. }
  655. pe.putInt32(b.id)
  656. err = pe.putString(host)
  657. if err != nil {
  658. return err
  659. }
  660. pe.putInt32(int32(port))
  661. if version >= 1 {
  662. err = pe.putNullableString(b.rack)
  663. if err != nil {
  664. return err
  665. }
  666. }
  667. return nil
  668. }
  669. func (b *Broker) responseReceiver() {
  670. var dead error
  671. for response := range b.responses {
  672. if dead != nil {
  673. // This was previously incremented in send() and
  674. // we are not calling updateIncomingCommunicationMetrics()
  675. b.addRequestInFlightMetrics(-1)
  676. response.errors <- dead
  677. continue
  678. }
  679. var headerLength = getHeaderLength(response.headerVersion)
  680. header := make([]byte, headerLength)
  681. bytesReadHeader, err := b.readFull(header)
  682. requestLatency := time.Since(response.requestTime)
  683. if err != nil {
  684. b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency)
  685. dead = err
  686. response.errors <- err
  687. continue
  688. }
  689. decodedHeader := responseHeader{}
  690. err = versionedDecode(header, &decodedHeader, response.headerVersion)
  691. if err != nil {
  692. b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency)
  693. dead = err
  694. response.errors <- err
  695. continue
  696. }
  697. if decodedHeader.correlationID != response.correlationID {
  698. b.updateIncomingCommunicationMetrics(bytesReadHeader, requestLatency)
  699. // TODO if decoded ID < cur ID, discard until we catch up
  700. // TODO if decoded ID > cur ID, save it so when cur ID catches up we have a response
  701. dead = PacketDecodingError{fmt.Sprintf("correlation ID didn't match, wanted %d, got %d", response.correlationID, decodedHeader.correlationID)}
  702. response.errors <- dead
  703. continue
  704. }
  705. buf := make([]byte, decodedHeader.length-int32(headerLength)+4)
  706. bytesReadBody, err := b.readFull(buf)
  707. b.updateIncomingCommunicationMetrics(bytesReadHeader+bytesReadBody, requestLatency)
  708. if err != nil {
  709. dead = err
  710. response.errors <- err
  711. continue
  712. }
  713. response.packets <- buf
  714. }
  715. close(b.done)
  716. }
  717. func getHeaderLength(headerVersion int16) int8 {
  718. if headerVersion < 1 {
  719. return 8
  720. } else {
  721. // header contains additional tagged field length (0), we don't support actual tags yet.
  722. return 9
  723. }
  724. }
  725. func (b *Broker) authenticateViaSASL() error {
  726. switch b.conf.Net.SASL.Mechanism {
  727. case SASLTypeOAuth:
  728. return b.sendAndReceiveSASLOAuth(b.conf.Net.SASL.TokenProvider)
  729. case SASLTypeSCRAMSHA256, SASLTypeSCRAMSHA512:
  730. return b.sendAndReceiveSASLSCRAMv1()
  731. case SASLTypeGSSAPI:
  732. return b.sendAndReceiveKerberos()
  733. default:
  734. return b.sendAndReceiveSASLPlainAuth()
  735. }
  736. }
  737. func (b *Broker) sendAndReceiveKerberos() error {
  738. b.kerberosAuthenticator.Config = &b.conf.Net.SASL.GSSAPI
  739. if b.kerberosAuthenticator.NewKerberosClientFunc == nil {
  740. b.kerberosAuthenticator.NewKerberosClientFunc = NewKerberosClient
  741. }
  742. return b.kerberosAuthenticator.Authorize(b)
  743. }
  744. func (b *Broker) sendAndReceiveSASLHandshake(saslType SASLMechanism, version int16) error {
  745. rb := &SaslHandshakeRequest{Mechanism: string(saslType), Version: version}
  746. req := &request{correlationID: b.correlationID, clientID: b.conf.ClientID, body: rb}
  747. buf, err := encode(req, b.conf.MetricRegistry)
  748. if err != nil {
  749. return err
  750. }
  751. requestTime := time.Now()
  752. // Will be decremented in updateIncomingCommunicationMetrics (except error)
  753. b.addRequestInFlightMetrics(1)
  754. bytes, err := b.write(buf)
  755. b.updateOutgoingCommunicationMetrics(bytes)
  756. if err != nil {
  757. b.addRequestInFlightMetrics(-1)
  758. Logger.Printf("Failed to send SASL handshake %s: %s\n", b.addr, err.Error())
  759. return err
  760. }
  761. b.correlationID++
  762. header := make([]byte, 8) // response header
  763. _, err = b.readFull(header)
  764. if err != nil {
  765. b.addRequestInFlightMetrics(-1)
  766. Logger.Printf("Failed to read SASL handshake header : %s\n", err.Error())
  767. return err
  768. }
  769. length := binary.BigEndian.Uint32(header[:4])
  770. payload := make([]byte, length-4)
  771. n, err := b.readFull(payload)
  772. if err != nil {
  773. b.addRequestInFlightMetrics(-1)
  774. Logger.Printf("Failed to read SASL handshake payload : %s\n", err.Error())
  775. return err
  776. }
  777. b.updateIncomingCommunicationMetrics(n+8, time.Since(requestTime))
  778. res := &SaslHandshakeResponse{}
  779. err = versionedDecode(payload, res, 0)
  780. if err != nil {
  781. Logger.Printf("Failed to parse SASL handshake : %s\n", err.Error())
  782. return err
  783. }
  784. if res.Err != ErrNoError {
  785. Logger.Printf("Invalid SASL Mechanism : %s\n", res.Err.Error())
  786. return res.Err
  787. }
  788. Logger.Print("Successful SASL handshake. Available mechanisms: ", res.EnabledMechanisms)
  789. return nil
  790. }
  791. // Kafka 0.10.x supported SASL PLAIN/Kerberos via KAFKA-3149 (KIP-43).
  792. // Kafka 1.x.x onward added a SaslAuthenticate request/response message which
  793. // wraps the SASL flow in the Kafka protocol, which allows for returning
  794. // meaningful errors on authentication failure.
  795. //
  796. // In SASL Plain, Kafka expects the auth header to be in the following format
  797. // Message format (from https://tools.ietf.org/html/rfc4616):
  798. //
  799. // message = [authzid] UTF8NUL authcid UTF8NUL passwd
  800. // authcid = 1*SAFE ; MUST accept up to 255 octets
  801. // authzid = 1*SAFE ; MUST accept up to 255 octets
  802. // passwd = 1*SAFE ; MUST accept up to 255 octets
  803. // UTF8NUL = %x00 ; UTF-8 encoded NUL character
  804. //
  805. // SAFE = UTF1 / UTF2 / UTF3 / UTF4
  806. // ;; any UTF-8 encoded Unicode character except NUL
  807. //
  808. // With SASL v0 handshake and auth then:
  809. // When credentials are valid, Kafka returns a 4 byte array of null characters.
  810. // When credentials are invalid, Kafka closes the connection.
  811. //
  812. // With SASL v1 handshake and auth then:
  813. // When credentials are invalid, Kafka replies with a SaslAuthenticate response
  814. // containing an error code and message detailing the authentication failure.
  815. func (b *Broker) sendAndReceiveSASLPlainAuth() error {
  816. // default to V0 to allow for backward compatibility when SASL is enabled
  817. // but not the handshake
  818. if b.conf.Net.SASL.Handshake {
  819. handshakeErr := b.sendAndReceiveSASLHandshake(SASLTypePlaintext, b.conf.Net.SASL.Version)
  820. if handshakeErr != nil {
  821. Logger.Printf("Error while performing SASL handshake %s\n", b.addr)
  822. return handshakeErr
  823. }
  824. }
  825. if b.conf.Net.SASL.Version == SASLHandshakeV1 {
  826. return b.sendAndReceiveV1SASLPlainAuth()
  827. }
  828. return b.sendAndReceiveV0SASLPlainAuth()
  829. }
  830. // sendAndReceiveV0SASLPlainAuth flows the v0 sasl auth NOT wrapped in the kafka protocol
  831. func (b *Broker) sendAndReceiveV0SASLPlainAuth() error {
  832. length := len(b.conf.Net.SASL.AuthIdentity) + 1 + len(b.conf.Net.SASL.User) + 1 + len(b.conf.Net.SASL.Password)
  833. authBytes := make([]byte, length+4) //4 byte length header + auth data
  834. binary.BigEndian.PutUint32(authBytes, uint32(length))
  835. copy(authBytes[4:], []byte(b.conf.Net.SASL.AuthIdentity+"\x00"+b.conf.Net.SASL.User+"\x00"+b.conf.Net.SASL.Password))
  836. requestTime := time.Now()
  837. // Will be decremented in updateIncomingCommunicationMetrics (except error)
  838. b.addRequestInFlightMetrics(1)
  839. bytesWritten, err := b.write(authBytes)
  840. b.updateOutgoingCommunicationMetrics(bytesWritten)
  841. if err != nil {
  842. b.addRequestInFlightMetrics(-1)
  843. Logger.Printf("Failed to write SASL auth header to broker %s: %s\n", b.addr, err.Error())
  844. return err
  845. }
  846. header := make([]byte, 4)
  847. n, err := b.readFull(header)
  848. b.updateIncomingCommunicationMetrics(n, time.Since(requestTime))
  849. // If the credentials are valid, we would get a 4 byte response filled with null characters.
  850. // Otherwise, the broker closes the connection and we get an EOF
  851. if err != nil {
  852. Logger.Printf("Failed to read response while authenticating with SASL to broker %s: %s\n", b.addr, err.Error())
  853. return err
  854. }
  855. Logger.Printf("SASL authentication successful with broker %s:%v - %v\n", b.addr, n, header)
  856. return nil
  857. }
  858. // sendAndReceiveV1SASLPlainAuth flows the v1 sasl authentication using the kafka protocol
  859. func (b *Broker) sendAndReceiveV1SASLPlainAuth() error {
  860. correlationID := b.correlationID
  861. requestTime := time.Now()
  862. // Will be decremented in updateIncomingCommunicationMetrics (except error)
  863. b.addRequestInFlightMetrics(1)
  864. bytesWritten, err := b.sendSASLPlainAuthClientResponse(correlationID)
  865. b.updateOutgoingCommunicationMetrics(bytesWritten)
  866. if err != nil {
  867. b.addRequestInFlightMetrics(-1)
  868. Logger.Printf("Failed to write SASL auth header to broker %s: %s\n", b.addr, err.Error())
  869. return err
  870. }
  871. b.correlationID++
  872. bytesRead, err := b.receiveSASLServerResponse(&SaslAuthenticateResponse{}, correlationID)
  873. b.updateIncomingCommunicationMetrics(bytesRead, time.Since(requestTime))
  874. // With v1 sasl we get an error message set in the response we can return
  875. if err != nil {
  876. Logger.Printf("Error returned from broker during SASL flow %s: %s\n", b.addr, err.Error())
  877. return err
  878. }
  879. return nil
  880. }
  881. // sendAndReceiveSASLOAuth performs the authentication flow as described by KIP-255
  882. // https://cwiki.apache.org/confluence/pages/viewpage.action?pageId=75968876
  883. func (b *Broker) sendAndReceiveSASLOAuth(provider AccessTokenProvider) error {
  884. if err := b.sendAndReceiveSASLHandshake(SASLTypeOAuth, SASLHandshakeV1); err != nil {
  885. return err
  886. }
  887. token, err := provider.Token()
  888. if err != nil {
  889. return err
  890. }
  891. message, err := buildClientFirstMessage(token)
  892. if err != nil {
  893. return err
  894. }
  895. challenged, err := b.sendClientMessage(message)
  896. if err != nil {
  897. return err
  898. }
  899. if challenged {
  900. // Abort the token exchange. The broker returns the failure code.
  901. _, err = b.sendClientMessage([]byte(`\x01`))
  902. }
  903. return err
  904. }
  905. // sendClientMessage sends a SASL/OAUTHBEARER client message and returns true
  906. // if the broker responds with a challenge, in which case the token is
  907. // rejected.
  908. func (b *Broker) sendClientMessage(message []byte) (bool, error) {
  909. requestTime := time.Now()
  910. // Will be decremented in updateIncomingCommunicationMetrics (except error)
  911. b.addRequestInFlightMetrics(1)
  912. correlationID := b.correlationID
  913. bytesWritten, err := b.sendSASLOAuthBearerClientMessage(message, correlationID)
  914. b.updateOutgoingCommunicationMetrics(bytesWritten)
  915. if err != nil {
  916. b.addRequestInFlightMetrics(-1)
  917. return false, err
  918. }
  919. b.correlationID++
  920. res := &SaslAuthenticateResponse{}
  921. bytesRead, err := b.receiveSASLServerResponse(res, correlationID)
  922. requestLatency := time.Since(requestTime)
  923. b.updateIncomingCommunicationMetrics(bytesRead, requestLatency)
  924. isChallenge := len(res.SaslAuthBytes) > 0
  925. if isChallenge && err != nil {
  926. Logger.Printf("Broker rejected authentication token: %s", res.SaslAuthBytes)
  927. }
  928. return isChallenge, err
  929. }
  930. func (b *Broker) sendAndReceiveSASLSCRAMv1() error {
  931. if err := b.sendAndReceiveSASLHandshake(b.conf.Net.SASL.Mechanism, SASLHandshakeV1); err != nil {
  932. return err
  933. }
  934. scramClient := b.conf.Net.SASL.SCRAMClientGeneratorFunc()
  935. if err := scramClient.Begin(b.conf.Net.SASL.User, b.conf.Net.SASL.Password, b.conf.Net.SASL.SCRAMAuthzID); err != nil {
  936. return fmt.Errorf("failed to start SCRAM exchange with the server: %s", err.Error())
  937. }
  938. msg, err := scramClient.Step("")
  939. if err != nil {
  940. return fmt.Errorf("failed to advance the SCRAM exchange: %s", err.Error())
  941. }
  942. for !scramClient.Done() {
  943. requestTime := time.Now()
  944. // Will be decremented in updateIncomingCommunicationMetrics (except error)
  945. b.addRequestInFlightMetrics(1)
  946. correlationID := b.correlationID
  947. bytesWritten, err := b.sendSaslAuthenticateRequest(correlationID, []byte(msg))
  948. b.updateOutgoingCommunicationMetrics(bytesWritten)
  949. if err != nil {
  950. b.addRequestInFlightMetrics(-1)
  951. Logger.Printf("Failed to write SASL auth header to broker %s: %s\n", b.addr, err.Error())
  952. return err
  953. }
  954. b.correlationID++
  955. challenge, err := b.receiveSaslAuthenticateResponse(correlationID)
  956. if err != nil {
  957. b.addRequestInFlightMetrics(-1)
  958. Logger.Printf("Failed to read response while authenticating with SASL to broker %s: %s\n", b.addr, err.Error())
  959. return err
  960. }
  961. b.updateIncomingCommunicationMetrics(len(challenge), time.Since(requestTime))
  962. msg, err = scramClient.Step(string(challenge))
  963. if err != nil {
  964. Logger.Println("SASL authentication failed", err)
  965. return err
  966. }
  967. }
  968. Logger.Println("SASL authentication succeeded")
  969. return nil
  970. }
  971. func (b *Broker) sendSaslAuthenticateRequest(correlationID int32, msg []byte) (int, error) {
  972. rb := &SaslAuthenticateRequest{msg}
  973. req := &request{correlationID: correlationID, clientID: b.conf.ClientID, body: rb}
  974. buf, err := encode(req, b.conf.MetricRegistry)
  975. if err != nil {
  976. return 0, err
  977. }
  978. return b.write(buf)
  979. }
  980. func (b *Broker) receiveSaslAuthenticateResponse(correlationID int32) ([]byte, error) {
  981. buf := make([]byte, responseLengthSize+correlationIDSize)
  982. _, err := b.readFull(buf)
  983. if err != nil {
  984. return nil, err
  985. }
  986. header := responseHeader{}
  987. err = versionedDecode(buf, &header, 0)
  988. if err != nil {
  989. return nil, err
  990. }
  991. if header.correlationID != correlationID {
  992. return nil, fmt.Errorf("correlation ID didn't match, wanted %d, got %d", b.correlationID, header.correlationID)
  993. }
  994. buf = make([]byte, header.length-correlationIDSize)
  995. _, err = b.readFull(buf)
  996. if err != nil {
  997. return nil, err
  998. }
  999. res := &SaslAuthenticateResponse{}
  1000. if err := versionedDecode(buf, res, 0); err != nil {
  1001. return nil, err
  1002. }
  1003. if res.Err != ErrNoError {
  1004. return nil, res.Err
  1005. }
  1006. return res.SaslAuthBytes, nil
  1007. }
  1008. // Build SASL/OAUTHBEARER initial client response as described by RFC-7628
  1009. // https://tools.ietf.org/html/rfc7628
  1010. func buildClientFirstMessage(token *AccessToken) ([]byte, error) {
  1011. var ext string
  1012. if token.Extensions != nil && len(token.Extensions) > 0 {
  1013. if _, ok := token.Extensions[SASLExtKeyAuth]; ok {
  1014. return []byte{}, fmt.Errorf("the extension `%s` is invalid", SASLExtKeyAuth)
  1015. }
  1016. ext = "\x01" + mapToString(token.Extensions, "=", "\x01")
  1017. }
  1018. resp := []byte(fmt.Sprintf("n,,\x01auth=Bearer %s%s\x01\x01", token.Token, ext))
  1019. return resp, nil
  1020. }
  1021. // mapToString returns a list of key-value pairs ordered by key.
  1022. // keyValSep separates the key from the value. elemSep separates each pair.
  1023. func mapToString(extensions map[string]string, keyValSep string, elemSep string) string {
  1024. buf := make([]string, 0, len(extensions))
  1025. for k, v := range extensions {
  1026. buf = append(buf, k+keyValSep+v)
  1027. }
  1028. sort.Strings(buf)
  1029. return strings.Join(buf, elemSep)
  1030. }
  1031. func (b *Broker) sendSASLPlainAuthClientResponse(correlationID int32) (int, error) {
  1032. authBytes := []byte(b.conf.Net.SASL.AuthIdentity + "\x00" + b.conf.Net.SASL.User + "\x00" + b.conf.Net.SASL.Password)
  1033. rb := &SaslAuthenticateRequest{authBytes}
  1034. req := &request{correlationID: correlationID, clientID: b.conf.ClientID, body: rb}
  1035. buf, err := encode(req, b.conf.MetricRegistry)
  1036. if err != nil {
  1037. return 0, err
  1038. }
  1039. return b.write(buf)
  1040. }
  1041. func (b *Broker) sendSASLOAuthBearerClientMessage(initialResp []byte, correlationID int32) (int, error) {
  1042. rb := &SaslAuthenticateRequest{initialResp}
  1043. req := &request{correlationID: correlationID, clientID: b.conf.ClientID, body: rb}
  1044. buf, err := encode(req, b.conf.MetricRegistry)
  1045. if err != nil {
  1046. return 0, err
  1047. }
  1048. return b.write(buf)
  1049. }
  1050. func (b *Broker) receiveSASLServerResponse(res *SaslAuthenticateResponse, correlationID int32) (int, error) {
  1051. buf := make([]byte, responseLengthSize+correlationIDSize)
  1052. bytesRead, err := b.readFull(buf)
  1053. if err != nil {
  1054. return bytesRead, err
  1055. }
  1056. header := responseHeader{}
  1057. err = versionedDecode(buf, &header, 0)
  1058. if err != nil {
  1059. return bytesRead, err
  1060. }
  1061. if header.correlationID != correlationID {
  1062. return bytesRead, fmt.Errorf("correlation ID didn't match, wanted %d, got %d", b.correlationID, header.correlationID)
  1063. }
  1064. buf = make([]byte, header.length-correlationIDSize)
  1065. c, err := b.readFull(buf)
  1066. bytesRead += c
  1067. if err != nil {
  1068. return bytesRead, err
  1069. }
  1070. if err := versionedDecode(buf, res, 0); err != nil {
  1071. return bytesRead, err
  1072. }
  1073. if res.Err != ErrNoError {
  1074. return bytesRead, res.Err
  1075. }
  1076. return bytesRead, nil
  1077. }
  1078. func (b *Broker) updateIncomingCommunicationMetrics(bytes int, requestLatency time.Duration) {
  1079. b.updateRequestLatencyAndInFlightMetrics(requestLatency)
  1080. b.responseRate.Mark(1)
  1081. if b.brokerResponseRate != nil {
  1082. b.brokerResponseRate.Mark(1)
  1083. }
  1084. responseSize := int64(bytes)
  1085. b.incomingByteRate.Mark(responseSize)
  1086. if b.brokerIncomingByteRate != nil {
  1087. b.brokerIncomingByteRate.Mark(responseSize)
  1088. }
  1089. b.responseSize.Update(responseSize)
  1090. if b.brokerResponseSize != nil {
  1091. b.brokerResponseSize.Update(responseSize)
  1092. }
  1093. }
  1094. func (b *Broker) updateRequestLatencyAndInFlightMetrics(requestLatency time.Duration) {
  1095. requestLatencyInMs := int64(requestLatency / time.Millisecond)
  1096. b.requestLatency.Update(requestLatencyInMs)
  1097. if b.brokerRequestLatency != nil {
  1098. b.brokerRequestLatency.Update(requestLatencyInMs)
  1099. }
  1100. b.addRequestInFlightMetrics(-1)
  1101. }
  1102. func (b *Broker) addRequestInFlightMetrics(i int64) {
  1103. b.requestsInFlight.Inc(i)
  1104. if b.brokerRequestsInFlight != nil {
  1105. b.brokerRequestsInFlight.Inc(i)
  1106. }
  1107. }
  1108. func (b *Broker) updateOutgoingCommunicationMetrics(bytes int) {
  1109. b.requestRate.Mark(1)
  1110. if b.brokerRequestRate != nil {
  1111. b.brokerRequestRate.Mark(1)
  1112. }
  1113. requestSize := int64(bytes)
  1114. b.outgoingByteRate.Mark(requestSize)
  1115. if b.brokerOutgoingByteRate != nil {
  1116. b.brokerOutgoingByteRate.Mark(requestSize)
  1117. }
  1118. b.requestSize.Update(requestSize)
  1119. if b.brokerRequestSize != nil {
  1120. b.brokerRequestSize.Update(requestSize)
  1121. }
  1122. }
  1123. func (b *Broker) registerMetrics() {
  1124. b.brokerIncomingByteRate = b.registerMeter("incoming-byte-rate")
  1125. b.brokerRequestRate = b.registerMeter("request-rate")
  1126. b.brokerRequestSize = b.registerHistogram("request-size")
  1127. b.brokerRequestLatency = b.registerHistogram("request-latency-in-ms")
  1128. b.brokerOutgoingByteRate = b.registerMeter("outgoing-byte-rate")
  1129. b.brokerResponseRate = b.registerMeter("response-rate")
  1130. b.brokerResponseSize = b.registerHistogram("response-size")
  1131. b.brokerRequestsInFlight = b.registerCounter("requests-in-flight")
  1132. }
  1133. func (b *Broker) unregisterMetrics() {
  1134. for _, name := range b.registeredMetrics {
  1135. b.conf.MetricRegistry.Unregister(name)
  1136. }
  1137. b.registeredMetrics = nil
  1138. }
  1139. func (b *Broker) registerMeter(name string) metrics.Meter {
  1140. nameForBroker := getMetricNameForBroker(name, b)
  1141. b.registeredMetrics = append(b.registeredMetrics, nameForBroker)
  1142. return metrics.GetOrRegisterMeter(nameForBroker, b.conf.MetricRegistry)
  1143. }
  1144. func (b *Broker) registerHistogram(name string) metrics.Histogram {
  1145. nameForBroker := getMetricNameForBroker(name, b)
  1146. b.registeredMetrics = append(b.registeredMetrics, nameForBroker)
  1147. return getOrRegisterHistogram(nameForBroker, b.conf.MetricRegistry)
  1148. }
  1149. func (b *Broker) registerCounter(name string) metrics.Counter {
  1150. nameForBroker := getMetricNameForBroker(name, b)
  1151. b.registeredMetrics = append(b.registeredMetrics, nameForBroker)
  1152. return metrics.GetOrRegisterCounter(nameForBroker, b.conf.MetricRegistry)
  1153. }