-
Notifications
You must be signed in to change notification settings - Fork 2
/
api_server.go
211 lines (184 loc) · 6.55 KB
/
api_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
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
package backend
import (
"encoding/json"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"path/filepath"
"time"
"github.com/stellar/go/clients/horizonclient"
"github.com/stellar/kelp/plugins"
"github.com/stellar/kelp/support/kelpos"
)
// APIServer is an instance of the API service
type APIServer struct {
kelpBinPath *kelpos.OSPath
botConfigsPath *kelpos.OSPath
botLogsPath *kelpos.OSPath
kos *kelpos.KelpOS
horizonTestnetURI string
horizonPubnetURI string
ccxtRestUrl string
apiTestNet *horizonclient.Client
apiPubNet *horizonclient.Client
noHeaders bool
quitFn func()
metricsTracker *plugins.MetricsTracker
cachedOptionsMetadata metadata
}
// MakeAPIServer is a factory method
func MakeAPIServer(
kos *kelpos.KelpOS,
botConfigsPath *kelpos.OSPath,
botLogsPath *kelpos.OSPath,
horizonTestnetURI string,
apiTestNet *horizonclient.Client,
horizonPubnetURI string,
apiPubNet *horizonclient.Client,
ccxtRestUrl string,
noHeaders bool,
quitFn func(),
metricsTracker *plugins.MetricsTracker,
) (*APIServer, error) {
kelpBinPath := kos.GetBinDir().Join(filepath.Base(os.Args[0]))
optionsMetadata, e := loadOptionsMetadata()
if e != nil {
return nil, fmt.Errorf("error while loading options metadata when making APIServer: %s", e)
}
return &APIServer{
kelpBinPath: kelpBinPath,
botConfigsPath: botConfigsPath,
botLogsPath: botLogsPath,
kos: kos,
horizonTestnetURI: horizonTestnetURI,
horizonPubnetURI: horizonPubnetURI,
ccxtRestUrl: ccxtRestUrl,
apiTestNet: apiTestNet,
apiPubNet: apiPubNet,
noHeaders: noHeaders,
cachedOptionsMetadata: optionsMetadata,
quitFn: quitFn,
metricsTracker: metricsTracker,
}, nil
}
func (s *APIServer) parseBotName(r *http.Request) (string, error) {
botNameBytes, e := ioutil.ReadAll(r.Body)
if e != nil {
return "", fmt.Errorf("error when reading request input: %s\n", e)
}
return string(botNameBytes), nil
}
func (s *APIServer) writeError(w http.ResponseWriter, message string) {
log.Print(message)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte(message))
}
// ErrorResponse represents an error (deprecated)
type ErrorResponse struct {
Error string `json:"error"`
}
// KelpError represents an error
type KelpError struct {
ObjectType errorType `json:"object_type"`
ObjectName string `json:"object_name"`
Date time.Time `json:"date"`
Level errorLevel `json:"level"`
Message string `json:"message"`
}
// String is the Stringer method
func (ke *KelpError) String() string {
return fmt.Sprintf("KelpError[objectType=%s, objectName=%s, date=%s, level=%s, message=%s]", ke.ObjectType, ke.ObjectName, ke.Date.Format("20060102T150405MST"), ke.Level, ke.Message)
}
// KelpErrorResponseWrapper is the outer object that contains the Kelp Error
type KelpErrorResponseWrapper struct {
KelpError KelpError `json:"kelp_error"`
}
func makeKelpErrorResponseWrapper(
objectType errorType,
objectName string,
date time.Time,
level errorLevel,
message string,
) KelpErrorResponseWrapper {
return KelpErrorResponseWrapper{
KelpError: KelpError{
ObjectType: objectType,
ObjectName: objectName,
Date: date,
Level: level,
Message: message,
},
}
}
// String is the Stringer method
func (kerw *KelpErrorResponseWrapper) String() string {
return fmt.Sprintf("KelpErrorResponseWrapper[kelp_error=%s]", kerw.KelpError)
}
func (s *APIServer) writeErrorJson(w http.ResponseWriter, message string) {
log.Println(message)
w.WriteHeader(http.StatusInternalServerError)
marshalledJson, e := json.MarshalIndent(ErrorResponse{Error: message}, "", " ")
if e != nil {
log.Printf("unable to marshal json with indentation: %s\n", e)
w.Write([]byte(fmt.Sprintf("unable to marshal json with indentation: %s\n", e)))
return
}
w.Write(marshalledJson)
}
func (s *APIServer) writeKelpError(w http.ResponseWriter, kerw KelpErrorResponseWrapper) {
w.WriteHeader(http.StatusInternalServerError)
log.Printf("writing error: %s\n", kerw)
marshalledJSON, e := json.MarshalIndent(kerw, "", " ")
if e != nil {
log.Printf("unable to marshal json with indentation: %s\n", e)
w.Write([]byte(fmt.Sprintf("unable to marshal json with indentation: %s\n", e)))
return
}
w.Write(marshalledJSON)
}
func (s *APIServer) writeJson(w http.ResponseWriter, v interface{}) {
s.writeJsonWithLog(w, v, true)
}
func (s *APIServer) writeJsonWithLog(w http.ResponseWriter, v interface{}, doLog bool) {
marshalledJson, e := json.MarshalIndent(v, "", " ")
if e != nil {
s.writeErrorJson(w, fmt.Sprintf("unable to marshal json with indentation: %s", e))
return
}
if doLog {
log.Printf("responseJson: %s\n", string(marshalledJson))
}
w.WriteHeader(http.StatusOK)
w.Write(marshalledJson)
}
func (s *APIServer) runKelpCommandBlocking(namespace string, cmd string) ([]byte, error) {
// There is a weird issue on windows where the absolute path for the kelp binary does not work on the release GUI
// version because of the unzipped directory name but it will work on the released cli version or if we change the
// name of the folder in which the GUI version is unzipped.
// To avoid these issues we only invoke with the binary name as opposed to the absolute path that contains the
// directory name. see start_bot.go for some experimentation with absolute and relative paths
cmdString := fmt.Sprintf("%s %s", s.kelpBinPath.Unix(), cmd)
return s.kos.Blocking(namespace, cmdString)
}
func (s *APIServer) runKelpCommandBackground(namespace string, cmd string) (*kelpos.Process, error) {
// There is a weird issue on windows where the absolute path for the kelp binary does not work on the release GUI
// version because of the unzipped directory name but it will work on the released cli version or if we change the
// name of the folder in which the GUI version is unzipped.
// To avoid these issues we only invoke with the binary name as opposed to the absolute path that contains the
// directory name. see start_bot.go for some experimentation with absolute and relative paths
cmdString := fmt.Sprintf("%s %s", s.kelpBinPath.Unix(), cmd)
return s.kos.Background(namespace, cmdString)
}
func (s *APIServer) setupOpsDirectory() error {
e := s.kos.Mkdir(s.botConfigsPath)
if e != nil {
return fmt.Errorf("error setting up configs directory (%s): %s\n", s.botConfigsPath, e)
}
e = s.kos.Mkdir(s.botLogsPath)
if e != nil {
return fmt.Errorf("error setting up logs directory (%s): %s\n", s.botLogsPath, e)
}
return nil
}