flags.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  1. // Copyright (c) 2016 Arista Networks, Inc.
  2. // Use of this source code is governed by the Apache License 2.0
  3. // that can be found in the COPYING file.
  4. package client
  5. import (
  6. "crypto/tls"
  7. "crypto/x509"
  8. "flag"
  9. "io/ioutil"
  10. "strings"
  11. "notabug.org/themusicgod1/glog"
  12. "google.golang.org/grpc"
  13. "google.golang.org/grpc/credentials"
  14. )
  15. // ParseFlags registers some additional common flags,
  16. // parses the flags, and returns the resulting gRPC options,
  17. // and other settings to connect to the gRPC interface.
  18. func ParseFlags() (username string, password string, subscriptions, addrs []string,
  19. opts []grpc.DialOption) {
  20. var (
  21. addrsFlag = flag.String("addrs", "localhost:6030",
  22. "Comma-separated list of addresses of OpenConfig gRPC servers")
  23. caFileFlag = flag.String("cafile", "",
  24. "Path to server TLS certificate file")
  25. certFileFlag = flag.String("certfile", "",
  26. "Path to client TLS certificate file")
  27. keyFileFlag = flag.String("keyfile", "",
  28. "Path to client TLS private key file")
  29. passwordFlag = flag.String("password", "",
  30. "Password to authenticate with")
  31. subscribeFlag = flag.String("subscribe", "",
  32. "Comma-separated list of paths to subscribe to upon connecting to the server")
  33. usernameFlag = flag.String("username", "",
  34. "Username to authenticate with")
  35. tlsFlag = flag.Bool("tls", false,
  36. "Enable TLS")
  37. )
  38. flag.Parse()
  39. if *tlsFlag || *caFileFlag != "" || *certFileFlag != "" {
  40. config := &tls.Config{}
  41. if *caFileFlag != "" {
  42. b, err := ioutil.ReadFile(*caFileFlag)
  43. if err != nil {
  44. glog.Fatal(err)
  45. }
  46. cp := x509.NewCertPool()
  47. if !cp.AppendCertsFromPEM(b) {
  48. glog.Fatalf("credentials: failed to append certificates")
  49. }
  50. config.RootCAs = cp
  51. } else {
  52. config.InsecureSkipVerify = true
  53. }
  54. if *certFileFlag != "" {
  55. if *keyFileFlag == "" {
  56. glog.Fatalf("Please provide both -certfile and -keyfile")
  57. }
  58. cert, err := tls.LoadX509KeyPair(*certFileFlag, *keyFileFlag)
  59. if err != nil {
  60. glog.Fatal(err)
  61. }
  62. config.Certificates = []tls.Certificate{cert}
  63. }
  64. opts = append(opts, grpc.WithTransportCredentials(credentials.NewTLS(config)))
  65. } else {
  66. opts = append(opts, grpc.WithInsecure())
  67. }
  68. addrs = strings.Split(*addrsFlag, ",")
  69. subscriptions = strings.Split(*subscribeFlag, ",")
  70. return *usernameFlag, *passwordFlag, subscriptions, addrs, opts
  71. }