github.com/godevsig/adaptiveservice@v0.9.23/examples/builtin/builtin.go (about)

     1  package main
     2  
     3  import (
     4  	"flag"
     5  	"fmt"
     6  	"os"
     7  	"sort"
     8  	"strings"
     9  
    10  	as "github.com/godevsig/adaptiveservice"
    11  )
    12  
    13  type subCmd struct {
    14  	*flag.FlagSet
    15  	action func() int
    16  }
    17  
    18  func trimName(name string, size int) string {
    19  	if len(name) > size {
    20  		name = name[:size-3] + "..."
    21  	}
    22  	return name
    23  }
    24  
    25  func getSelfID(opts []as.Option) (selfID string, err error) {
    26  	opts = append(opts, as.WithScope(as.ScopeProcess|as.ScopeOS))
    27  	c := as.NewClient(opts...).SetDiscoverTimeout(0)
    28  	conn := <-c.Discover(as.BuiltinPublisher, as.SrvProviderInfo)
    29  	if conn == nil {
    30  		return "", as.ErrServiceNotFound(as.BuiltinPublisher, as.SrvProviderInfo)
    31  	}
    32  	defer conn.Close()
    33  
    34  	err = conn.SendRecv(&as.ReqProviderInfo{}, &selfID)
    35  	return
    36  }
    37  
    38  func main() {
    39  	var cmds []subCmd
    40  	{
    41  		cmd := flag.NewFlagSet("server", flag.ExitOnError)
    42  		cmd.SetOutput(os.Stdout)
    43  
    44  		debug := cmd.Bool("d", false, "enable debug")
    45  		rootRegistry := cmd.Bool("root", false, "enable root registry service")
    46  		reverseProxy := cmd.Bool("proxy", false, "enable reverse proxy service")
    47  		serviceLister := cmd.Bool("lister", false, "enable service lister service")
    48  		registryAddr := cmd.String("registry", "", "root registry address")
    49  		lanBroadcastPort := cmd.String("bcast", "", "broadcast port for LAN")
    50  
    51  		action := func() int {
    52  			cmd.Parse(os.Args[2:])
    53  			if len(*registryAddr) == 0 {
    54  				panic("root registry address not set")
    55  			}
    56  			if len(*lanBroadcastPort) == 0 {
    57  				panic("lan broadcast port not set")
    58  			}
    59  
    60  			var opts []as.Option
    61  			opts = append(opts, as.WithRegistryAddr(*registryAddr))
    62  			if *debug {
    63  				opts = append(opts, as.WithLogger(as.LoggerAll{}))
    64  			}
    65  
    66  			s := as.NewServer(opts...)
    67  			s.SetBroadcastPort(*lanBroadcastPort)
    68  
    69  			if *rootRegistry {
    70  				s.EnableRootRegistry()
    71  			}
    72  			if *reverseProxy {
    73  				s.EnableAutoReverseProxy()
    74  			}
    75  			if *serviceLister {
    76  				s.EnableServiceLister()
    77  			}
    78  
    79  			s.Serve()
    80  			return 0
    81  		}
    82  
    83  		cmds = append(cmds, subCmd{cmd, action})
    84  	}
    85  	{
    86  		cmd := flag.NewFlagSet("list", flag.ExitOnError)
    87  		cmd.SetOutput(os.Stdout)
    88  
    89  		debug := cmd.Bool("d", false, "enable debug")
    90  		verbose := cmd.Bool("v", false, "show verbose info")
    91  		publisher := cmd.String("p", "*", "publisher name, can be wildcard")
    92  		service := cmd.String("s", "*", "service name, can be wildcard")
    93  
    94  		action := func() int {
    95  			cmd.Parse(os.Args[2:])
    96  			var opts []as.Option
    97  			if *debug {
    98  				opts = append(opts, as.WithLogger(as.LoggerAll{}))
    99  			}
   100  			selfID, err := getSelfID(opts)
   101  			if err != nil {
   102  				fmt.Println(err)
   103  				return 1
   104  			}
   105  
   106  			c := as.NewClient(opts...)
   107  			conn := <-c.Discover(as.BuiltinPublisher, as.SrvServiceLister)
   108  			if conn == nil {
   109  				fmt.Println(as.ErrServiceNotFound(as.BuiltinPublisher, as.SrvServiceLister))
   110  				return 1
   111  			}
   112  			defer conn.Close()
   113  
   114  			msg := as.ListService{TargetScope: as.ScopeAll, Publisher: *publisher, Service: *service}
   115  			var scopes [4][]*as.ServiceInfo
   116  			if err := conn.SendRecv(&msg, &scopes); err != nil {
   117  				fmt.Println(err)
   118  				return 1
   119  			}
   120  			if *verbose {
   121  				for _, services := range scopes {
   122  					for _, svc := range services {
   123  						if svc.ProviderID == selfID {
   124  							svc.ProviderID = "self"
   125  						}
   126  						fmt.Printf("PUBLISHER: %s\n", svc.Publisher)
   127  						fmt.Printf("SERVICE  : %s\n", svc.Service)
   128  						fmt.Printf("PROVIDER : %s\n", svc.ProviderID)
   129  						addr := svc.Addr
   130  						if addr[len(addr)-1] == 'P' {
   131  							addr = addr[:len(addr)-1] + "(proxied)"
   132  						}
   133  						fmt.Printf("ADDRESS  : %s\n\n", addr)
   134  					}
   135  				}
   136  			} else {
   137  				list := make(map[string]*as.Scope)
   138  				for i, services := range scopes {
   139  					for _, svc := range services {
   140  						if svc.ProviderID == selfID {
   141  							svc.ProviderID = "self"
   142  						}
   143  						k := svc.Publisher + "_" + svc.Service + "_" + svc.ProviderID
   144  						p, has := list[k]
   145  						if !has {
   146  							v := as.Scope(0)
   147  							p = &v
   148  							list[k] = p
   149  						}
   150  						*p = *p | 1<<i
   151  					}
   152  				}
   153  				names := make([]string, 0, len(list))
   154  				for name := range list {
   155  					names = append(names, name)
   156  				}
   157  				sort.Strings(names)
   158  				fmt.Println("PUBLISHER           SERVICE             PROVIDER      WLOP(SCOPE)")
   159  				for _, svc := range names {
   160  					p := list[svc]
   161  					if p == nil {
   162  						panic("nil p")
   163  					}
   164  					ss := strings.Split(svc, "_")
   165  					fmt.Printf("%-18s  %-18s  %-12s  %4b\n", trimName(ss[0], 18), trimName(ss[1], 18), ss[2], *p)
   166  				}
   167  			}
   168  			return 0
   169  		}
   170  
   171  		cmds = append(cmds, subCmd{cmd, action})
   172  	}
   173  	{
   174  		cmd := flag.NewFlagSet("id", flag.ExitOnError)
   175  		cmd.SetOutput(os.Stdout)
   176  
   177  		debug := cmd.Bool("d", false, "enable debug")
   178  
   179  		action := func() int {
   180  			cmd.Parse(os.Args[2:])
   181  			var opts []as.Option
   182  			if *debug {
   183  				opts = append(opts, as.WithLogger(as.LoggerAll{}))
   184  			}
   185  			selfID, err := getSelfID(opts)
   186  			if err != nil {
   187  				fmt.Println(err)
   188  				return 1
   189  			}
   190  			fmt.Println(selfID)
   191  			return 0
   192  		}
   193  
   194  		cmds = append(cmds, subCmd{cmd, action})
   195  	}
   196  
   197  	usage := func(exitCode int) {
   198  		fmt.Println("COMMAND [OPTIONS]")
   199  		for _, cmd := range cmds {
   200  			fmt.Println(cmd.Name() + ":")
   201  			cmd.PrintDefaults()
   202  		}
   203  		os.Exit(exitCode)
   204  	}
   205  
   206  	if len(os.Args) < 2 {
   207  		usage(1)
   208  	}
   209  
   210  	str := os.Args[1]
   211  CMD:
   212  	switch str {
   213  	case "-h", "--help":
   214  		usage(0)
   215  	default:
   216  		for _, cmd := range cmds {
   217  			if str == cmd.Name() {
   218  				os.Exit(cmd.action())
   219  				break CMD
   220  			}
   221  		}
   222  		usage(1)
   223  	}
   224  }