admin.go 16 KB

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