admin.go 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648
  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. //make sure we can retrieve the controller
  89. _, err = client.Controller()
  90. if err != nil {
  91. return nil, err
  92. }
  93. ca := &clusterAdmin{
  94. client: client,
  95. conf: client.Config(),
  96. }
  97. return ca, nil
  98. }
  99. func (ca *clusterAdmin) Close() error {
  100. return ca.client.Close()
  101. }
  102. func (ca *clusterAdmin) Controller() (*Broker, error) {
  103. return ca.client.Controller()
  104. }
  105. func (ca *clusterAdmin) CreateTopic(topic string, detail *TopicDetail, validateOnly bool) error {
  106. if topic == "" {
  107. return ErrInvalidTopic
  108. }
  109. if detail == nil {
  110. return errors.New("you must specify topic details")
  111. }
  112. topicDetails := make(map[string]*TopicDetail)
  113. topicDetails[topic] = detail
  114. request := &CreateTopicsRequest{
  115. TopicDetails: topicDetails,
  116. ValidateOnly: validateOnly,
  117. Timeout: ca.conf.Admin.Timeout,
  118. }
  119. if ca.conf.Version.IsAtLeast(V0_11_0_0) {
  120. request.Version = 1
  121. }
  122. if ca.conf.Version.IsAtLeast(V1_0_0_0) {
  123. request.Version = 2
  124. }
  125. b, err := ca.Controller()
  126. if err != nil {
  127. return err
  128. }
  129. rsp, err := b.CreateTopics(request)
  130. if err != nil {
  131. return err
  132. }
  133. topicErr, ok := rsp.TopicErrors[topic]
  134. if !ok {
  135. return ErrIncompleteResponse
  136. }
  137. if topicErr.Err != ErrNoError {
  138. return topicErr
  139. }
  140. return nil
  141. }
  142. func (ca *clusterAdmin) DescribeTopics(topics []string) (metadata []*TopicMetadata, err error) {
  143. controller, err := ca.Controller()
  144. if err != nil {
  145. return nil, err
  146. }
  147. request := &MetadataRequest{
  148. Topics: topics,
  149. AllowAutoTopicCreation: false,
  150. }
  151. if ca.conf.Version.IsAtLeast(V1_0_0_0) {
  152. request.Version = 5
  153. } else if ca.conf.Version.IsAtLeast(V0_11_0_0) {
  154. request.Version = 4
  155. }
  156. response, err := controller.GetMetadata(request)
  157. if err != nil {
  158. return nil, err
  159. }
  160. return response.Topics, nil
  161. }
  162. func (ca *clusterAdmin) DescribeCluster() (brokers []*Broker, controllerID int32, err error) {
  163. controller, err := ca.Controller()
  164. if err != nil {
  165. return nil, int32(0), err
  166. }
  167. request := &MetadataRequest{
  168. Topics: []string{},
  169. }
  170. response, err := controller.GetMetadata(request)
  171. if err != nil {
  172. return nil, int32(0), err
  173. }
  174. return response.Brokers, response.ControllerID, nil
  175. }
  176. func (ca *clusterAdmin) findAnyBroker() (*Broker, error) {
  177. brokers := ca.client.Brokers()
  178. if len(brokers) > 0 {
  179. index := rand.Intn(len(brokers))
  180. return brokers[index], nil
  181. }
  182. return nil, errors.New("no available broker")
  183. }
  184. func (ca *clusterAdmin) ListTopics() (map[string]TopicDetail, error) {
  185. // In order to build TopicDetails we need to first get the list of all
  186. // topics using a MetadataRequest and then get their configs using a
  187. // DescribeConfigsRequest request. To avoid sending many requests to the
  188. // broker, we use a single DescribeConfigsRequest.
  189. // Send the all-topic MetadataRequest
  190. b, err := ca.findAnyBroker()
  191. if err != nil {
  192. return nil, err
  193. }
  194. _ = b.Open(ca.client.Config())
  195. metadataReq := &MetadataRequest{}
  196. metadataResp, err := b.GetMetadata(metadataReq)
  197. if err != nil {
  198. return nil, err
  199. }
  200. topicsDetailsMap := make(map[string]TopicDetail)
  201. var describeConfigsResources []*ConfigResource
  202. for _, topic := range metadataResp.Topics {
  203. topicDetails := TopicDetail{
  204. NumPartitions: int32(len(topic.Partitions)),
  205. }
  206. if len(topic.Partitions) > 0 {
  207. topicDetails.ReplicaAssignment = map[int32][]int32{}
  208. for _, partition := range topic.Partitions {
  209. topicDetails.ReplicaAssignment[partition.ID] = partition.Replicas
  210. }
  211. topicDetails.ReplicationFactor = int16(len(topic.Partitions[0].Replicas))
  212. }
  213. topicsDetailsMap[topic.Name] = topicDetails
  214. // we populate the resources we want to describe from the MetadataResponse
  215. topicResource := ConfigResource{
  216. Type: TopicResource,
  217. Name: topic.Name,
  218. }
  219. describeConfigsResources = append(describeConfigsResources, &topicResource)
  220. }
  221. // Send the DescribeConfigsRequest
  222. describeConfigsReq := &DescribeConfigsRequest{
  223. Resources: describeConfigsResources,
  224. }
  225. describeConfigsResp, err := b.DescribeConfigs(describeConfigsReq)
  226. if err != nil {
  227. return nil, err
  228. }
  229. for _, resource := range describeConfigsResp.Resources {
  230. topicDetails := topicsDetailsMap[resource.Name]
  231. topicDetails.ConfigEntries = make(map[string]*string)
  232. for _, entry := range resource.Configs {
  233. // only include non-default non-sensitive config
  234. // (don't actually think topic config will ever be sensitive)
  235. if entry.Default || entry.Sensitive {
  236. continue
  237. }
  238. topicDetails.ConfigEntries[entry.Name] = &entry.Value
  239. }
  240. topicsDetailsMap[resource.Name] = topicDetails
  241. }
  242. return topicsDetailsMap, nil
  243. }
  244. func (ca *clusterAdmin) DeleteTopic(topic string) error {
  245. if topic == "" {
  246. return ErrInvalidTopic
  247. }
  248. request := &DeleteTopicsRequest{
  249. Topics: []string{topic},
  250. Timeout: ca.conf.Admin.Timeout,
  251. }
  252. if ca.conf.Version.IsAtLeast(V0_11_0_0) {
  253. request.Version = 1
  254. }
  255. b, err := ca.Controller()
  256. if err != nil {
  257. return err
  258. }
  259. rsp, err := b.DeleteTopics(request)
  260. if err != nil {
  261. return err
  262. }
  263. topicErr, ok := rsp.TopicErrorCodes[topic]
  264. if !ok {
  265. return ErrIncompleteResponse
  266. }
  267. if topicErr != ErrNoError {
  268. return topicErr
  269. }
  270. return nil
  271. }
  272. func (ca *clusterAdmin) CreatePartitions(topic string, count int32, assignment [][]int32, validateOnly bool) error {
  273. if topic == "" {
  274. return ErrInvalidTopic
  275. }
  276. topicPartitions := make(map[string]*TopicPartition)
  277. topicPartitions[topic] = &TopicPartition{Count: count, Assignment: assignment}
  278. request := &CreatePartitionsRequest{
  279. TopicPartitions: topicPartitions,
  280. Timeout: ca.conf.Admin.Timeout,
  281. }
  282. b, err := ca.Controller()
  283. if err != nil {
  284. return err
  285. }
  286. rsp, err := b.CreatePartitions(request)
  287. if err != nil {
  288. return err
  289. }
  290. topicErr, ok := rsp.TopicPartitionErrors[topic]
  291. if !ok {
  292. return ErrIncompleteResponse
  293. }
  294. if topicErr.Err != ErrNoError {
  295. return topicErr
  296. }
  297. return nil
  298. }
  299. func (ca *clusterAdmin) DeleteRecords(topic string, partitionOffsets map[int32]int64) error {
  300. if topic == "" {
  301. return ErrInvalidTopic
  302. }
  303. topics := make(map[string]*DeleteRecordsRequestTopic)
  304. topics[topic] = &DeleteRecordsRequestTopic{PartitionOffsets: partitionOffsets}
  305. request := &DeleteRecordsRequest{
  306. Topics: topics,
  307. Timeout: ca.conf.Admin.Timeout,
  308. }
  309. b, err := ca.Controller()
  310. if err != nil {
  311. return err
  312. }
  313. rsp, err := b.DeleteRecords(request)
  314. if err != nil {
  315. return err
  316. }
  317. _, ok := rsp.Topics[topic]
  318. if !ok {
  319. return ErrIncompleteResponse
  320. }
  321. //todo since we are dealing with couple of partitions it would be good if we return slice of errors
  322. //for each partition instead of one error
  323. return nil
  324. }
  325. func (ca *clusterAdmin) DescribeConfig(resource ConfigResource) ([]ConfigEntry, error) {
  326. var entries []ConfigEntry
  327. var resources []*ConfigResource
  328. resources = append(resources, &resource)
  329. request := &DescribeConfigsRequest{
  330. Resources: resources,
  331. }
  332. b, err := ca.Controller()
  333. if err != nil {
  334. return nil, err
  335. }
  336. rsp, err := b.DescribeConfigs(request)
  337. if err != nil {
  338. return nil, err
  339. }
  340. for _, rspResource := range rsp.Resources {
  341. if rspResource.Name == resource.Name {
  342. if rspResource.ErrorMsg != "" {
  343. return nil, errors.New(rspResource.ErrorMsg)
  344. }
  345. for _, cfgEntry := range rspResource.Configs {
  346. entries = append(entries, *cfgEntry)
  347. }
  348. }
  349. }
  350. return entries, nil
  351. }
  352. func (ca *clusterAdmin) AlterConfig(resourceType ConfigResourceType, name string, entries map[string]*string, validateOnly bool) error {
  353. var resources []*AlterConfigsResource
  354. resources = append(resources, &AlterConfigsResource{
  355. Type: resourceType,
  356. Name: name,
  357. ConfigEntries: entries,
  358. })
  359. request := &AlterConfigsRequest{
  360. Resources: resources,
  361. ValidateOnly: validateOnly,
  362. }
  363. b, err := ca.Controller()
  364. if err != nil {
  365. return err
  366. }
  367. rsp, err := b.AlterConfigs(request)
  368. if err != nil {
  369. return err
  370. }
  371. for _, rspResource := range rsp.Resources {
  372. if rspResource.Name == name {
  373. if rspResource.ErrorMsg != "" {
  374. return errors.New(rspResource.ErrorMsg)
  375. }
  376. }
  377. }
  378. return nil
  379. }
  380. func (ca *clusterAdmin) CreateACL(resource Resource, acl Acl) error {
  381. var acls []*AclCreation
  382. acls = append(acls, &AclCreation{resource, acl})
  383. request := &CreateAclsRequest{AclCreations: acls}
  384. b, err := ca.Controller()
  385. if err != nil {
  386. return err
  387. }
  388. _, err = b.CreateAcls(request)
  389. return err
  390. }
  391. func (ca *clusterAdmin) ListAcls(filter AclFilter) ([]ResourceAcls, error) {
  392. request := &DescribeAclsRequest{AclFilter: filter}
  393. b, err := ca.Controller()
  394. if err != nil {
  395. return nil, err
  396. }
  397. rsp, err := b.DescribeAcls(request)
  398. if err != nil {
  399. return nil, err
  400. }
  401. var lAcls []ResourceAcls
  402. for _, rAcl := range rsp.ResourceAcls {
  403. lAcls = append(lAcls, *rAcl)
  404. }
  405. return lAcls, nil
  406. }
  407. func (ca *clusterAdmin) DeleteACL(filter AclFilter, validateOnly bool) ([]MatchingAcl, error) {
  408. var filters []*AclFilter
  409. filters = append(filters, &filter)
  410. request := &DeleteAclsRequest{Filters: filters}
  411. b, err := ca.Controller()
  412. if err != nil {
  413. return nil, err
  414. }
  415. rsp, err := b.DeleteAcls(request)
  416. if err != nil {
  417. return nil, err
  418. }
  419. var mAcls []MatchingAcl
  420. for _, fr := range rsp.FilterResponses {
  421. for _, mACL := range fr.MatchingAcls {
  422. mAcls = append(mAcls, *mACL)
  423. }
  424. }
  425. return mAcls, nil
  426. }
  427. func (ca *clusterAdmin) DescribeConsumerGroups(groups []string) (result []*GroupDescription, err error) {
  428. groupsPerBroker := make(map[*Broker][]string)
  429. for _, group := range groups {
  430. controller, err := ca.client.Coordinator(group)
  431. if err != nil {
  432. return nil, err
  433. }
  434. groupsPerBroker[controller] = append(groupsPerBroker[controller], group)
  435. }
  436. for broker, brokerGroups := range groupsPerBroker {
  437. response, err := broker.DescribeGroups(&DescribeGroupsRequest{
  438. Groups: brokerGroups,
  439. })
  440. if err != nil {
  441. return nil, err
  442. }
  443. result = append(result, response.Groups...)
  444. }
  445. return result, nil
  446. }
  447. func (ca *clusterAdmin) ListConsumerGroups() (allGroups map[string]string, err error) {
  448. allGroups = make(map[string]string)
  449. // Query brokers in parallel, since we have to query *all* brokers
  450. brokers := ca.client.Brokers()
  451. groupMaps := make(chan map[string]string, len(brokers))
  452. errors := make(chan error, len(brokers))
  453. wg := sync.WaitGroup{}
  454. for _, b := range brokers {
  455. wg.Add(1)
  456. go func(b *Broker, conf *Config) {
  457. defer wg.Done()
  458. _ = b.Open(conf) // Ensure that broker is opened
  459. response, err := b.ListGroups(&ListGroupsRequest{})
  460. if err != nil {
  461. errors <- err
  462. return
  463. }
  464. groups := make(map[string]string)
  465. for group, typ := range response.Groups {
  466. groups[group] = typ
  467. }
  468. groupMaps <- groups
  469. }(b, ca.conf)
  470. }
  471. wg.Wait()
  472. close(groupMaps)
  473. close(errors)
  474. for groupMap := range groupMaps {
  475. for group, protocolType := range groupMap {
  476. allGroups[group] = protocolType
  477. }
  478. }
  479. // Intentionally return only the first error for simplicity
  480. err = <-errors
  481. return
  482. }
  483. func (ca *clusterAdmin) ListConsumerGroupOffsets(group string, topicPartitions map[string][]int32) (*OffsetFetchResponse, error) {
  484. coordinator, err := ca.client.Coordinator(group)
  485. if err != nil {
  486. return nil, err
  487. }
  488. request := &OffsetFetchRequest{
  489. ConsumerGroup: group,
  490. partitions: topicPartitions,
  491. }
  492. if ca.conf.Version.IsAtLeast(V0_10_2_0) {
  493. request.Version = 2
  494. } else if ca.conf.Version.IsAtLeast(V0_8_2_2) {
  495. request.Version = 1
  496. }
  497. return coordinator.FetchOffset(request)
  498. }
  499. func (ca *clusterAdmin) DeleteConsumerGroup(group string) error {
  500. coordinator, err := ca.client.Coordinator(group)
  501. if err != nil {
  502. return err
  503. }
  504. request := &DeleteGroupsRequest{
  505. Groups: []string{group},
  506. }
  507. resp, err := coordinator.DeleteGroups(request)
  508. if err != nil {
  509. return err
  510. }
  511. groupErr, ok := resp.GroupErrorCodes[group]
  512. if !ok {
  513. return ErrIncompleteResponse
  514. }
  515. if groupErr != ErrNoError {
  516. return groupErr
  517. }
  518. return nil
  519. }