main.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437
  1. // Copyright 2014 Google Inc. All Rights Reserved.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // Package main contains a simple command line tool for Cloud Pub/Sub
  15. // Cloud Pub/Sub docs: https://cloud.google.com/pubsub/docs
  16. package main
  17. import (
  18. "errors"
  19. "flag"
  20. "fmt"
  21. "io/ioutil"
  22. "log"
  23. "net/http"
  24. "os"
  25. "strconv"
  26. "time"
  27. "golang.org/x/net/context"
  28. "golang.org/x/oauth2"
  29. "golang.org/x/oauth2/google"
  30. "google.golang.org/cloud"
  31. "google.golang.org/cloud/compute/metadata"
  32. "google.golang.org/cloud/pubsub"
  33. )
  34. var (
  35. jsonFile = flag.String("j", "", "A path to your JSON key file for your service account downloaded from Google Developer Console, not needed if you run it on Compute Engine instances.")
  36. projID = flag.String("p", "", "The ID of your Google Cloud project.")
  37. reportMPS = flag.Bool("report", false, "Reports the incoming/outgoing message rate in msg/sec if set.")
  38. size = flag.Int("size", 10, "Batch size for pull_messages and publish_messages subcommands.")
  39. )
  40. const (
  41. usage = `Available arguments are:
  42. create_topic <name>
  43. topic_exists <name>
  44. delete_topic <name>
  45. list_topic_subscriptions <name>
  46. list_topics
  47. create_subscription <name> <linked_topic>
  48. show_subscription <name>
  49. subscription_exists <name>
  50. delete_subscription <name>
  51. list_subscriptions
  52. publish <topic> <message>
  53. pull_messages <subscription> <numworkers>
  54. publish_messages <topic> <numworkers>
  55. `
  56. tick = 1 * time.Second
  57. )
  58. func usageAndExit(msg string) {
  59. fmt.Fprintln(os.Stderr, msg)
  60. fmt.Println("Flags:")
  61. flag.PrintDefaults()
  62. fmt.Fprint(os.Stderr, usage)
  63. os.Exit(2)
  64. }
  65. // Check the length of the arguments.
  66. func checkArgs(argv []string, min int) {
  67. if len(argv) < min {
  68. usageAndExit("Missing arguments")
  69. }
  70. }
  71. // newClient creates http.Client with a jwt service account when
  72. // jsonFile flag is specified, otherwise by obtaining the GCE service
  73. // account's access token.
  74. func newClient(jsonFile string) (*http.Client, error) {
  75. if jsonFile != "" {
  76. jsonKey, err := ioutil.ReadFile(jsonFile)
  77. if err != nil {
  78. return nil, err
  79. }
  80. conf, err := google.JWTConfigFromJSON(jsonKey, pubsub.ScopePubSub)
  81. if err != nil {
  82. return nil, err
  83. }
  84. return conf.Client(oauth2.NoContext), nil
  85. }
  86. if metadata.OnGCE() {
  87. c := &http.Client{
  88. Transport: &oauth2.Transport{
  89. Source: google.ComputeTokenSource(""),
  90. },
  91. }
  92. if *projID == "" {
  93. projectID, err := metadata.ProjectID()
  94. if err != nil {
  95. return nil, fmt.Errorf("ProjectID failed, %v", err)
  96. }
  97. *projID = projectID
  98. }
  99. return c, nil
  100. }
  101. return nil, errors.New("Could not create an authenticated client.")
  102. }
  103. func createTopic(client *pubsub.Client, argv []string) {
  104. checkArgs(argv, 2)
  105. topic := argv[1]
  106. _, err := client.NewTopic(context.Background(), topic)
  107. if err != nil {
  108. log.Fatalf("Creating topic failed: %v", err)
  109. }
  110. fmt.Printf("Topic %s was created.\n", topic)
  111. }
  112. func listTopics(client *pubsub.Client, argv []string) {
  113. checkArgs(argv, 1)
  114. topics, err := client.Topics(context.Background())
  115. if err != nil {
  116. log.Fatalf("Listing topics failed: %v", err)
  117. }
  118. for _, t := range topics {
  119. fmt.Println(t.Name())
  120. }
  121. }
  122. func listTopicSubscriptions(client *pubsub.Client, argv []string) {
  123. checkArgs(argv, 2)
  124. topic := argv[1]
  125. subs, err := client.Topic(topic).Subscriptions(context.Background())
  126. if err != nil {
  127. log.Fatalf("Listing subscriptions failed: %v", err)
  128. }
  129. for _, s := range subs {
  130. fmt.Println(s.Name())
  131. }
  132. }
  133. func checkTopicExists(client *pubsub.Client, argv []string) {
  134. checkArgs(argv, 1)
  135. topic := argv[1]
  136. exists, err := client.Topic(topic).Exists(context.Background())
  137. if err != nil {
  138. log.Fatalf("Checking topic exists failed: %v", err)
  139. }
  140. fmt.Println(exists)
  141. }
  142. func deleteTopic(client *pubsub.Client, argv []string) {
  143. checkArgs(argv, 2)
  144. topic := argv[1]
  145. err := client.Topic(topic).Delete(context.Background())
  146. if err != nil {
  147. log.Fatalf("Deleting topic failed: %v", err)
  148. }
  149. fmt.Printf("Topic %s was deleted.\n", topic)
  150. }
  151. func createSubscription(client *pubsub.Client, argv []string) {
  152. checkArgs(argv, 3)
  153. sub := argv[1]
  154. topic := argv[2]
  155. _, err := client.Topic(topic).Subscribe(context.Background(), sub, 0, nil)
  156. if err != nil {
  157. log.Fatalf("Creating Subscription failed: %v", err)
  158. }
  159. fmt.Printf("Subscription %s was created.\n", sub)
  160. }
  161. func showSubscription(client *pubsub.Client, argv []string) {
  162. checkArgs(argv, 2)
  163. sub := argv[1]
  164. conf, err := client.Subscription(sub).Config(context.Background())
  165. if err != nil {
  166. log.Fatalf("Getting Subscription failed: %v", err)
  167. }
  168. fmt.Printf("%+v\n", conf)
  169. exists, err := conf.Topic.Exists(context.Background())
  170. if err != nil {
  171. log.Fatalf("Checking whether topic exists: %v", err)
  172. }
  173. if !exists {
  174. fmt.Println("The topic for this subscription has been deleted.\n")
  175. }
  176. }
  177. func checkSubscriptionExists(client *pubsub.Client, argv []string) {
  178. checkArgs(argv, 1)
  179. sub := argv[1]
  180. exists, err := client.Subscription(sub).Exists(context.Background())
  181. if err != nil {
  182. log.Fatalf("Checking subscription exists failed: %v", err)
  183. }
  184. fmt.Println(exists)
  185. }
  186. func deleteSubscription(client *pubsub.Client, argv []string) {
  187. checkArgs(argv, 2)
  188. sub := argv[1]
  189. err := client.Subscription(sub).Delete(context.Background())
  190. if err != nil {
  191. log.Fatalf("Deleting Subscription failed: %v", err)
  192. }
  193. fmt.Printf("Subscription %s was deleted.\n", sub)
  194. }
  195. func listSubscriptions(client *pubsub.Client, argv []string) {
  196. checkArgs(argv, 1)
  197. subs, err := client.Subscriptions(context.Background())
  198. if err != nil {
  199. log.Fatalf("Listing subscriptions failed: %v", err)
  200. }
  201. for _, s := range subs {
  202. fmt.Println(s.Name())
  203. }
  204. }
  205. func publish(client *pubsub.Client, argv []string) {
  206. checkArgs(argv, 3)
  207. topic := argv[1]
  208. message := argv[2]
  209. msgIDs, err := client.Topic(topic).Publish(context.Background(), &pubsub.Message{
  210. Data: []byte(message),
  211. })
  212. if err != nil {
  213. log.Fatalf("Publish failed, %v", err)
  214. }
  215. fmt.Printf("Message '%s' published to topic %s and the message id is %s\n", message, topic, msgIDs[0])
  216. }
  217. type reporter struct {
  218. reportTitle string
  219. lastC uint64
  220. c uint64
  221. result <-chan int
  222. }
  223. func (r *reporter) report() {
  224. ticker := time.NewTicker(tick)
  225. defer func() {
  226. ticker.Stop()
  227. }()
  228. for {
  229. select {
  230. case <-ticker.C:
  231. n := r.c - r.lastC
  232. r.lastC = r.c
  233. mps := n / uint64(tick/time.Second)
  234. log.Printf("%s ~%d msgs/s, total: %d", r.reportTitle, mps, r.c)
  235. case n := <-r.result:
  236. r.c += uint64(n)
  237. }
  238. }
  239. }
  240. func publishLoop(client *pubsub.Client, topic string, workerid int, result chan<- int) {
  241. var r uint64
  242. for {
  243. msgs := make([]*pubsub.Message, *size)
  244. for i := 0; i < *size; i++ {
  245. msgs[i] = &pubsub.Message{
  246. Data: []byte(fmt.Sprintf("Worker: %d, Round: %d, Message: %d", workerid, r, i)),
  247. }
  248. }
  249. _, err := client.Topic(topic).Publish(context.Background(), msgs...)
  250. if err != nil {
  251. log.Printf("Publish failed, %v\n", err)
  252. return
  253. }
  254. r++
  255. if *reportMPS {
  256. result <- *size
  257. }
  258. }
  259. }
  260. func publishMessages(client *pubsub.Client, argv []string) {
  261. checkArgs(argv, 3)
  262. topic := argv[1]
  263. workers, err := strconv.Atoi(argv[2])
  264. if err != nil {
  265. log.Fatalf("Atoi failed, %v", err)
  266. }
  267. result := make(chan int, 1024)
  268. for i := 0; i < int(workers); i++ {
  269. go publishLoop(client, topic, i, result)
  270. }
  271. if *reportMPS {
  272. r := reporter{reportTitle: "Sent", result: result}
  273. r.report()
  274. } else {
  275. select {}
  276. }
  277. }
  278. // NOTE: the following operations (which take a Context rather than a Client)
  279. // use the old API which is being progressively deprecated.
  280. func ack(ctx context.Context, sub string, ackID ...string) {
  281. err := pubsub.Ack(ctx, sub, ackID...)
  282. if err != nil {
  283. log.Printf("Ack failed, %v\n", err)
  284. }
  285. }
  286. func pullLoop(ctx context.Context, sub string, result chan<- int) {
  287. for {
  288. msgs, err := pubsub.PullWait(ctx, sub, *size)
  289. if err != nil {
  290. log.Printf("PullWait failed, %v\n", err)
  291. time.Sleep(5 * time.Second)
  292. continue
  293. }
  294. if len(msgs) == 0 {
  295. log.Println("Received no messages")
  296. continue
  297. }
  298. if *reportMPS {
  299. result <- len(msgs)
  300. }
  301. ackIDs := make([]string, len(msgs))
  302. for i, msg := range msgs {
  303. if !*reportMPS {
  304. fmt.Printf("Got a message: %s\n", msg.Data)
  305. }
  306. ackIDs[i] = msg.AckID
  307. }
  308. go ack(ctx, sub, ackIDs...)
  309. }
  310. }
  311. func pullMessages(ctx context.Context, argv []string) {
  312. checkArgs(argv, 3)
  313. sub := argv[1]
  314. workers, err := strconv.Atoi(argv[2])
  315. if err != nil {
  316. log.Fatalf("Atoi failed, %v", err)
  317. }
  318. result := make(chan int, 1024)
  319. for i := 0; i < int(workers); i++ {
  320. go pullLoop(ctx, sub, result)
  321. }
  322. if *reportMPS {
  323. r := reporter{reportTitle: "Received", result: result}
  324. r.report()
  325. } else {
  326. select {}
  327. }
  328. }
  329. // This example demonstrates calling the Cloud Pub/Sub API.
  330. //
  331. // Before running this example, be sure to enable Cloud Pub/Sub
  332. // service on your project in Developer Console at:
  333. // https://console.developers.google.com/
  334. //
  335. // Unless you run this sample on Compute Engine instance, please
  336. // create a new service account and download a JSON key file for it at
  337. // the developer console: https://console.developers.google.com/
  338. //
  339. // It has the following subcommands:
  340. //
  341. // create_topic <name>
  342. // delete_topic <name>
  343. // create_subscription <name> <linked_topic>
  344. // delete_subscription <name>
  345. // publish <topic> <message>
  346. // pull_messages <subscription> <numworkers>
  347. // publish_messages <topic> <numworkers>
  348. //
  349. // You can choose any names for topic and subscription as long as they
  350. // follow the naming rule described at:
  351. // https://cloud.google.com/pubsub/overview#names
  352. //
  353. // You can create/delete topics/subscriptions by self-explanatory
  354. // subcommands.
  355. //
  356. // The "publish" subcommand is for publishing a single message to a
  357. // specified Cloud Pub/Sub topic.
  358. //
  359. // The "pull_messages" subcommand is for continuously pulling messages
  360. // from a specified Cloud Pub/Sub subscription with specified number
  361. // of workers.
  362. //
  363. // The "publish_messages" subcommand is for continuously publishing
  364. // messages to a specified Cloud Pub/Sub topic with specified number
  365. // of workers.
  366. func main() {
  367. flag.Parse()
  368. argv := flag.Args()
  369. checkArgs(argv, 1)
  370. if *projID == "" {
  371. usageAndExit("Please specify Project ID.")
  372. }
  373. oldStyle := map[string]func(ctx context.Context, argv []string){
  374. "pull_messages": pullMessages,
  375. }
  376. newStyle := map[string]func(client *pubsub.Client, argv []string){
  377. "create_topic": createTopic,
  378. "delete_topic": deleteTopic,
  379. "list_topics": listTopics,
  380. "list_topic_subscriptions": listTopicSubscriptions,
  381. "topic_exists": checkTopicExists,
  382. "create_subscription": createSubscription,
  383. "show_subscription": showSubscription,
  384. "delete_subscription": deleteSubscription,
  385. "subscription_exists": checkSubscriptionExists,
  386. "list_subscriptions": listSubscriptions,
  387. "publish": publish,
  388. "publish_messages": publishMessages,
  389. }
  390. subcommand := argv[0]
  391. if f, ok := oldStyle[subcommand]; ok {
  392. httpClient, err := newClient(*jsonFile)
  393. if err != nil {
  394. log.Fatalf("clientAndId failed, %v", err)
  395. }
  396. ctx := cloud.NewContext(*projID, httpClient)
  397. f(ctx, argv)
  398. } else if f, ok := newStyle[subcommand]; ok {
  399. client, err := pubsub.NewClient(context.Background(), *projID)
  400. if err != nil {
  401. log.Fatalf("creating pubsub client: %v", err)
  402. }
  403. f(client, argv)
  404. } else {
  405. usageAndExit(fmt.Sprintf("Function not found for %s", subcommand))
  406. }
  407. }