admin.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686
  1. package sarama
  2. import (
  3. "errors"
  4. "math/rand"
  5. "sync"
  6. )
  7. // ClusterAdmin is the administrative client for Kafka, which supports managing and inspecting topics,
  8. // brokers, configurations and ACLs. The minimum broker version required is 0.10.0.0.
  9. // Methods with stricter requirements will specify the minimum broker version required.
  10. // You MUST call Close() on a client to avoid leaks
  11. type ClusterAdmin interface {
  12. // Creates a new topic. This operation is supported by brokers with version 0.10.1.0 or higher.
  13. // It may take several seconds after CreateTopic returns success for all the brokers
  14. // to become aware that the topic has been created. During this time, listTopics
  15. // may not return information about the new topic.The validateOnly option is supported from version 0.10.2.0.
  16. CreateTopic(topic string, detail *TopicDetail, validateOnly bool) error
  17. // List the topics available in the cluster with the default options.
  18. ListTopics() (map[string]TopicDetail, error)
  19. // Describe some topics in the cluster.
  20. DescribeTopics(topics []string) (metadata []*TopicMetadata, err error)
  21. // Delete a topic. It may take several seconds after the DeleteTopic to returns success
  22. // and for all the brokers to become aware that the topics are gone.
  23. // During this time, listTopics may continue to return information about the deleted topic.
  24. // If delete.topic.enable is false on the brokers, deleteTopic will mark
  25. // the topic for deletion, but not actually delete them.
  26. // This operation is supported by brokers with version 0.10.1.0 or higher.
  27. DeleteTopic(topic string) error
  28. // Increase the number of partitions of the topics according to the corresponding values.
  29. // If partitions are increased for a topic that has a key, the partition logic or ordering of
  30. // the messages will be affected. It may take several seconds after this method returns
  31. // success for all the brokers to become aware that the partitions have been created.
  32. // During this time, ClusterAdmin#describeTopics may not return information about the
  33. // new partitions. This operation is supported by brokers with version 1.0.0 or higher.
  34. CreatePartitions(topic string, count int32, assignment [][]int32, validateOnly bool) error
  35. // Delete records whose offset is smaller than the given offset of the corresponding partition.
  36. // This operation is supported by brokers with version 0.11.0.0 or higher.
  37. DeleteRecords(topic string, partitionOffsets map[int32]int64) error
  38. // Get the configuration for the specified resources.
  39. // The returned configuration includes default values and the Default is true
  40. // can be used to distinguish them from user supplied values.
  41. // Config entries where ReadOnly is true cannot be updated.
  42. // The value of config entries where Sensitive is true is always nil so
  43. // sensitive information is not disclosed.
  44. // This operation is supported by brokers with version 0.11.0.0 or higher.
  45. DescribeConfig(resource ConfigResource) ([]ConfigEntry, error)
  46. // Update the configuration for the specified resources with the default options.
  47. // This operation is supported by brokers with version 0.11.0.0 or higher.
  48. // The resources with their configs (topic is the only resource type with configs
  49. // that can be updated currently Updates are not transactional so they may succeed
  50. // for some resources while fail for others. The configs for a particular resource are updated automatically.
  51. AlterConfig(resourceType ConfigResourceType, name string, entries map[string]*string, validateOnly bool) error
  52. // Creates access control lists (ACLs) which are bound to specific resources.
  53. // This operation is not transactional so it may succeed for some ACLs while fail for others.
  54. // If you attempt to add an ACL that duplicates an existing ACL, no error will be raised, but
  55. // no changes will be made. This operation is supported by brokers with version 0.11.0.0 or higher.
  56. CreateACL(resource Resource, acl Acl) error
  57. // Lists access control lists (ACLs) according to the supplied filter.
  58. // it may take some time for changes made by createAcls or deleteAcls to be reflected in the output of ListAcls
  59. // This operation is supported by brokers with version 0.11.0.0 or higher.
  60. ListAcls(filter AclFilter) ([]ResourceAcls, error)
  61. // Deletes access control lists (ACLs) according to the supplied filters.
  62. // This operation is not transactional so it may succeed for some ACLs while fail for others.
  63. // This operation is supported by brokers with version 0.11.0.0 or higher.
  64. DeleteACL(filter AclFilter, validateOnly bool) ([]MatchingAcl, error)
  65. // List the consumer groups available in the cluster.
  66. ListConsumerGroups() (map[string]string, error)
  67. // Describe the given consumer groups.
  68. DescribeConsumerGroups(groups []string) ([]*GroupDescription, error)
  69. // List the consumer group offsets available in the cluster.
  70. ListConsumerGroupOffsets(group string, topicPartitions map[string][]int32) (*OffsetFetchResponse, error)
  71. // Delete a consumer group.
  72. DeleteConsumerGroup(group string) error
  73. // Get information about the nodes in the cluster
  74. DescribeCluster() (brokers []*Broker, controllerID int32, err error)
  75. // Close shuts down the admin and closes underlying client.
  76. Close() error
  77. }
  78. type clusterAdmin struct {
  79. client Client
  80. conf *Config
  81. }
  82. // NewClusterAdmin creates a new ClusterAdmin using the given broker addresses and configuration.
  83. func NewClusterAdmin(addrs []string, conf *Config) (ClusterAdmin, error) {
  84. client, err := NewClient(addrs, conf)
  85. if err != nil {
  86. return nil, err
  87. }
  88. return NewClusterAdminFromClient(client)
  89. }
  90. // NewClusterAdminFromClient creates a new ClusterAdmin using the given client.
  91. // Note that underlying client will also be closed on admin's Close() call.
  92. func NewClusterAdminFromClient(client Client) (ClusterAdmin, error) {
  93. //make sure we can retrieve the controller
  94. _, err := client.Controller()
  95. if err != nil {
  96. return nil, err
  97. }
  98. ca := &clusterAdmin{
  99. client: client,
  100. conf: client.Config(),
  101. }
  102. return ca, nil
  103. }
  104. func (ca *clusterAdmin) Close() error {
  105. return ca.client.Close()
  106. }
  107. func (ca *clusterAdmin) Controller() (*Broker, error) {
  108. return ca.client.Controller()
  109. }
  110. func (ca *clusterAdmin) CreateTopic(topic string, detail *TopicDetail, validateOnly bool) error {
  111. if topic == "" {
  112. return ErrInvalidTopic
  113. }
  114. if detail == nil {
  115. return errors.New("you must specify topic details")
  116. }
  117. topicDetails := make(map[string]*TopicDetail)
  118. topicDetails[topic] = detail
  119. request := &CreateTopicsRequest{
  120. TopicDetails: topicDetails,
  121. ValidateOnly: validateOnly,
  122. Timeout: ca.conf.Admin.Timeout,
  123. }
  124. if ca.conf.Version.IsAtLeast(V0_11_0_0) {
  125. request.Version = 1
  126. }
  127. if ca.conf.Version.IsAtLeast(V1_0_0_0) {
  128. request.Version = 2
  129. }
  130. b, err := ca.Controller()
  131. if err != nil {
  132. return err
  133. }
  134. rsp, err := b.CreateTopics(request)
  135. if err != nil {
  136. return err
  137. }
  138. topicErr, ok := rsp.TopicErrors[topic]
  139. if !ok {
  140. return ErrIncompleteResponse
  141. }
  142. if topicErr.Err != ErrNoError {
  143. return topicErr
  144. }
  145. return nil
  146. }
  147. func (ca *clusterAdmin) DescribeTopics(topics []string) (metadata []*TopicMetadata, err error) {
  148. controller, err := ca.Controller()
  149. if err != nil {
  150. return nil, err
  151. }
  152. request := &MetadataRequest{
  153. Topics: topics,
  154. AllowAutoTopicCreation: false,
  155. }
  156. if ca.conf.Version.IsAtLeast(V1_0_0_0) {
  157. request.Version = 5
  158. } else if ca.conf.Version.IsAtLeast(V0_11_0_0) {
  159. request.Version = 4
  160. }
  161. response, err := controller.GetMetadata(request)
  162. if err != nil {
  163. return nil, err
  164. }
  165. return response.Topics, nil
  166. }
  167. func (ca *clusterAdmin) DescribeCluster() (brokers []*Broker, controllerID int32, err error) {
  168. controller, err := ca.Controller()
  169. if err != nil {
  170. return nil, int32(0), err
  171. }
  172. request := &MetadataRequest{
  173. Topics: []string{},
  174. }
  175. response, err := controller.GetMetadata(request)
  176. if err != nil {
  177. return nil, int32(0), err
  178. }
  179. return response.Brokers, response.ControllerID, nil
  180. }
  181. func (ca *clusterAdmin) findAnyBroker() (*Broker, error) {
  182. brokers := ca.client.Brokers()
  183. if len(brokers) > 0 {
  184. index := rand.Intn(len(brokers))
  185. return brokers[index], nil
  186. }
  187. return nil, errors.New("no available broker")
  188. }
  189. func (ca *clusterAdmin) ListTopics() (map[string]TopicDetail, error) {
  190. // In order to build TopicDetails we need to first get the list of all
  191. // topics using a MetadataRequest and then get their configs using a
  192. // DescribeConfigsRequest request. To avoid sending many requests to the
  193. // broker, we use a single DescribeConfigsRequest.
  194. // Send the all-topic MetadataRequest
  195. b, err := ca.findAnyBroker()
  196. if err != nil {
  197. return nil, err
  198. }
  199. _ = b.Open(ca.client.Config())
  200. metadataReq := &MetadataRequest{}
  201. metadataResp, err := b.GetMetadata(metadataReq)
  202. if err != nil {
  203. return nil, err
  204. }
  205. topicsDetailsMap := make(map[string]TopicDetail)
  206. var describeConfigsResources []*ConfigResource
  207. for _, topic := range metadataResp.Topics {
  208. topicDetails := TopicDetail{
  209. NumPartitions: int32(len(topic.Partitions)),
  210. }
  211. if len(topic.Partitions) > 0 {
  212. topicDetails.ReplicaAssignment = map[int32][]int32{}
  213. for _, partition := range topic.Partitions {
  214. topicDetails.ReplicaAssignment[partition.ID] = partition.Replicas
  215. }
  216. topicDetails.ReplicationFactor = int16(len(topic.Partitions[0].Replicas))
  217. }
  218. topicsDetailsMap[topic.Name] = topicDetails
  219. // we populate the resources we want to describe from the MetadataResponse
  220. topicResource := ConfigResource{
  221. Type: TopicResource,
  222. Name: topic.Name,
  223. }
  224. describeConfigsResources = append(describeConfigsResources, &topicResource)
  225. }
  226. // Send the DescribeConfigsRequest
  227. describeConfigsReq := &DescribeConfigsRequest{
  228. Resources: describeConfigsResources,
  229. }
  230. describeConfigsResp, err := b.DescribeConfigs(describeConfigsReq)
  231. if err != nil {
  232. return nil, err
  233. }
  234. for _, resource := range describeConfigsResp.Resources {
  235. topicDetails := topicsDetailsMap[resource.Name]
  236. topicDetails.ConfigEntries = make(map[string]*string)
  237. for _, entry := range resource.Configs {
  238. // only include non-default non-sensitive config
  239. // (don't actually think topic config will ever be sensitive)
  240. if entry.Default || entry.Sensitive {
  241. continue
  242. }
  243. topicDetails.ConfigEntries[entry.Name] = &entry.Value
  244. }
  245. topicsDetailsMap[resource.Name] = topicDetails
  246. }
  247. return topicsDetailsMap, nil
  248. }
  249. func (ca *clusterAdmin) DeleteTopic(topic string) error {
  250. if topic == "" {
  251. return ErrInvalidTopic
  252. }
  253. request := &DeleteTopicsRequest{
  254. Topics: []string{topic},
  255. Timeout: ca.conf.Admin.Timeout,
  256. }
  257. if ca.conf.Version.IsAtLeast(V0_11_0_0) {
  258. request.Version = 1
  259. }
  260. b, err := ca.Controller()
  261. if err != nil {
  262. return err
  263. }
  264. rsp, err := b.DeleteTopics(request)
  265. if err != nil {
  266. return err
  267. }
  268. topicErr, ok := rsp.TopicErrorCodes[topic]
  269. if !ok {
  270. return ErrIncompleteResponse
  271. }
  272. if topicErr != ErrNoError {
  273. return topicErr
  274. }
  275. return nil
  276. }
  277. func (ca *clusterAdmin) CreatePartitions(topic string, count int32, assignment [][]int32, validateOnly bool) error {
  278. if topic == "" {
  279. return ErrInvalidTopic
  280. }
  281. topicPartitions := make(map[string]*TopicPartition)
  282. topicPartitions[topic] = &TopicPartition{Count: count, Assignment: assignment}
  283. request := &CreatePartitionsRequest{
  284. TopicPartitions: topicPartitions,
  285. Timeout: ca.conf.Admin.Timeout,
  286. }
  287. b, err := ca.Controller()
  288. if err != nil {
  289. return err
  290. }
  291. rsp, err := b.CreatePartitions(request)
  292. if err != nil {
  293. return err
  294. }
  295. topicErr, ok := rsp.TopicPartitionErrors[topic]
  296. if !ok {
  297. return ErrIncompleteResponse
  298. }
  299. if topicErr.Err != ErrNoError {
  300. return topicErr
  301. }
  302. return nil
  303. }
  304. func (ca *clusterAdmin) DeleteRecords(topic string, partitionOffsets map[int32]int64) error {
  305. if topic == "" {
  306. return ErrInvalidTopic
  307. }
  308. partitionPerBroker := make(map[*Broker][]int32)
  309. for partition := range partitionOffsets {
  310. broker, err := ca.client.Leader(topic, partition)
  311. if err != nil {
  312. return err
  313. }
  314. if _, ok := partitionPerBroker[broker]; ok {
  315. partitionPerBroker[broker] = append(partitionPerBroker[broker], partition)
  316. } else {
  317. partitionPerBroker[broker] = []int32{partition}
  318. }
  319. }
  320. errs := make([]error, 0)
  321. for broker, partitions := range partitionPerBroker {
  322. topics := make(map[string]*DeleteRecordsRequestTopic)
  323. recordsToDelete := make(map[int32]int64)
  324. for _, p := range partitions {
  325. recordsToDelete[p] = partitionOffsets[p]
  326. }
  327. topics[topic] = &DeleteRecordsRequestTopic{PartitionOffsets: recordsToDelete}
  328. request := &DeleteRecordsRequest{
  329. Topics: topics,
  330. Timeout: ca.conf.Admin.Timeout,
  331. }
  332. rsp, err := broker.DeleteRecords(request)
  333. if err != nil {
  334. errs = append(errs, err)
  335. } else {
  336. deleteRecordsResponseTopic, ok := rsp.Topics[topic]
  337. if !ok {
  338. errs = append(errs, ErrIncompleteResponse)
  339. } else {
  340. for _, deleteRecordsResponsePartition := range deleteRecordsResponseTopic.Partitions {
  341. if deleteRecordsResponsePartition.Err != ErrNoError {
  342. errs = append(errs, errors.New(deleteRecordsResponsePartition.Err.Error()))
  343. }
  344. }
  345. }
  346. }
  347. }
  348. if len(errs) > 0 {
  349. return ErrDeleteRecords{MultiError{&errs}}
  350. }
  351. //todo since we are dealing with couple of partitions it would be good if we return slice of errors
  352. //for each partition instead of one error
  353. return nil
  354. }
  355. func (ca *clusterAdmin) DescribeConfig(resource ConfigResource) ([]ConfigEntry, error) {
  356. var entries []ConfigEntry
  357. var resources []*ConfigResource
  358. resources = append(resources, &resource)
  359. request := &DescribeConfigsRequest{
  360. Resources: resources,
  361. }
  362. b, err := ca.Controller()
  363. if err != nil {
  364. return nil, err
  365. }
  366. rsp, err := b.DescribeConfigs(request)
  367. if err != nil {
  368. return nil, err
  369. }
  370. for _, rspResource := range rsp.Resources {
  371. if rspResource.Name == resource.Name {
  372. if rspResource.ErrorMsg != "" {
  373. return nil, errors.New(rspResource.ErrorMsg)
  374. }
  375. for _, cfgEntry := range rspResource.Configs {
  376. entries = append(entries, *cfgEntry)
  377. }
  378. }
  379. }
  380. return entries, nil
  381. }
  382. func (ca *clusterAdmin) AlterConfig(resourceType ConfigResourceType, name string, entries map[string]*string, validateOnly bool) error {
  383. var resources []*AlterConfigsResource
  384. resources = append(resources, &AlterConfigsResource{
  385. Type: resourceType,
  386. Name: name,
  387. ConfigEntries: entries,
  388. })
  389. request := &AlterConfigsRequest{
  390. Resources: resources,
  391. ValidateOnly: validateOnly,
  392. }
  393. b, err := ca.Controller()
  394. if err != nil {
  395. return err
  396. }
  397. rsp, err := b.AlterConfigs(request)
  398. if err != nil {
  399. return err
  400. }
  401. for _, rspResource := range rsp.Resources {
  402. if rspResource.Name == name {
  403. if rspResource.ErrorMsg != "" {
  404. return errors.New(rspResource.ErrorMsg)
  405. }
  406. }
  407. }
  408. return nil
  409. }
  410. func (ca *clusterAdmin) CreateACL(resource Resource, acl Acl) error {
  411. var acls []*AclCreation
  412. acls = append(acls, &AclCreation{resource, acl})
  413. request := &CreateAclsRequest{AclCreations: acls}
  414. if ca.conf.Version.IsAtLeast(V2_0_0_0) {
  415. request.Version = 1
  416. }
  417. b, err := ca.Controller()
  418. if err != nil {
  419. return err
  420. }
  421. _, err = b.CreateAcls(request)
  422. return err
  423. }
  424. func (ca *clusterAdmin) ListAcls(filter AclFilter) ([]ResourceAcls, error) {
  425. request := &DescribeAclsRequest{AclFilter: filter}
  426. if ca.conf.Version.IsAtLeast(V2_0_0_0) {
  427. request.Version = 1
  428. }
  429. b, err := ca.Controller()
  430. if err != nil {
  431. return nil, err
  432. }
  433. rsp, err := b.DescribeAcls(request)
  434. if err != nil {
  435. return nil, err
  436. }
  437. var lAcls []ResourceAcls
  438. for _, rAcl := range rsp.ResourceAcls {
  439. lAcls = append(lAcls, *rAcl)
  440. }
  441. return lAcls, nil
  442. }
  443. func (ca *clusterAdmin) DeleteACL(filter AclFilter, validateOnly bool) ([]MatchingAcl, error) {
  444. var filters []*AclFilter
  445. filters = append(filters, &filter)
  446. request := &DeleteAclsRequest{Filters: filters}
  447. if ca.conf.Version.IsAtLeast(V2_0_0_0) {
  448. request.Version = 1
  449. }
  450. b, err := ca.Controller()
  451. if err != nil {
  452. return nil, err
  453. }
  454. rsp, err := b.DeleteAcls(request)
  455. if err != nil {
  456. return nil, err
  457. }
  458. var mAcls []MatchingAcl
  459. for _, fr := range rsp.FilterResponses {
  460. for _, mACL := range fr.MatchingAcls {
  461. mAcls = append(mAcls, *mACL)
  462. }
  463. }
  464. return mAcls, nil
  465. }
  466. func (ca *clusterAdmin) DescribeConsumerGroups(groups []string) (result []*GroupDescription, err error) {
  467. groupsPerBroker := make(map[*Broker][]string)
  468. for _, group := range groups {
  469. controller, err := ca.client.Coordinator(group)
  470. if err != nil {
  471. return nil, err
  472. }
  473. groupsPerBroker[controller] = append(groupsPerBroker[controller], group)
  474. }
  475. for broker, brokerGroups := range groupsPerBroker {
  476. response, err := broker.DescribeGroups(&DescribeGroupsRequest{
  477. Groups: brokerGroups,
  478. })
  479. if err != nil {
  480. return nil, err
  481. }
  482. result = append(result, response.Groups...)
  483. }
  484. return result, nil
  485. }
  486. func (ca *clusterAdmin) ListConsumerGroups() (allGroups map[string]string, err error) {
  487. allGroups = make(map[string]string)
  488. // Query brokers in parallel, since we have to query *all* brokers
  489. brokers := ca.client.Brokers()
  490. groupMaps := make(chan map[string]string, len(brokers))
  491. errors := make(chan error, len(brokers))
  492. wg := sync.WaitGroup{}
  493. for _, b := range brokers {
  494. wg.Add(1)
  495. go func(b *Broker, conf *Config) {
  496. defer wg.Done()
  497. _ = b.Open(conf) // Ensure that broker is opened
  498. response, err := b.ListGroups(&ListGroupsRequest{})
  499. if err != nil {
  500. errors <- err
  501. return
  502. }
  503. groups := make(map[string]string)
  504. for group, typ := range response.Groups {
  505. groups[group] = typ
  506. }
  507. groupMaps <- groups
  508. }(b, ca.conf)
  509. }
  510. wg.Wait()
  511. close(groupMaps)
  512. close(errors)
  513. for groupMap := range groupMaps {
  514. for group, protocolType := range groupMap {
  515. allGroups[group] = protocolType
  516. }
  517. }
  518. // Intentionally return only the first error for simplicity
  519. err = <-errors
  520. return
  521. }
  522. func (ca *clusterAdmin) ListConsumerGroupOffsets(group string, topicPartitions map[string][]int32) (*OffsetFetchResponse, error) {
  523. coordinator, err := ca.client.Coordinator(group)
  524. if err != nil {
  525. return nil, err
  526. }
  527. request := &OffsetFetchRequest{
  528. ConsumerGroup: group,
  529. partitions: topicPartitions,
  530. }
  531. if ca.conf.Version.IsAtLeast(V0_10_2_0) {
  532. request.Version = 2
  533. } else if ca.conf.Version.IsAtLeast(V0_8_2_2) {
  534. request.Version = 1
  535. }
  536. return coordinator.FetchOffset(request)
  537. }
  538. func (ca *clusterAdmin) DeleteConsumerGroup(group string) error {
  539. coordinator, err := ca.client.Coordinator(group)
  540. if err != nil {
  541. return err
  542. }
  543. request := &DeleteGroupsRequest{
  544. Groups: []string{group},
  545. }
  546. resp, err := coordinator.DeleteGroups(request)
  547. if err != nil {
  548. return err
  549. }
  550. groupErr, ok := resp.GroupErrorCodes[group]
  551. if !ok {
  552. return ErrIncompleteResponse
  553. }
  554. if groupErr != ErrNoError {
  555. return groupErr
  556. }
  557. return nil
  558. }