This repository has been archived by the owner on Mar 24, 2022. It is now read-only.
forked from cloudfoundry/bosh-cli
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
104 lines (86 loc) · 2.36 KB
/
server.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package registry
import (
"fmt"
"net"
"net/http"
bosherr "github.com/cloudfoundry/bosh-utils/errors"
boshlog "github.com/cloudfoundry/bosh-utils/logger"
)
type ServerManager interface {
Start(string, string, string, int) (Server, error)
}
type serverManager struct {
logger boshlog.Logger
logTag string
}
func NewServerManager(logger boshlog.Logger) ServerManager {
return &serverManager{
logger: logger,
logTag: "registryServer",
}
}
// Create starts a new server on a goroutine and returns it
// The returned error is only for starting. Error while running is logged.
func (s *serverManager) Start(username string, password string, host string, port int) (Server, error) {
startedCh := make(chan error)
server := &server{
logger: s.logger,
logTag: "registryServer",
}
go func() {
err := server.start(username, password, host, port, startedCh)
if err != nil {
s.logger.Debug(s.logTag, "Registry error occurred: %s", err.Error())
}
}()
// block until started
err := <-startedCh
if err != nil {
if stopErr := server.Stop(); stopErr != nil {
s.logger.Warn(s.logTag, "Failed to stop server: %s", stopErr.Error())
}
}
return server, err
}
type Server interface {
Stop() error
}
type server struct {
listener net.Listener
logger boshlog.Logger
logTag string
}
func NewServer(logger boshlog.Logger) Server {
return &server{
logger: logger,
logTag: "registryServer",
}
}
func (s *server) start(username string, password string, host string, port int, readyErrCh chan error) error {
s.logger.Debug(s.logTag, "Starting registry server at %s:%d", host, port)
var err error
s.listener, err = net.Listen("tcp", fmt.Sprintf("%s:%d", host, port))
if err != nil {
readyErrCh <- bosherr.WrapError(err, "Starting registry listener")
return nil
}
readyErrCh <- nil
httpServer := http.Server{}
mux := http.NewServeMux()
httpServer.Handler = mux
registry := NewRegistry()
instanceHandler := newInstanceHandler(username, password, registry, s.logger)
mux.HandleFunc("/instances/", instanceHandler.HandleFunc)
return httpServer.Serve(s.listener)
}
func (s *server) Stop() error {
if s.listener == nil {
return bosherr.Error("Stopping not-started registry server")
}
s.logger.Debug(s.logTag, "Stopping registry server")
err := s.listener.Close()
if err != nil {
return bosherr.WrapError(err, "Stopping registry server")
}
return nil
}