-
Notifications
You must be signed in to change notification settings - Fork 88
/
api.go
240 lines (194 loc) · 6.43 KB
/
api.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
package replicatedapp
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
"github.com/pkg/errors"
apptypes "github.com/replicatedhq/kots/pkg/app/types"
"github.com/replicatedhq/kots/pkg/logger"
"github.com/replicatedhq/kots/pkg/persistence"
"github.com/replicatedhq/kots/pkg/reporting"
"github.com/replicatedhq/kots/pkg/store"
"github.com/replicatedhq/kots/pkg/util"
kotsv1beta1 "github.com/replicatedhq/kotskinds/apis/kots/v1beta1"
"github.com/replicatedhq/kotskinds/client/kotsclientset/scheme"
)
type ApplicationMetadata struct {
Manifest []byte
Branding []byte
}
const DefaultMetadata = `apiVersion: kots.io/v1beta1
kind: Application
metadata:
name: "default-application"
spec:
title: "the application"
icon: https://cdn2.iconfinder.com/data/icons/mixd/512/16_kubernetes-512.png
releaseNotes: |
release notes`
type LicenseData struct {
LicenseBytes []byte
License *kotsv1beta1.License
}
func GetLatestLicense(license *kotsv1beta1.License) (*LicenseData, error) {
url := fmt.Sprintf("%s/license/%s", license.Spec.Endpoint, license.Spec.AppSlug)
licenseData, err := getLicenseFromAPI(url, license.Spec.LicenseID)
if err != nil {
return nil, errors.Wrap(err, "failed to get license from api")
}
return licenseData, nil
}
func getAppIdFromLicenseId(s store.Store, licenseID string) (string, error) {
apps, err := s.ListInstalledApps()
if err != nil {
return "", errors.Wrap(err, "failed to get all app licenses")
}
for _, a := range apps {
l, err := s.GetLatestLicenseForApp(a.ID)
if err != nil {
return "", errors.Wrap(err, "failed to get latest license for app")
}
if l.Spec.LicenseID == licenseID {
return a.ID, nil
}
}
return "", nil
}
func getLicenseFromAPI(url string, licenseID string) (*LicenseData, error) {
req, err := util.NewRequest("GET", url, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to call newrequest")
}
req.SetBasicAuth(licenseID, licenseID)
if persistence.IsInitialized() {
appId, err := getAppIdFromLicenseId(store.GetStore(), licenseID)
if err != nil {
return nil, errors.Wrap(err, "failed to get license by id")
}
if appId != "" {
reportingInfo := reporting.GetReportingInfo(appId)
reporting.InjectReportingInfoHeaders(req, reportingInfo)
}
}
resp, err := http.DefaultClient.Do(req)
if err != nil {
return nil, errors.Wrap(err, "failed to execute get request")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to load response")
}
if resp.StatusCode >= 400 {
return nil, errors.Errorf("unexpected result from get request: %d, data: %s", resp.StatusCode, body)
}
decode := scheme.Codecs.UniversalDeserializer().Decode
obj, _, err := decode(body, nil, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to decode latest license data")
}
data := &LicenseData{
LicenseBytes: body,
License: obj.(*kotsv1beta1.License),
}
return data, nil
}
// GetApplicationMetadata will return any available application yaml from
// the upstream. If there is no application.yaml, it will return
// a placeholder one
func GetApplicationMetadata(upstream *url.URL, versionLabel string) (*ApplicationMetadata, error) {
host := util.GetReplicatedAPIEndpoint()
manifest, err := getApplicationMetadataFromHost(host, "metadata", upstream, versionLabel)
if err != nil {
return nil, errors.Wrapf(err, "failed to get metadata from %s", host)
}
if len(manifest) == 0 {
manifest = []byte(DefaultMetadata)
}
branding, err := getApplicationMetadataFromHost(host, "branding", upstream, versionLabel)
if err != nil {
return nil, errors.Wrapf(err, "failed to get branding from %s", host)
}
return &ApplicationMetadata{
Manifest: manifest,
Branding: branding,
}, nil
}
func getApplicationMetadataFromHost(host string, endpoint string, upstream *url.URL, versionLabel string) ([]byte, error) {
r, err := ParseReplicatedURL(upstream)
if err != nil {
return nil, errors.Wrap(err, "failed to parse replicated upstream")
}
if r.VersionLabel != nil && *r.VersionLabel != "" && versionLabel != "" && *r.VersionLabel != versionLabel {
return nil, errors.Errorf("version label in upstream (%q) does not match version label in parameter (%q)", *r.VersionLabel, versionLabel)
}
getUrl := fmt.Sprintf("%s/%s/%s", host, endpoint, url.PathEscape(r.AppSlug))
if r.Channel != nil {
getUrl = fmt.Sprintf("%s/%s", getUrl, url.PathEscape(*r.Channel))
}
v := url.Values{}
if r.VersionLabel != nil && *r.VersionLabel != "" {
v.Set("versionLabel", *r.VersionLabel)
} else if versionLabel != "" {
v.Set("versionLabel", versionLabel)
}
getUrl = fmt.Sprintf("%s?%s", getUrl, v.Encode())
getReq, err := util.NewRequest("GET", getUrl, nil)
if err != nil {
return nil, errors.Wrap(err, "failed to call newrequest")
}
getResp, err := http.DefaultClient.Do(getReq)
if err != nil {
return nil, errors.Wrap(err, "failed to execute get request")
}
defer getResp.Body.Close()
if getResp.StatusCode == 404 {
// no metadata is not an error
return nil, nil
}
if getResp.StatusCode >= 400 {
return nil, errors.Errorf("unexpected result from get request: %d", getResp.StatusCode)
}
respBody, err := ioutil.ReadAll(getResp.Body)
if err != nil {
return nil, errors.Wrap(err, "failed to read response body")
}
return respBody, nil
}
func SendCustomAppMetricsData(license *kotsv1beta1.License, app *apptypes.App, data map[string]interface{}) error {
url := fmt.Sprintf("%s/application/custom-metrics", license.Spec.Endpoint)
payload := struct {
Data map[string]interface{} `json:"data"`
}{
Data: data,
}
reqBody, err := json.Marshal(payload)
if err != nil {
return errors.Wrap(err, "marshal data")
}
req, err := util.NewRequest("POST", url, bytes.NewBuffer(reqBody))
if err != nil {
return errors.Wrap(err, "call newrequest")
}
req.Header.Set("Content-Type", "application/json")
reportingInfo := reporting.GetReportingInfo(app.ID)
reporting.InjectReportingInfoHeaders(req, reportingInfo)
req.SetBasicAuth(license.Spec.LicenseID, license.Spec.LicenseID)
resp, err := http.DefaultClient.Do(req)
if err != nil {
return errors.Wrap(err, "execute request")
}
defer resp.Body.Close()
if resp.StatusCode >= 400 {
respBody, err := io.ReadAll(resp.Body)
if err != nil {
logger.Warnf("failed to read metrics response body: %v", err)
}
return errors.Errorf("unexpected result from post request: %d, data: %s", resp.StatusCode, respBody)
}
return nil
}