-
Notifications
You must be signed in to change notification settings - Fork 310
/
manager.go
265 lines (235 loc) · 7.83 KB
/
manager.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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
/*
* Copyright (C) 2018 The "MysteriumNetwork/node" Authors.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package connection
import (
"errors"
log "github.com/cihub/seelog"
"github.com/mysterium/node/communication"
"github.com/mysterium/node/identity"
"github.com/mysterium/node/openvpn"
"github.com/mysterium/node/openvpn/middlewares/client/bytescount"
"github.com/mysterium/node/server"
"github.com/mysterium/node/service_discovery/dto"
"github.com/mysterium/node/session"
"github.com/mysterium/node/utils"
)
const managerLogPrefix = "[connection-manager] "
var (
// ErrNoConnection error indicates that action applied to manager expects active connection (i.e. disconnect)
ErrNoConnection = errors.New("no connection exists")
// ErrAlreadyExists error indicates that aciton applieto to manager expects no active connection (i.e. connect)
ErrAlreadyExists = errors.New("connection already exists")
// ErrConnectionCancelled indicates that connection in progress was cancelled by request of api user
ErrConnectionCancelled = errors.New("connection was cancelled")
// ErrOpenvpnProcessDied indicates that Connect method didn't reach "Connected" phase due to openvpn error
ErrOpenvpnProcessDied = errors.New("openvpn process died")
)
type connectionManager struct {
//these are passed on creation
mysteriumClient server.Client
newDialog DialogCreator
newVpnClient VpnClientCreator
statsKeeper bytescount.SessionStatsKeeper
//these are populated by Connect at runtime
status ConnectionStatus
cleanConnection func()
}
// NewManager creates connection manager with given dependencies
func NewManager(mysteriumClient server.Client, dialogCreator DialogCreator,
vpnClientCreator VpnClientCreator, statsKeeper bytescount.SessionStatsKeeper) *connectionManager {
return &connectionManager{
mysteriumClient: mysteriumClient,
newDialog: dialogCreator,
newVpnClient: vpnClientCreator,
statsKeeper: statsKeeper,
status: statusNotConnected(),
cleanConnection: warnOnClean,
}
}
func (manager *connectionManager) Connect(consumerID, providerID identity.Identity) (err error) {
if manager.status.State != NotConnected {
return ErrAlreadyExists
}
manager.status = statusConnecting()
defer func() {
if err != nil {
manager.status = statusNotConnected()
}
}()
err = manager.startConnection(consumerID, providerID)
if err == utils.ErrRequestCancelled {
return ErrConnectionCancelled
}
return err
}
func (manager *connectionManager) startConnection(consumerID, providerID identity.Identity) (err error) {
cancelable := utils.NewCancelable()
manager.cleanConnection = utils.CallOnce(func() {
log.Info(managerLogPrefix, "Cancelling connection initiation")
manager.status = statusDisconnecting()
cancelable.Cancel()
})
val, err := cancelable.
NewRequest(func() (interface{}, error) {
return manager.findProposalByProviderID(providerID)
}).
Call()
if err != nil {
return err
}
proposal := val.(*dto.ServiceProposal)
val, err = cancelable.
NewRequest(func() (interface{}, error) {
return manager.newDialog(consumerID, providerID, proposal.ProviderContacts[0])
}).
Cleanup(utils.InvokeOnSuccess(func(val interface{}) {
val.(communication.Dialog).Close()
})).
Call()
if err != nil {
return err
}
dialog := val.(communication.Dialog)
val, err = cancelable.
NewRequest(func() (interface{}, error) {
return session.RequestSessionCreate(dialog, proposal.ID)
}).
Call()
if err != nil {
dialog.Close()
return err
}
vpnSession := val.(*session.SessionDto)
stateChannel := make(chan openvpn.State, 10)
val, err = cancelable.
NewRequest(func() (interface{}, error) {
return manager.startOpenvpnClient(*vpnSession, consumerID, providerID, stateChannel)
}).
Cleanup(utils.InvokeOnSuccess(func(val interface{}) {
val.(openvpn.Client).Stop()
})).
Call()
if err != nil {
dialog.Close()
return err
}
openvpnClient := val.(openvpn.Client)
err = manager.waitForConnectedState(stateChannel, vpnSession.ID, cancelable.Cancelled)
if err != nil {
dialog.Close()
openvpnClient.Stop()
return err
}
manager.cleanConnection = func() {
log.Info(managerLogPrefix, "Closing active connection")
manager.status = statusDisconnecting()
if err := openvpnClient.Stop(); err != nil {
log.Warn(managerLogPrefix, "Openvpn client stopped with error: ", err)
} else {
log.Info(managerLogPrefix, "Openvpn client stopped")
}
}
go openvpnClientWaiter(openvpnClient, dialog)
go manager.consumeOpenvpnStates(stateChannel, vpnSession.ID)
return nil
}
func (manager *connectionManager) Status() ConnectionStatus {
return manager.status
}
func (manager *connectionManager) Disconnect() error {
if manager.status.State == NotConnected {
return ErrNoConnection
}
manager.cleanConnection()
return nil
}
func warnOnClean() {
log.Warn(managerLogPrefix, "Trying to close when there is nothing to close. Possible bug or race condition")
}
// TODO this can be extraced as depencency later when node selection criteria will be clear
func (manager *connectionManager) findProposalByProviderID(providerID identity.Identity) (*dto.ServiceProposal, error) {
proposals, err := manager.mysteriumClient.FindProposals(providerID.Address)
if err != nil {
return nil, err
}
if len(proposals) == 0 {
err = errors.New("provider has no service proposals")
return nil, err
}
return &proposals[0], nil
}
func openvpnClientWaiter(openvpnClient openvpn.Client, dialog communication.Dialog) {
err := openvpnClient.Wait()
if err != nil {
log.Warn(managerLogPrefix, "Openvpn client exited with error: ", err)
} else {
log.Info(managerLogPrefix, "Openvpn client exited")
}
dialog.Close()
}
func (manager *connectionManager) startOpenvpnClient(vpnSession session.SessionDto, consumerID, providerID identity.Identity, stateChannel chan openvpn.State) (openvpn.Client, error) {
openvpnClient, err := manager.newVpnClient(
vpnSession,
consumerID,
providerID,
channelToStateCallbackAdapter(stateChannel),
)
if err != nil {
return nil, err
}
if err = openvpnClient.Start(); err != nil {
return nil, err
}
return openvpnClient, nil
}
func (manager *connectionManager) waitForConnectedState(stateChannel <-chan openvpn.State, sessionID session.SessionID, cancelRequest utils.CancelChannel) error {
for {
select {
case state, more := <-stateChannel:
if !more {
return ErrOpenvpnProcessDied
}
switch state {
case openvpn.ConnectedState:
manager.onStateChanged(state, sessionID)
return nil
default:
manager.onStateChanged(state, sessionID)
}
case <-cancelRequest:
return utils.ErrRequestCancelled
}
}
}
func (manager *connectionManager) consumeOpenvpnStates(stateChannel <-chan openvpn.State, sessionID session.SessionID) {
for state := range stateChannel {
manager.onStateChanged(state, sessionID)
}
manager.status = statusNotConnected()
log.Debug(managerLogPrefix, "State updater stopped")
}
func (manager *connectionManager) onStateChanged(state openvpn.State, sessionID session.SessionID) {
switch state {
case openvpn.ConnectedState:
manager.statsKeeper.MarkSessionStart()
manager.status = statusConnected(sessionID)
case openvpn.ExitingState:
manager.statsKeeper.MarkSessionEnd()
case openvpn.ReconnectingState:
manager.status = statusReconnecting()
}
}