This repository has been archived by the owner on Apr 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 29
/
client.go
482 lines (420 loc) · 13 KB
/
client.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
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
package harbor
import (
"context"
"crypto/tls"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/url"
"strings"
"github.com/dghubble/sling"
"github.com/flanksource/commons/console"
"github.com/flanksource/commons/logger"
"github.com/flanksource/commons/text"
"github.com/flanksource/karina/pkg/platform"
"github.com/flanksource/karina/pkg/types"
"github.com/flanksource/kommons/proxy"
"github.com/pkg/errors"
metav1 "k8s.io/apimachinery/pkg/apis/meta/v1"
)
const perPage = 50
type Client struct {
logger.Logger
sling *sling.Sling
client *http.Client
url string
base string
}
type IngressClient struct {
logger.Logger
sling *sling.Sling
client *http.Client
url string
host string
base string
}
// NewClient creates a new harbor client using proxy dialer
func NewClient(p *platform.Platform) (*Client, error) {
clientset, err := p.GetClientset()
if err != nil {
return nil, err
}
pods, err := clientset.CoreV1().Pods(Namespace).List(context.TODO(), metav1.ListOptions{
LabelSelector: "app=harbor,component=core",
})
if err != nil {
return nil, err
}
if len(pods.Items) == 0 {
return nil, fmt.Errorf("no running harbor-core pods")
}
dialer, _ := p.GetProxyDialer(proxy.Proxy{
Namespace: Namespace,
Kind: "pods",
ResourceName: pods.Items[0].Name,
Port: 8443,
})
tr := &http.Transport{
DialContext: dialer.DialContext,
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
var base string
if strings.HasPrefix(p.Harbor.Version, "v1") {
base = "/api"
} else {
base = "/api/v2.0"
}
client := &http.Client{Transport: tr}
return &Client{
Logger: p.Logger,
client: client,
base: base,
url: p.Harbor.URL,
sling: sling.New().Client(client).Base("https://harbor-core"+base).
SetBasicAuth("admin", p.Harbor.AdminPassword).
Set("accept", "application/json").
Set("content-type", "application/json"),
}, nil
}
// NewIngressClient creates a new harbor client using the harbor ingress
func NewIngressClient(p *platform.Platform) (*IngressClient, error) {
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
harborDomain := fmt.Sprintf("harbor.%s", p.Domain)
harborIP, err := dnsLookup(harborDomain)
if err != nil {
return nil, errors.Wrap(err, "failed to lookup harbor ingress IP")
}
harborURL := "https://" + harborIP
var base = "/api/v2.0"
client := &http.Client{Transport: tr}
return &IngressClient{
Logger: p.Logger,
client: client,
base: base,
url: p.Harbor.URL,
host: harborDomain,
sling: sling.New().Client(client).Base(harborURL+base).
Set("Host", harborDomain).
SetBasicAuth("admin", p.Harbor.AdminPassword).
Set("accept", "application/json").
Set("content-type", "application/json"),
}, nil
}
func (harbor *Client) GetStatus() (*Status, error) {
resp, err := harbor.client.Get("https://harbor-core" + harbor.base + "/health")
if err != nil {
return nil, err
}
status := Status{}
defer resp.Body.Close()
body, _ := ioutil.ReadAll(resp.Body)
if err := json.Unmarshal(body, &status); err != nil {
harbor.Errorf("Failed to unmarshall :%v", err)
}
return &status, nil
}
func (harbor *Client) ListReplicationPolicies() (policies []ReplicationPolicy, customErr error) {
resp, err := harbor.sling.New().
Get("replication/policies").
Receive(&policies, &customErr)
if err == nil {
err = customErr
}
defer resp.Body.Close()
return policies, err
}
func (harbor *Client) TriggerReplication(id int) (*Replication, error) {
req := Replication{PolicyID: id}
r, err := harbor.sling.New().
BodyJSON(&req).
Post("replication/executions").
Receive(nil, nil)
if err != nil {
return nil, fmt.Errorf("TriggerReplication: failed to trigger replication: %v", err)
}
defer r.Body.Close()
resp, err := harbor.sling.New().Get(r.Header["Location"][0]).Receive(&req, &req)
if err != nil {
return nil, err
}
defer resp.Body.Close()
return &req, nil
}
func (harbor *Client) UpdateSettings(settings types.HarborSettings) error {
data, _ := json.Marshal(settings)
harbor.Tracef("Harbor settings: \n%s\n", console.StripSecrets(string(data)))
harbor.Infof("Updating harbor using: %s \n", harbor.base)
r, err := harbor.sling.New().
Put(harbor.base+"/configurations").
BodyJSON(&settings).
Receive(nil, nil)
if err != nil {
return fmt.Errorf("failed to update harbor settings: %v", err)
}
defer r.Body.Close()
harbor.Debugf("Updated settings: %s:\n%+v", r.Status, text.SafeRead(r.Body))
return nil
}
func (harbor *Client) ListMembers(project string) ([]ProjectMember, error) {
return nil, nil
}
func (harbor *IngressClient) ListProjects() ([]Project, error) {
allProjects := []Project{}
page := 1
for {
projects := []Project{}
er := ErrorResponse{}
r, err := harbor.sling.New().
Get(fmt.Sprintf("https://%s/%s/projects?page=%d&per_page=%d", harbor.host, harbor.base, page, perPage)).
Set("Host", harbor.host).
Receive(&projects, &er)
if r != nil {
r.Body.Close()
}
if err != nil {
return nil, errors.Wrap(err, "failed to list projects")
}
if len(er.Errors) > 0 {
return nil, errors.Errorf("received error code from server: %s", er.String())
}
allProjects = append(allProjects, projects...)
if len(projects) == 0 {
break
}
page++
}
return allProjects, nil
}
func (harbor *IngressClient) ListImages(project string) ([]Image, error) {
allImages := []Image{}
page := 1
for {
images := []Image{}
er := ErrorResponse{}
r, err := harbor.sling.New().
Get(fmt.Sprintf("https://%s/%s/projects/%s/repositories?page=%d&perPage=%d", harbor.host, harbor.base, project, page, perPage)).
Set("Host", harbor.host).
Receive(&images, &er)
if r != nil {
r.Body.Close()
}
if err != nil {
return nil, errors.Wrap(err, "failed to list images")
}
if len(er.Errors) > 0 {
return nil, errors.Errorf("received error code from server: %s", er.String())
}
allImages = append(allImages, images...)
if len(images) == 0 {
break
}
page++
}
return allImages, nil
}
func (harbor *IngressClient) ListArtifacts(project string, image string) ([]Artifact, error) {
allArtifacts := []Artifact{}
page := 1
imageEncoded := url.QueryEscape(image)
for {
artifacts := []Artifact{}
er := ErrorResponse{}
r, err := harbor.sling.New().
Get(fmt.Sprintf("https://%s/%s/projects/%s/repositories/%s/artifacts?page=%d&per_page=%d", harbor.host, harbor.base, project, imageEncoded, page, perPage)).
Set("Host", harbor.host).
Receive(&artifacts, &er)
if r != nil {
r.Body.Close()
}
if err != nil {
return nil, errors.Wrap(err, "failed to list tags")
}
if len(er.Errors) > 0 {
return nil, errors.Errorf("received error code from server: %s", er.String())
}
allArtifacts = append(allArtifacts, artifacts...)
if len(artifacts) == 0 {
break
}
page++
}
return allArtifacts, nil
}
func (harbor *IngressClient) GetManifest(project, image, tag string) (*Manifest, error) {
manifest := &Manifest{}
er := ErrorResponse{}
// fmt.Printf("url: https://%s/v2/%s/%s/manifests/%s\n", harbor.host, project, image, tag)
r, err := harbor.sling.New().
Get(fmt.Sprintf("https://%s/v2/%s/%s/manifests/%s", harbor.host, project, image, tag)).
Set("Host", harbor.host).
Receive(&manifest, &er)
if r != nil {
r.Body.Close()
}
if err != nil {
return nil, errors.Wrap(err, "failed to get manifest")
}
if len(er.Errors) > 0 {
return nil, errors.Errorf("received error code from server: %s", er.String())
}
return manifest, nil
}
func (harbor *IngressClient) DeleteTag(tag Tag) error {
// response := map[string]interface{}{}
er := ErrorResponse{}
r, err := harbor.sling.New().
Delete(fmt.Sprintf("https://%s/v2/%s/%s/manifests/%s", harbor.host, tag.ProjectName, tag.RepositoryName, tag.Digest)).
Set("Host", "harbor.host").
Receive(nil, &er)
if r != nil {
r.Body.Close()
}
if err != nil {
return errors.Wrap(err, "failed to delete manifest")
}
if len(er.Errors) > 0 {
return errors.Errorf("received error code from server: %s", er.String())
}
// fmt.Printf("Response: %v", response)
return nil
}
type Project struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
}
type Replication struct {
ID int `json:"id,omitempty"`
PolicyID int `json:"policy_id,omitempty"`
Status string `json:"status,omitempty"`
StatusText string `json:"status_text,omitempty"`
Trigger string `json:"trigger,omitempty"`
Total int `json:"total,omitempty"`
Failed int `json:"failed,omitempty"`
Succeed int `json:"succeed,omitempty"`
InProgress int `json:"in_progress,omitempty"`
Stopped int `json:"stopped,omitempty"`
StartTime string `json:"start_time,omitempty"`
EndTime string `json:"end_time,omitempty"`
}
type ReplicationRegistry struct {
ID int `json:"id,omitempty"`
URL string `json:"url,omitempty"`
Name string `json:"name,omitempty"`
Credential struct {
Type string `json:"type,omitempty"`
AccessKey string `json:"access_key,omitempty"`
AccessSecret string `json:"access_secret,omitempty"`
} `json:"credential,omitempty"`
Type string `json:"type,omitempty"`
Insecure bool `json:"insecure,omitempty"`
Description string `json:"description,omitempty"`
Status string `json:"status,omitempty"`
CreationTime string `json:"creation_time,omitempty"`
UpdateTime string `json:"update_time,omitempty"`
}
type ReplicationPolicy struct {
ID int `json:"id,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
SrcRegistry ReplicationRegistry `json:"src_registry,omitempty"`
DestRegistry ReplicationRegistry `json:"dest_registry,omitempty"`
DestNamespace string `json:"dest_namespace,omitempty"`
Trigger ReplicationTrigger `json:"trigger,omitempty"`
Filters []ReplicationFilter `json:"filters,omitempty"`
Deletion bool `json:"deletion,omitempty"`
Override bool `json:"override,omitempty"`
Enabled bool `json:"enabled,omitempty"`
CreationTime string `json:"creation_time,omitempty"`
UpdateTime string `json:"update_time,omitempty"`
}
type ReplicationTrigger struct {
Type string `json:"type,omitempty"`
TriggerSettings struct {
Cron string `json:"cron,omitempty"`
} `json:"trigger_settings,omitempty"`
}
type ReplicationFilter struct {
Type string `json:"type,omitempty"`
Value string `json:"value,omitempty"`
}
type ProjectMember struct {
ID int `json:"id,omitempty"`
ProjectID int `json:"project_id,omitempty"`
EntityName string `json:"entity_name,omitempty"`
RoleName string `json:"role_name,omitempty"`
RoleID int `json:"role_id,omitempty"`
EntityID int `json:"entity_id,omitempty"`
EntityType string `json:"entity_type,omitempty"`
}
type Status struct {
Status string `json:"status"`
Components []struct {
Name string `json:"name"`
Status string `json:"status"`
} `json:"components"`
}
type Image struct {
ID int `json:"id,omitempty"`
ProjectID int `json:"project_id,omitempty"`
Name string `json:"name,omitempty"`
Description string `json:"description,omitempty"`
ArtifactCount int `json:"artifact_count,omitempty"`
PullCount int `json:"pull_count,omitempty"`
ProjectName string `json:"-"`
}
type Artifact struct {
ID int `json:"id,omitempty"`
Type string `json:"type,omitempty"`
MediaType string `json:"media_type,omitempty"`
ManifestMediaType string `json:"manifest_media_type,omitempty"`
ProjectID int `json:"project_id,omitempty"`
RepositoryID int `json:"repository_id,omitempty"`
Digest string `json:"digest,omitempty"`
Size int `json:"size,omitempty"`
Tags []ArtifactTag `json:"tags"`
}
type ArtifactTag struct {
Name string `json:"name"`
}
type Tag struct {
Name string `json:"-" yaml:"tag"`
ProjectName string `json:"-" yaml:"project"`
RepositoryName string `json:"-" yaml:"repository"`
Digest string `json:"-" yaml:"digest"`
}
type Manifest struct {
SchemaVersion int `json:"schemaVersion"`
MediaType string `json:"mediaType"`
Config ManifestLayer `json:"config"`
Layers []ManifestLayer `json:"layers"`
}
type ManifestLayer struct {
MediaType string `json:"mediaType"`
Size int `json:"size"`
Digest string `json:"digest"`
}
type ErrorResponse struct {
Errors []Error `json:"errors"`
}
func (e *ErrorResponse) String() string {
j, _ := json.Marshal(e)
return string(j)
}
type Error struct {
Code string `json:"code"`
Message string `json:"message"`
}
func dnsLookup(hostname string) (string, error) {
addrs, err := net.LookupHost(hostname)
if err != nil {
return "", errors.Wrapf(err, "failed to lookup %s", hostname)
}
if len(addrs) == 0 {
return "", errors.Errorf("lookup %s did not return any address", hostname)
}
return addrs[0], nil
}