/
tools.go
194 lines (177 loc) · 6.52 KB
/
tools.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
// Copyright 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package apiserver
import (
"crypto/sha256"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net/http"
"os"
"path"
"strings"
"github.com/wallyworld/core/environs"
"github.com/wallyworld/core/environs/filestorage"
"github.com/wallyworld/core/environs/sync"
envtools "github.com/wallyworld/core/environs/tools"
"github.com/wallyworld/core/state/api/params"
"github.com/wallyworld/core/state/apiserver/common"
"github.com/wallyworld/core/tools"
"github.com/wallyworld/core/version"
)
// toolsHandler handles tool upload through HTTPS in the API server.
type toolsHandler struct {
httpHandler
}
func (h *toolsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
if err := h.authenticate(r); err != nil {
h.authError(w, h)
return
}
switch r.Method {
case "POST":
// Add a local charm to the store provider.
// Requires a "series" query specifying the series to use for the charm.
agentTools, disableSSLHostnameVerification, err := h.processPost(r)
if err != nil {
h.sendError(w, http.StatusBadRequest, err.Error())
return
}
h.sendJSON(w, http.StatusOK, ¶ms.ToolsResult{
Tools: agentTools,
DisableSSLHostnameVerification: disableSSLHostnameVerification,
})
default:
h.sendError(w, http.StatusMethodNotAllowed, fmt.Sprintf("unsupported method: %q", r.Method))
}
}
// sendJSON sends a JSON-encoded response to the client.
func (h *toolsHandler) sendJSON(w http.ResponseWriter, statusCode int, response *params.ToolsResult) error {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(statusCode)
body, err := json.Marshal(response)
if err != nil {
return err
}
w.Write(body)
return nil
}
// sendError sends a JSON-encoded error response.
func (h *toolsHandler) sendError(w http.ResponseWriter, statusCode int, message string) error {
err := common.ServerError(fmt.Errorf(message))
return h.sendJSON(w, statusCode, ¶ms.ToolsResult{Error: err})
}
// processPost handles a charm upload POST request after authentication.
func (h *toolsHandler) processPost(r *http.Request) (*tools.Tools, bool, error) {
query := r.URL.Query()
binaryVersionParam := query.Get("binaryVersion")
if binaryVersionParam == "" {
return nil, false, fmt.Errorf("expected binaryVersion argument")
}
toolsVersion, err := version.ParseBinary(binaryVersionParam)
if err != nil {
return nil, false, fmt.Errorf("invalid tools version %q: %v", binaryVersionParam, err)
}
var fakeSeries []string
seriesParam := query.Get("series")
if seriesParam != "" {
fakeSeries = strings.Split(seriesParam, ",")
}
logger.Debugf("request to upload tools %s for series %q", toolsVersion, seriesParam)
// Make sure the content type is x-tar-gz.
contentType := r.Header.Get("Content-Type")
if contentType != "application/x-tar-gz" {
return nil, false, fmt.Errorf("expected Content-Type: application/x-tar-gz, got: %v", contentType)
}
return h.handleUpload(r.Body, toolsVersion, fakeSeries...)
}
// handleUpload uploads the tools data from the reader to env storage as the specified version.
func (h *toolsHandler) handleUpload(r io.Reader, toolsVersion version.Binary, fakeSeries ...string) (*tools.Tools, bool, error) {
// Set up a local temp directory for the tools tarball.
tmpDir, err := ioutil.TempDir("", "juju-upload-tools-")
if err != nil {
return nil, false, fmt.Errorf("cannot create temp dir: %v", err)
}
defer os.RemoveAll(tmpDir)
toolsFilename := envtools.StorageName(toolsVersion)
toolsDir := path.Dir(toolsFilename)
fullToolsDir := path.Join(tmpDir, toolsDir)
err = os.MkdirAll(fullToolsDir, 0700)
if err != nil {
return nil, false, fmt.Errorf("cannot create tools dir %s: %v", toolsDir, err)
}
// Read the tools tarball from the request, calculating the sha256 along the way.
fullToolsFilename := path.Join(tmpDir, toolsFilename)
toolsFile, err := os.Create(fullToolsFilename)
if err != nil {
return nil, false, fmt.Errorf("cannot create tools file %s: %v", fullToolsFilename, err)
}
logger.Debugf("saving uploaded tools to temp file: %s", fullToolsFilename)
defer toolsFile.Close()
sha256hash := sha256.New()
var size int64
if size, err = io.Copy(toolsFile, io.TeeReader(r, sha256hash)); err != nil {
return nil, false, fmt.Errorf("error processing file upload: %v", err)
}
if size == 0 {
return nil, false, fmt.Errorf("no tools uploaded")
}
// TODO(wallyworld): check integrity of tools tarball.
// Create a tools record and sync to storage.
uploadedTools := &tools.Tools{
Version: toolsVersion,
Size: size,
SHA256: fmt.Sprintf("%x", sha256hash.Sum(nil)),
}
logger.Debugf("about to upload tools %+v to storage", uploadedTools)
return h.uploadToStorage(uploadedTools, tmpDir, toolsFilename, fakeSeries...)
}
// uploadToStorage uploads the tools from the specified directory to environment storage.
func (h *toolsHandler) uploadToStorage(uploadedTools *tools.Tools, toolsDir,
toolsFilename string, fakeSeries ...string) (*tools.Tools, bool, error) {
// SyncTools requires simplestreams metadata to find the tools to upload.
stor, err := filestorage.NewFileStorageWriter(toolsDir)
if err != nil {
return nil, false, fmt.Errorf("cannot create metadata storage: %v", err)
}
// Generate metadata for the fake series. The URL for each fake series
// record points to the same tools tarball.
allToolsMetadata := []*tools.Tools{uploadedTools}
for _, series := range fakeSeries {
vers := uploadedTools.Version
vers.Series = series
allToolsMetadata = append(allToolsMetadata, &tools.Tools{
Version: vers,
URL: uploadedTools.URL,
Size: uploadedTools.Size,
SHA256: uploadedTools.SHA256,
})
}
err = envtools.MergeAndWriteMetadata(stor, allToolsMetadata, false)
if err != nil {
return nil, false, fmt.Errorf("cannot get environment config: %v", err)
}
// Create the environment so we can get the storage to which we upload the tools.
envConfig, err := h.state.EnvironConfig()
if err != nil {
return nil, false, fmt.Errorf("cannot get environment config: %v", err)
}
env, err := environs.New(envConfig)
if err != nil {
return nil, false, fmt.Errorf("cannot access environment: %v", err)
}
// Now perform the upload.
builtTools := &sync.BuiltTools{
Version: uploadedTools.Version,
Dir: toolsDir,
StorageName: toolsFilename,
Size: uploadedTools.Size,
Sha256Hash: uploadedTools.SHA256,
}
uploadedTools, err = sync.SyncBuiltTools(env.Storage(), builtTools, fakeSeries...)
if err != nil {
return nil, false, err
}
return uploadedTools, !envConfig.SSLHostnameVerification(), nil
}