14287: Refactor controller to use strong types in API handlers.
[arvados.git] / lib / controller / rpc / conn.go
1 // Copyright (C) The Arvados Authors. All rights reserved.
2 //
3 // SPDX-License-Identifier: AGPL-3.0
4
5 package rpc
6
7 import (
8         "context"
9         "crypto/tls"
10         "encoding/json"
11         "fmt"
12         "io"
13         "net"
14         "net/http"
15         "net/url"
16         "strings"
17         "time"
18
19         "git.curoverse.com/arvados.git/sdk/go/arvados"
20 )
21
22 type contextKey string
23
24 const ContextKeyCredentials contextKey = "credentials"
25
26 type TokenProvider func(context.Context) ([]string, error)
27
28 type Conn struct {
29         clusterID     string
30         httpClient    http.Client
31         baseURL       url.URL
32         tokenProvider TokenProvider
33 }
34
35 func NewConn(clusterID string, url *url.URL, insecure bool, tp TokenProvider) *Conn {
36         transport := http.DefaultTransport
37         if insecure {
38                 // It's not safe to copy *http.DefaultTransport
39                 // because it has a mutex (which might be locked)
40                 // protecting a private map (which might not be nil).
41                 // So we build our own, using the Go 1.12 default
42                 // values, ignoring any changes the application has
43                 // made to http.DefaultTransport.
44                 transport = &http.Transport{
45                         DialContext: (&net.Dialer{
46                                 Timeout:   30 * time.Second,
47                                 KeepAlive: 30 * time.Second,
48                                 DualStack: true,
49                         }).DialContext,
50                         MaxIdleConns:          100,
51                         IdleConnTimeout:       90 * time.Second,
52                         TLSHandshakeTimeout:   10 * time.Second,
53                         ExpectContinueTimeout: 1 * time.Second,
54                         TLSClientConfig:       &tls.Config{InsecureSkipVerify: true},
55                 }
56         }
57         return &Conn{
58                 clusterID:     clusterID,
59                 httpClient:    http.Client{Transport: transport},
60                 baseURL:       *url,
61                 tokenProvider: tp,
62         }
63 }
64
65 func (conn *Conn) requestAndDecode(ctx context.Context, dst interface{}, ep arvados.APIEndpoint, body io.Reader, opts interface{}) error {
66         aClient := arvados.Client{
67                 Client:  &conn.httpClient,
68                 Scheme:  conn.baseURL.Scheme,
69                 APIHost: conn.baseURL.Host,
70         }
71         tokens, err := conn.tokenProvider(ctx)
72         if err != nil {
73                 return err
74         } else if len(tokens) == 0 {
75                 return fmt.Errorf("bug: token provider returned no tokens and no error")
76         }
77         ctx = context.WithValue(ctx, "Authorization", "Bearer "+tokens[0])
78
79         // Encode opts to JSON and decode from there to a
80         // map[string]interface{}, so we can munge the query params
81         // using the JSON key names specified by opts' struct tags.
82         j, err := json.Marshal(opts)
83         if err != nil {
84                 return fmt.Errorf("%T: requestAndDecode: Marshal opts: %s", conn, err)
85         }
86         var params map[string]interface{}
87         err = json.Unmarshal(j, &params)
88         if err != nil {
89                 return fmt.Errorf("%T: requestAndDecode: Unmarshal opts: %s", conn, err)
90         }
91         if attrs, ok := params["attrs"]; ok && ep.AttrsKey != "" {
92                 params[ep.AttrsKey] = attrs
93                 delete(params, "attrs")
94         }
95         if limit, ok := params["limit"].(float64); ok && limit < 0 {
96                 // Negative limit means "not specified" here, but some
97                 // servers/versions do not accept that, so we need to
98                 // remove it entirely.
99                 delete(params, "limit")
100         }
101         path := ep.Path
102         if strings.Contains(ep.Path, "/:uuid") {
103                 uuid, _ := params["uuid"].(string)
104                 path = strings.Replace(path, "/:uuid", "/"+uuid, 1)
105                 delete(params, "uuid")
106         }
107         return aClient.RequestAndDecodeContext(ctx, dst, ep.Method, path, body, params)
108 }
109
110 func (conn *Conn) CollectionCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Collection, error) {
111         ep := arvados.EndpointCollectionCreate
112         var resp arvados.Collection
113         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
114         return resp, err
115 }
116
117 func (conn *Conn) CollectionUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Collection, error) {
118         ep := arvados.EndpointCollectionUpdate
119         var resp arvados.Collection
120         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
121         return resp, err
122 }
123
124 func (conn *Conn) CollectionGet(ctx context.Context, options arvados.GetOptions) (arvados.Collection, error) {
125         ep := arvados.EndpointCollectionGet
126         var resp arvados.Collection
127         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
128         return resp, err
129 }
130
131 func (conn *Conn) CollectionList(ctx context.Context, options arvados.ListOptions) (arvados.CollectionList, error) {
132         ep := arvados.EndpointCollectionList
133         var resp arvados.CollectionList
134         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
135         return resp, err
136 }
137
138 func (conn *Conn) CollectionDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Collection, error) {
139         ep := arvados.EndpointCollectionDelete
140         var resp arvados.Collection
141         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
142         return resp, err
143 }
144
145 func (conn *Conn) ContainerCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Container, error) {
146         ep := arvados.EndpointContainerCreate
147         var resp arvados.Container
148         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
149         return resp, err
150 }
151
152 func (conn *Conn) ContainerUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Container, error) {
153         ep := arvados.EndpointContainerUpdate
154         var resp arvados.Container
155         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
156         return resp, err
157 }
158
159 func (conn *Conn) ContainerGet(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
160         ep := arvados.EndpointContainerGet
161         var resp arvados.Container
162         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
163         return resp, err
164 }
165
166 func (conn *Conn) ContainerList(ctx context.Context, options arvados.ListOptions) (arvados.ContainerList, error) {
167         ep := arvados.EndpointContainerList
168         var resp arvados.ContainerList
169         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
170         return resp, err
171 }
172
173 func (conn *Conn) ContainerDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Container, error) {
174         ep := arvados.EndpointContainerDelete
175         var resp arvados.Container
176         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
177         return resp, err
178 }
179
180 func (conn *Conn) ContainerLock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
181         ep := arvados.EndpointContainerLock
182         var resp arvados.Container
183         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
184         return resp, err
185 }
186
187 func (conn *Conn) ContainerUnlock(ctx context.Context, options arvados.GetOptions) (arvados.Container, error) {
188         ep := arvados.EndpointContainerUnlock
189         var resp arvados.Container
190         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
191         return resp, err
192 }
193
194 func (conn *Conn) SpecimenCreate(ctx context.Context, options arvados.CreateOptions) (arvados.Specimen, error) {
195         ep := arvados.EndpointSpecimenCreate
196         var resp arvados.Specimen
197         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
198         return resp, err
199 }
200
201 func (conn *Conn) SpecimenUpdate(ctx context.Context, options arvados.UpdateOptions) (arvados.Specimen, error) {
202         ep := arvados.EndpointSpecimenUpdate
203         var resp arvados.Specimen
204         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
205         return resp, err
206 }
207
208 func (conn *Conn) SpecimenGet(ctx context.Context, options arvados.GetOptions) (arvados.Specimen, error) {
209         ep := arvados.EndpointSpecimenGet
210         var resp arvados.Specimen
211         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
212         return resp, err
213 }
214
215 func (conn *Conn) SpecimenList(ctx context.Context, options arvados.ListOptions) (arvados.SpecimenList, error) {
216         ep := arvados.EndpointSpecimenList
217         var resp arvados.SpecimenList
218         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
219         return resp, err
220 }
221
222 func (conn *Conn) SpecimenDelete(ctx context.Context, options arvados.DeleteOptions) (arvados.Specimen, error) {
223         ep := arvados.EndpointSpecimenDelete
224         var resp arvados.Specimen
225         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
226         return resp, err
227 }
228
229 func (conn *Conn) APIClientAuthorizationCurrent(ctx context.Context, options arvados.GetOptions) (arvados.APIClientAuthorization, error) {
230         ep := arvados.EndpointAPIClientAuthorizationCurrent
231         var resp arvados.APIClientAuthorization
232         err := conn.requestAndDecode(ctx, &resp, ep, nil, options)
233         return resp, err
234 }