-
Notifications
You must be signed in to change notification settings - Fork 7
/
service.go
165 lines (131 loc) · 3.89 KB
/
service.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
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
// Copyright 2016 Nevio Vesic
// Please check out LICENSE file for more information about limitations
// MIT License
package main
import (
"io/ioutil"
"net"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"golang.org/x/net/context"
log "github.com/Sirupsen/logrus"
graceful "gopkg.in/tylerb/graceful.v1"
"github.com/gorilla/mux"
"github.com/koding/cache"
"github.com/0x19/disposable/protos"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
// Service -
type Service struct {
GRPCAddr, HTTPAddr string
done chan bool
GRPCListener net.Listener
GRPC *grpc.Server
Cache *cache.MemoryTTL
Ctx context.Context
CtxCancel context.CancelFunc
DisposableEmails *DisposableEmails
}
// RegisterAndListenGrpcServer -
func (s *Service) RegisterAndListenGrpcServer() error {
log.Infof("[register_grpc_server] Registering GRPC services...")
var err error
if s.GRPCListener, err = net.Listen("tcp", s.GRPCAddr); err != nil {
return err
}
certfile := OptionString("GRPC_CA_FILE", "")
if cert := OptionString("GRPC_CA", ""); cert != "" {
cf, _ := ioutil.TempFile(os.TempDir(), "grpc_")
cf.WriteString(cert)
defer os.Remove(cf.Name())
certfile = cf.Name()
}
keyfile := OptionString("GRPC_KEY_FILE", "")
if key := OptionString("GRPC_KEY", ""); key != "" {
kf, _ := ioutil.TempFile(os.TempDir(), "grpc_")
kf.WriteString(key)
defer os.Remove(kf.Name())
keyfile = kf.Name()
}
creds, err := credentials.NewServerTLSFromFile(certfile, keyfile)
if err != nil {
log.Errorf("[register_grpc_server] Could not create new server from TLS due to (err: %s)", err)
return err
}
s.GRPC = grpc.NewServer([]grpc.ServerOption{grpc.Creds(creds)}...)
disposable.RegisterDisposableServiceServer(s.GRPC, s)
return s.GRPC.Serve(s.GRPCListener)
}
// RegisterAndListenHTTPServer -
func (s *Service) RegisterAndListenHTTPServer() error {
log.Infof("[register_http_server] Registering HTTP services...")
httpmux := mux.NewRouter()
httpmux.NotFoundHandler = http.HandlerFunc(HandleNotFound)
httpmux.HandleFunc("/v1/verify", Use(func(w http.ResponseWriter, req *http.Request) {
HandleVerifyEmail(s, w, req)
}, BasicAuth, CapturePanic, CompressionHandler)).Methods("POST")
srv := &graceful.Server{
Timeout: 10 * time.Second,
Server: &http.Server{
Addr: s.HTTPAddr,
Handler: httpmux,
},
}
return srv.ListenAndServe()
}
// HandleSigterm - Will basically wait for channel to close and than initiate
// service stop logic followed by actual exit.
func (s *Service) HandleSigterm(kill chan os.Signal) {
<-kill
s.CtxCancel()
}
// Start -
func (s *Service) Start() (err error) {
log.Infof("[start] Starting up (grpc: %s) and (http: %s) services...", s.GRPCAddr, s.HTTPAddr)
defer s.CtxCancel()
errors := make(chan error)
kill := make(chan os.Signal, 1)
s.done = make(chan bool)
signal.Notify(kill, os.Interrupt)
signal.Notify(kill, syscall.SIGTERM)
go s.HandleSigterm(kill)
go func() { errors <- s.RegisterAndListenGrpcServer() }()
go func() { errors <- s.RegisterAndListenHTTPServer() }()
go func() {
if err := s.DisposableEmails.Load(); err != nil {
errors <- err
}
}()
select {
case err := <-errors:
log.Errorf("[start] Failed to serve services due to (err: %s)", err)
s.CtxCancel()
return err
case <-s.Ctx.Done():
log.Warn("[start] Received shutdown signal. Exiting service...")
os.Exit(0)
}
return
}
// New -
func New() (*Service, error) {
cache := cache.NewMemoryWithTTL(10 * time.Minute)
cache.StartGC(1 * time.Second)
emails, deerr := NewDisposableEmails()
if deerr != nil {
return nil, deerr
}
ctx, cancel := context.WithCancel(context.Background())
return &Service{
GRPCAddr: OptionString("GRPC_ADDR", ":6874"),
HTTPAddr: OptionString("HTTP_ADDR", ":4432"),
Cache: cache,
Ctx: ctx,
CtxCancel: cancel,
DisposableEmails: emails,
}, nil
}