• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

Golang activation.Listeners函数代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了Golang中github.com/coreos/go-systemd/activation.Listeners函数的典型用法代码示例。如果您正苦于以下问题:Golang Listeners函数的具体用法?Golang Listeners怎么用?Golang Listeners使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。



在下文中一共展示了Listeners函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。

示例1: main

func main() {
	fixListenPid()

	listeners, _ := activation.Listeners(false)

	if len(listeners) == 0 {
		panic("No listeners")
	}

	if os.Getenv("LISTEN_PID") == "" || os.Getenv("LISTEN_FDS") == "" {
		panic("Should not unset envs")
	}

	listeners, err := activation.Listeners(true)
	if err != nil {
		panic(err)
	}

	if os.Getenv("LISTEN_PID") != "" || os.Getenv("LISTEN_FDS") != "" {
		panic("Can not unset envs")
	}

	c0, _ := listeners[0].Accept()
	c1, _ := listeners[1].Accept()

	// Write out the expected strings to the two pipes
	c0.Write([]byte("Hello world"))
	c1.Write([]byte("Goodbye world"))

	return
}
开发者ID:tychoish,项目名称:grip,代码行数:31,代码来源:listen.go


示例2: Init

// Init sets up the Daemon's internal workings.
// Don't call more than once.
func (d *Daemon) Init() error {
	t0 := time.Now()
	listeners, err := activation.Listeners(false)
	if err != nil {
		return err
	}

	listenerMap := make(map[string]net.Listener)

	for _, listener := range listeners {
		listenerMap[listener.Addr().String()] = listener
	}

	// The SnapdSocket is required-- without it, die.
	if listener, ok := listenerMap[dirs.SnapdSocket]; ok {
		d.snapdListener = &ucrednetListener{listener}
	} else {
		return fmt.Errorf("daemon is missing the listener for %s", dirs.SnapdSocket)
	}

	// Note that the SnapSocket listener does not use ucrednet. We use the lack
	// of remote information as an indication that the request originated with
	// this socket. This listener may also be nil if that socket wasn't among
	// the listeners, so check it before using it.
	d.snapListener = listenerMap[dirs.SnapSocket]

	d.addRoutes()

	logger.Debugf("init done in %s", time.Now().Sub(t0))

	return nil
}
开发者ID:clobrano,项目名称:snappy,代码行数:34,代码来源:daemon.go


示例3: fdListener

func fdListener(addr string) (net.Listener, error) {
	fdOffset := 0
	if addr != "" {
		fd, err := strconv.Atoi(addr)
		if err != nil {
			return nil, fmt.Errorf("fd index is not a number")
		}
		fdOffset = fd - 3
	}

	listeners, err := activation.Listeners(false)
	if err != nil {
		return nil, err
	}

	if fdOffset >= len(listeners) {
		return nil, fmt.Errorf("fd %v is out of range (%v)", addr, len(listeners)+3)
	}

	if listeners[fdOffset] == nil {
		return nil, fmt.Errorf("fd %v was not socket activated", addr)
	}

	return listeners[fdOffset], nil
}
开发者ID:luxas,项目名称:flannel,代码行数:25,代码来源:server.go


示例4: ListenFD

// ListenFD returns the specified socket activated files as a slice of
// net.Listeners or all of the activated files if "*" is given.
func ListenFD(addr string) ([]net.Listener, error) {
	// socket activation
	listeners, err := activation.Listeners(false)
	if err != nil {
		return nil, err
	}

	if listeners == nil || len(listeners) == 0 {
		return nil, errors.New("No sockets found")
	}

	// default to all fds just like unix:// and tcp://
	if addr == "" {
		addr = "*"
	}

	fdNum, _ := strconv.Atoi(addr)
	fdOffset := fdNum - 3
	if (addr != "*") && (len(listeners) < int(fdOffset)+1) {
		return nil, errors.New("Too few socket activated files passed in")
	}

	if addr == "*" {
		return listeners, nil
	}

	return []net.Listener{listeners[fdOffset]}, nil
}
开发者ID:98pm,项目名称:docker,代码行数:30,代码来源:listendfd.go


示例5: main

func main() {

	log.SetFlags(0)
	flag.Parse()

	os.Setenv("DISCOVERY_URL", url)

	if os.Getenv("DISCOVERY_ADDR") != "" {
		http.ListenAndServe(os.Getenv("DISCOVERY_ADDR"), nil)
	} else {
		if *addr != "" {
			http.ListenAndServe(*addr, nil)
		}
	}

	listeners, err := activation.Listeners(true)
	if err != nil {
		panic(err)
	}

	if len(listeners) != 1 {
		log.Print(len(listeners))
		panic("Unexpected number of socket activation fds:")
	}

	http.Serve(listeners[0], nil)
}
开发者ID:nimblestratus,项目名称:discovery.etcd.io,代码行数:27,代码来源:discovery.go


示例6: socketActivationListener

func socketActivationListener() net.Listener {
	listeners, err := activation.Listeners(true)
	if err != nil {
		panic(err)
	}

	if len(listeners) != 1 {
		panic(fmt.Sprintf("Unexpected number of socket activation fds, got: %d listeners, expected 1!", len(listeners)))
	}

	return listeners[0]
}
开发者ID:jawi,项目名称:mad,代码行数:12,代码来源:srv_linux.go


示例7: main

func main() {
	listeners, err := activation.Listeners(true)
	if err != nil {
		panic(err)
	}

	if len(listeners) != 1 {
		panic("Unexpected number of socket activation fds")
	}

	http.HandleFunc("/", HelloServer)
	http.Serve(listeners[0], nil)
}
开发者ID:camarox53,项目名称:coreos-baremetal,代码行数:13,代码来源:httpserver.go


示例8: systemdServe

func (s *Server) systemdServe() {
	// We will usually have at least one TCP socket and one UDP socket.
	// PacketConns are UDP sockets, Listeners are TCP sockets.
	// To make things more annoying, both can (and usually will) have nil
	// entries for the file descriptors that don't match.
	pconns, err := activation.PacketConns(false)
	if err != nil {
		glog.Fatalf("Error getting systemd packet conns: %v", err)
	}

	listeners, err := activation.Listeners(false)
	if err != nil {
		glog.Fatalf("Error getting systemd listeners: %v", err)
	}

	var wg sync.WaitGroup

	for _, pconn := range pconns {
		if pconn == nil {
			continue
		}

		wg.Add(1)
		go func(c net.PacketConn) {
			defer wg.Done()
			glog.Infof("Activate on packet connection (UDP)")
			err := dns.ActivateAndServe(nil, c, dns.HandlerFunc(s.Handler))
			glog.Fatalf("Exiting UDP listener: %v", err)
		}(pconn)
	}

	for _, lis := range listeners {
		if lis == nil {
			continue
		}

		wg.Add(1)
		go func(l net.Listener) {
			defer wg.Done()
			glog.Infof("Activate on listening socket (TCP)")
			err := dns.ActivateAndServe(l, nil, dns.HandlerFunc(s.Handler))
			glog.Fatalf("Exiting TCP listener: %v", err)
		}(lis)
	}

	wg.Wait()

	// We should only get here if there were no useful sockets.
	glog.Fatalf("No systemd sockets, did you forget the .socket?")
}
开发者ID:albertito,项目名称:dnss,代码行数:50,代码来源:dnstox.go


示例9: Serve

// Serve either serves on the previously opened sockets if started with systemd-compatible protocol, or:
//  - opens sockets and starts /proc/self/exe in a subprocess with systemd-compatible protocol
//  - gracefully terminates subprocess on SIGTERM
//  - gracefully restarts subprocess on SIGUSR2
func Serve(servers ...*http.Server) error {
	// Simplify LISTEN_PID protocol because it is harder to set PID between
	// fork and exec in Golang.
	pid := os.Getenv(listenPID)
	initActivated := len(pid) != 0 && pid != "0"
	if pid == "0" {
		if err := os.Setenv(listenPID, strconv.Itoa(os.Getpid())); err != nil {
			return err
		}
	}

	listeners, _ := activation.Listeners(true) // ignore error: always nil
	didInherit := len(listeners) != 0

	if *verbose {
		if didInherit {
			if initActivated {
				log.Printf("Listening on init activated %s", pprintAddr(servers))
			} else {
				const msg = "Graceful handoff of %s with new pid %d"
				log.Printf(msg, pprintAddr(servers), os.Getpid())
			}
		} else {
			const msg = "Serving %s with pid %d"
			log.Printf(msg, pprintAddr(servers), os.Getpid())
		}
	}

	if didInherit {
		// Serve.
		return serve(listeners, servers)
	}

	// Listen and fork&exec to serve.
	fds := make([]*os.File, len(servers))
	for i, srv := range servers {
		l, err := net.Listen("tcp", srv.Addr)
		if err != nil {
			return err
		}

		fds[i], err = l.(*net.TCPListener).File()
		if err != nil {
			return err
		}
		defer fds[i].Close() // ignore error
	}

	return runServer(fds)
}
开发者ID:orivej,项目名称:grace,代码行数:54,代码来源:http.go


示例10: cmdRunSa

func cmdRunSa(c *cli.Context) error {
	s, err := openAndCheck(c)
	if err != nil {
		return cli.NewExitError(err.Error(), 3)
	}

	listeners, err := activation.Listeners(true)
	if err != nil {
		return cli.NewExitError(fmt.Sprintf("fetching socket listeners from systemd failed: %s", err), 2)
	}

	fmt.Printf("got %d sockets from systemd\n", len(listeners))
	if len(listeners) == 0 {
		return cli.NewExitError("shutting down since there are no sockets to lissten on.", 2)
	}

	var wg sync.WaitGroup
	for idx, listener := range listeners {
		switch listener.(type) {
		case *net.UnixListener:
			fmt.Printf("listener[%d]: is a UNIX socket (-> saslauthd)\n", idx)
			wg.Add(1)
			ln := listener.(*net.UnixListener)
			go func() {
				defer wg.Done()
				if err := runSaslAuthSocketListener(ln, s.GetInterface()); err != nil {
					fmt.Printf("warning running auth agent failed: %s\n", err)
				}
			}()
		case *net.TCPListener:
			fmt.Printf("listener[%d]: is a TCP socket (-> HTTP)\n", idx)
			wg.Add(1)
			ln := listener.(*net.TCPListener)
			go func() {
				defer wg.Done()
				if err := runWebListener(ln, s.GetInterface(), c.GlobalString("web-static-dir")); err != nil {
					fmt.Printf("error running web-api: %s", err)
				}
			}()
		default:
			fmt.Printf("listener[%d]: has type %T (ingnoring)\n", idx, listener)
		}
	}
	wg.Wait()

	return cli.NewExitError(fmt.Sprintf("shutting down since all auth sockets have closed."), 0)
}
开发者ID:whawty,项目名称:auth,代码行数:47,代码来源:main.go


示例11: listenFD

// listenFD returns the specified socket activated files as a slice of
// net.Listeners or all of the activated files if "*" is given.
func listenFD(addr string, tlsConfig *tls.Config) ([]net.Listener, error) {
	var (
		err       error
		listeners []net.Listener
	)
	// socket activation
	if tlsConfig != nil {
		listeners, err = activation.TLSListeners(false, tlsConfig)
	} else {
		listeners, err = activation.Listeners(false)
	}
	if err != nil {
		return nil, err
	}

	if len(listeners) == 0 {
		return nil, fmt.Errorf("no sockets found via socket activation: make sure the service was started by systemd")
	}

	// default to all fds just like unix:// and tcp://
	if addr == "" || addr == "*" {
		return listeners, nil
	}

	fdNum, err := strconv.Atoi(addr)
	if err != nil {
		return nil, fmt.Errorf("failed to parse systemd fd address: should be a number: %v", addr)
	}
	fdOffset := fdNum - 3
	if len(listeners) < int(fdOffset)+1 {
		return nil, fmt.Errorf("too few socket activated files passed in by systemd")
	}
	if listeners[fdOffset] == nil {
		return nil, fmt.Errorf("failed to listen on systemd activated file: fd %d", fdOffset+3)
	}
	for i, ls := range listeners {
		if i == fdOffset || ls == nil {
			continue
		}
		if err := ls.Close(); err != nil {
			// TODO: We shouldn't log inside a library. Remove this or error out.
			logrus.Errorf("failed to close systemd activated file: fd %d: %v", fdOffset+3, err)
		}
	}
	return []net.Listener{listeners[fdOffset]}, nil
}
开发者ID:Altiscale,项目名称:containerd,代码行数:48,代码来源:listeners_unix.go


示例12: listenFD

// listenFD returns the specified socket activated files as a slice of
// net.Listeners or all of the activated files if "*" is given.
func listenFD(addr string, tlsConfig *tls.Config) ([]net.Listener, error) {
	var (
		err       error
		listeners []net.Listener
	)
	// socket activation
	if tlsConfig != nil {
		listeners, err = systemdActivation.TLSListeners(false, tlsConfig)
	} else {
		listeners, err = systemdActivation.Listeners(false)
	}
	if err != nil {
		return nil, err
	}

	if len(listeners) == 0 {
		return nil, fmt.Errorf("No sockets found")
	}

	// default to all fds just like unix:// and tcp://
	if addr == "" || addr == "*" {
		return listeners, nil
	}

	fdNum, err := strconv.Atoi(addr)
	if err != nil {
		return nil, fmt.Errorf("failed to parse systemd address, should be number: %v", err)
	}
	fdOffset := fdNum - 3
	if len(listeners) < int(fdOffset)+1 {
		return nil, fmt.Errorf("Too few socket activated files passed in")
	}
	if listeners[fdOffset] == nil {
		return nil, fmt.Errorf("failed to listen on systemd activated file at fd %d", fdOffset+3)
	}
	for i, ls := range listeners {
		if i == fdOffset || ls == nil {
			continue
		}
		if err := ls.Close(); err != nil {
			logrus.Errorf("Failed to close systemd activated file at fd %d: %v", fdOffset+3, err)
		}
	}
	return []net.Listener{listeners[fdOffset]}, nil
}
开发者ID:DaveDaCoda,项目名称:docker,代码行数:47,代码来源:server_unix.go


示例13: main

func main() {
	log.SetFlags(0)
	flag.Parse()

	if *addr != "" {
		http.ListenAndServe(*addr, nil)
	}

	listeners, err := activation.Listeners(true)
	if err != nil {
		panic(err)
	}

	if len(listeners) != 1 {
		panic("Unexpected number of socket activation fds")
	}

	http.Serve(listeners[0], nil)
}
开发者ID:omkensey,项目名称:discovery.etcd.io,代码行数:19,代码来源:discovery.go


示例14: Init

// Init sets up the Daemon's internal workings.
// Don't call more than once.
func (d *Daemon) Init() error {
	t0 := time.Now()
	listeners, err := activation.Listeners(false)
	if err != nil {
		return err
	}

	if len(listeners) != 1 {
		return fmt.Errorf("daemon does not handle %d listeners right now, just one", len(listeners))
	}

	d.listener = listeners[0]

	d.addRoutes()

	logger.Debugf("init done in %s", time.Now().Sub(t0))

	return nil
}
开发者ID:General-Beck,项目名称:snappy,代码行数:21,代码来源:daemon.go


示例15: getListener

func getListener() (net.Listener, error) {
	l, err := activation.Listeners(true)
	if err != nil {
		return nil, err
	}

	switch {
	case len(l) == 0:
		if err := os.MkdirAll(filepath.Dir(socketPath), 0700); err != nil {
			return nil, err
		}
		return net.Listen("unix", socketPath)

	case len(l) == 1:
		if l[0] == nil {
			return nil, fmt.Errorf("LISTEN_FDS=1 but no FD found")
		}
		return l[0], nil

	default:
		return nil, fmt.Errorf("Too many (%v) FDs passed through socket activation", len(l))
	}
}
开发者ID:zachgersh,项目名称:cni,代码行数:23,代码来源:daemon.go


示例16: Run

// Run is a blocking operation that starts the server listening on the DNS ports.
func (s *server) Run() error {
	mux := dns.NewServeMux()
	mux.Handle(".", s)

	dnsReadyMsg := func(addr, net string) {
		if s.config.DNSSEC == "" {
			log.Printf("skydns: ready for queries on %s for %s://%s [rcache %d]", s.config.Domain, net, addr, s.config.RCache)
		} else {
			log.Printf("skydns: ready for queries on %s for %s://%s [rcache %d], signing with %s [scache %d]", s.config.Domain, net, addr, s.config.RCache, s.config.DNSSEC, s.config.SCache)
		}
	}

	if s.config.Systemd {
		packetConns, err := activation.PacketConns(false)
		if err != nil {
			return err
		}
		listeners, err := activation.Listeners(true)
		if err != nil {
			return err
		}
		if len(packetConns) == 0 && len(listeners) == 0 {
			return fmt.Errorf("no UDP or TCP sockets supplied by systemd")
		}
		for _, p := range packetConns {
			if u, ok := p.(*net.UDPConn); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(nil, u, mux); err != nil {
						log.Fatalf("skydns: %s", err)
					}
				}()
				dnsReadyMsg(u.LocalAddr().String(), "udp")
			}
		}
		for _, l := range listeners {
			if t, ok := l.(*net.TCPListener); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(t, nil, mux); err != nil {
						log.Fatalf("skydns: %s", err)
					}
				}()
				dnsReadyMsg(t.Addr().String(), "tcp")
			}
		}
	} else {
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "tcp", mux); err != nil {
				log.Fatalf("skydns: %s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "tcp")
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "udp", mux); err != nil {
				log.Fatalf("skydns: %s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "udp")
	}

	s.group.Wait()
	return nil
}
开发者ID:wealthworks,项目名称:skydns,代码行数:71,代码来源:server.go


示例17: Run

// Run is a blocking operation that starts the server listening on the DNS ports.
func (s *server) Run() error {
	mux := dns.NewServeMux()
	mux.Handle(".", s)

	dnsReadyMsg := func(addr, net string) {
		rCacheState := "disabled"
		if s.config.RCache > 0 {
			rCacheState = fmt.Sprintf("capacity: %d", s.config.RCache)
		}
		log.Infof("Ready for queries on %s://%s [cache: %s]", net, addr, rCacheState)
	}

	if s.config.Systemd {
		packetConns, err := activation.PacketConns(false)
		if err != nil {
			return err
		}
		listeners, err := activation.Listeners(true)
		if err != nil {
			return err
		}
		if len(packetConns) == 0 && len(listeners) == 0 {
			return fmt.Errorf("No UDP or TCP sockets supplied by systemd")
		}
		for _, p := range packetConns {
			if u, ok := p.(*net.UDPConn); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(nil, u, mux); err != nil {
						log.Fatalf("%s", err)
					}
				}()
				dnsReadyMsg(u.LocalAddr().String(), "udp")
			}
		}
		for _, l := range listeners {
			if t, ok := l.(*net.TCPListener); ok {
				s.group.Add(1)
				go func() {
					defer s.group.Done()
					if err := dns.ActivateAndServe(t, nil, mux); err != nil {
						log.Fatalf("%s", err)
					}
				}()
				dnsReadyMsg(t.Addr().String(), "tcp")
			}
		}
	} else {
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "tcp", mux); err != nil {
				log.Fatalf("%s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "tcp")
		s.group.Add(1)
		go func() {
			defer s.group.Done()
			if err := dns.ListenAndServe(s.config.DnsAddr, "udp", mux); err != nil {
				log.Fatalf("%s", err)
			}
		}()
		dnsReadyMsg(s.config.DnsAddr, "udp")
	}

	s.group.Wait()
	return nil
}
开发者ID:janeczku,项目名称:go-dnsmasq,代码行数:71,代码来源:server.go


示例18: Init


//.........这里部分代码省略.........
				tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256},
			PreferServerCipherSuites: true,
		}
		tlsConfig.BuildNameToCertificate()

		d.tlsConfig = tlsConfig

		readSavedClientCAList(d)
	}

	/* Setup the web server */
	d.mux = mux.NewRouter()
	d.mux.StrictSlash(false)

	d.mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
		w.Header().Set("Content-Type", "application/json")
		SyncResponse(true, []string{"/1.0"}).Render(w)
	})

	for _, c := range api10 {
		d.createCmd("1.0", c)
	}

	for _, c := range apiInternal {
		d.createCmd("internal", c)
	}

	d.mux.NotFoundHandler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		shared.Log.Debug("Sending top level 404", log.Ctx{"url": r.URL})
		w.Header().Set("Content-Type", "application/json")
		NotFound.Render(w)
	})

	listeners, err := activation.Listeners(false)
	if err != nil {
		return err
	}

	if len(listeners) > 0 {
		shared.Log.Info("LXD is socket activated")

		for _, listener := range listeners {
			if shared.PathExists(listener.Addr().String()) {
				d.UnixSocket = &Socket{Socket: listener, CloseOnExit: false}
			} else {
				tlsListener := tls.NewListener(listener, d.tlsConfig)
				d.TCPSocket = &Socket{Socket: tlsListener, CloseOnExit: false}
			}
		}
	} else {
		shared.Log.Info("LXD isn't socket activated")

		localSocketPath := shared.VarPath("unix.socket")

		// If the socket exists, let's try to connect to it and see if there's
		// a lxd running.
		if shared.PathExists(localSocketPath) {
			_, err := lxd.NewClient(&lxd.DefaultConfig, "local")
			if err != nil {
				shared.Log.Debug("Detected stale unix socket, deleting")
				// Connecting failed, so let's delete the socket and
				// listen on it ourselves.
				err = os.Remove(localSocketPath)
				if err != nil {
					return err
				}
开发者ID:jsavikko,项目名称:lxd,代码行数:67,代码来源:daemon.go


示例19: main

func main() {
	var patterns []matcher
	var n int

	if len(os.Args) < 2 {
		usage()
	}

	for n = 1; ; n += 1 {
		if bytes.Equal([]byte(os.Args[n])[:2], []byte("--")) {
			break
		}

		if n == len(os.Args)-1 {
			usage()
		}
	}

	firstFilterArg := n

	for ; n < len(os.Args)-1; n += 2 {
		if bytes.Equal([]byte(os.Args[n]), []byte("--regex")) {
			if len(os.Args) < n+2 {
				fmt.Println("Not enough arguments to --regex")
				os.Exit(1)
			}
			host, port, err := parseHostPort(os.Args[n+2])
			if err != nil {
				fmt.Println("Bad host:port specification:", os.Args[n+2], host, port, err)
				os.Exit(1)
			}

			r, err := regexp.Compile(os.Args[n+1])
			if err != nil {
				fmt.Println("Failed to compile regular expression:", os.Args[n+1], err)
				os.Exit(1)
			}

			patterns = append(patterns, (func(packet []byte, length int) (h string, p int) {
				h = host
				if r.Match(packet) {
					p = port
				}
				return
			}))

			n += 1
			continue
		}

		host, port, err := parseHostPort(os.Args[n+1])
		if err != nil {
			fmt.Println("Bad host:port specification:", os.Args[n+1], host, port, err)
			os.Exit(1)
		}
		if bytes.Equal([]byte(os.Args[n]), []byte("--ssh")) {
			patterns = append(patterns, (func(packet []byte, length int) (h string, p int) {
				h = host
				if bytes.Equal(packet[:4], []byte("SSH-")) {
					p = port
				}
				return
			}))
		} else if bytes.Equal([]byte(os.Args[n]), []byte("--ssl")) {
			patterns = append(patterns, (func(pack []byte, length int) (h string, p int) {
				h = host
				if bytes.Equal(pack[:2], []byte{0x16, 0x03}) && pack[3] >= 0x00 && pack[3] <= 0x03 {
					p = port
				}
				return
			}))
		} else if bytes.Equal([]byte(os.Args[n]), []byte("--openvpn")) {
			patterns = append(patterns, (func(pack []byte, length int) (h string, p int) {
				var l uint16
				h = host
				binary.Read(bytes.NewReader(pack), binary.BigEndian, &l)
				if l == uint16(length-2) {
					p = port
				}
				return
			}))
		}
	}

	listeners, err := activation.Listeners(true)

	if err != nil {
		panic(err)
	}

	// If we recieved any sockets from systemd do not open our own listeners
	if len(listeners) > 0 {
		for _, ln := range listeners {
			go handleListener(ln, patterns)
		}
	} else {
		if firstFilterArg == 1 {
			fmt.Println("No listen port(s) specified and did not recieve and not being systemd socket activated")
			os.Exit(1)
		}
//.........这里部分代码省略.........
开发者ID:postfix,项目名称:multiplexd,代码行数:101,代码来源:multiplexd.go


示例20: New

func New(cfg config.Config, listeners []net.Listener) (*Server, error) {
	agentTTL, err := time.ParseDuration(cfg.AgentTTL)
	if err != nil {
		return nil, err
	}

	mgr, err := systemd.NewSystemdUnitManager(systemd.DefaultUnitsDirectory)
	if err != nil {
		return nil, err
	}

	mach, err := newMachineFromConfig(cfg, mgr)
	if err != nil {
		return nil, err
	}

	tlsConfig, err := pkg.ReadTLSConfigFiles(cfg.EtcdCAFile, cfg.EtcdCertFile, cfg.EtcdKeyFile)
	if err != nil {
		return nil, err
	}

	eCfg := etcd.Config{
		Transport:               &http.Transport{TLSClientConfig: tlsConfig},
		Endpoints:               cfg.EtcdServers,
		HeaderTimeoutPerRequest: (time.Duration(cfg.EtcdRequestTimeout*1000) * time.Millisecond),
	}
	eClient, err := etcd.New(eCfg)
	if err != nil {
		return nil, err
	}

	kAPI := etcd.NewKeysAPI(eClient)
	reg := registry.NewEtcdRegistry(kAPI, cfg.EtcdKeyPrefix)

	pub := agent.NewUnitStatePublisher(reg, mach, agentTTL)
	gen := unit.NewUnitStateGenerator(mgr)

	a := agent.New(mgr, gen, reg, mach, agentTTL)

	var rStream pkg.EventStream
	if !cfg.DisableWatches {
		rStream = registry.NewEtcdEventStream(kAPI, cfg.EtcdKeyPrefix)
	}
	lManager := lease.NewEtcdLeaseManager(kAPI, cfg.EtcdKeyPrefix)

	ar := agent.NewReconciler(reg, rStream)

	e := engine.New(reg, lManager, rStream, mach)

	if len(listeners) == 0 {
		listeners, err = activation.Listeners(false)
		if err != nil {
			return nil, err
		}
	}

	hrt := heart.New(reg, mach)
	mon := NewMonitor(agentTTL)

	apiServer := api.NewServer(listeners, api.NewServeMux(reg, cfg.TokenLimit))
	apiServer.Serve()

	eIval := time.Duration(cfg.EngineReconcileInterval*1000) * time.Millisecond

	srv := Server{
		agent:       a,
		aReconciler: ar,
		usGen:       gen,
		usPub:       pub,
		engine:      e,
		mach:        mach,
		hrt:         hrt,
		mon:         mon,
		api:         apiServer,
		killc:       make(chan struct{}),
		stopc:       nil,
		engineReconcileInterval: eIval,
		disableEngine:           cfg.DisableEngine,
		reconfigServer:          false,
		restartServer:           false,
	}

	return &srv, nil
}
开发者ID:pulcy,项目名称:j2,代码行数:84,代码来源:server.go



注:本文中的github.com/coreos/go-systemd/activation.Listeners函数示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
Golang daemon.SdNotify函数代码示例发布时间:2022-05-23
下一篇:
Golang semver.Version类代码示例发布时间:2022-05-23
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap