1
0

utils.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "net"
  6. "net/url"
  7. "os"
  8. "github.com/sirupsen/logrus"
  9. "github.com/cad/ovpm/errors"
  10. "github.com/urfave/cli"
  11. "google.golang.org/grpc"
  12. )
  13. func emitToFile(filePath, content string, mode uint) error {
  14. file, err := os.Create(filePath)
  15. if err != nil {
  16. return fmt.Errorf("Cannot create file %s: %v", filePath, err)
  17. }
  18. if mode != 0 {
  19. file.Chmod(os.FileMode(mode))
  20. }
  21. defer file.Close()
  22. fmt.Fprintf(file, content)
  23. return nil
  24. }
  25. func getConn(port string) *grpc.ClientConn {
  26. if port == "" {
  27. port = "9090"
  28. }
  29. conn, err := grpc.Dial(fmt.Sprintf(":%s", port), grpc.WithInsecure())
  30. if err != nil {
  31. logrus.Fatalf("fail to dial: %v", err)
  32. }
  33. return conn
  34. }
  35. // grpcConnect receives a rpc server url and makes a connection to the
  36. // GRPC server.
  37. func grpcConnect(rpcServURL *url.URL) (*grpc.ClientConn, error) {
  38. // Ensure rpcServURL host part contains a localhost addr only.
  39. if !isLoopbackURL(rpcServURL) {
  40. return nil, errors.MustBeLoopbackURL(rpcServURL)
  41. }
  42. conn, err := grpc.Dial(rpcServURL.Host, grpc.WithInsecure())
  43. if err != nil {
  44. return nil, errors.UnknownSysError(err)
  45. }
  46. return conn, nil
  47. }
  48. // isLoopbackURL is a utility function that determines whether the
  49. // given url.URL's host part resolves to a loopback ip addr or not.
  50. func isLoopbackURL(u *url.URL) bool {
  51. // Resolve url to ip addresses.
  52. ips, err := net.LookupIP(u.Hostname())
  53. if err != nil {
  54. fmt.Println(err)
  55. return false
  56. }
  57. // Ensure all resolved ip addrs are loopback addrs.
  58. for _, ip := range ips {
  59. if !ip.IsLoopback() {
  60. return false
  61. }
  62. }
  63. return true
  64. }
  65. func stringInSlice(a string, list []string) bool {
  66. for _, b := range list {
  67. if b == a {
  68. return true
  69. }
  70. }
  71. return false
  72. }
  73. func exit(status int) {
  74. if flag.Lookup("test.v") == nil {
  75. os.Exit(status)
  76. } else {
  77. }
  78. }
  79. // Prints the received message followed by the usage string.
  80. func failureMsg(c *cli.Context, msg string) {
  81. fmt.Printf(msg)
  82. fmt.Println()
  83. fmt.Println(cli.ShowSubcommandHelp(c))
  84. }