admin.go 16 KB

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