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
|
// -*- Mode: Go; indent-tabs-mode: t -*-
/*
* Copyright (C) 2019 Canonical Ltd
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 as
* published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
*/
package client
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"mime/multipart"
"net/textproto"
"net/url"
"os"
"path/filepath"
"golang.org/x/xerrors"
"github.com/snapcore/snapd/asserts"
)
type remodelData struct {
NewModel string `json:"new-model"`
Offline bool `json:"offline,omitempty"`
}
// RemodelOpts defines options to be used when remodeling the system.
type RemodelOpts struct {
// Offline indicates whether the remodel should be done offline. If true,
// the remodel will be attempted to be done without contacting the store.
Offline bool
}
// Remodel tries to remodel the system with the given assertion data
func (client *Client) Remodel(b []byte, opts RemodelOpts) (changeID string, err error) {
data, err := json.Marshal(&remodelData{
NewModel: string(b),
Offline: opts.Offline,
})
if err != nil {
return "", fmt.Errorf("cannot marshal remodel data: %v", err)
}
headers := map[string]string{
"Content-Type": "application/json",
}
return client.doAsync("POST", "/v2/model", nil, headers, bytes.NewReader(data))
}
// RemodelWithLocalSnaps tries to remodel the system with the given model
// assertion and local snaps and assertion files. Remodeling using this method
// will ensure that snapd does not contact the store.
func (client *Client) RemodelWithLocalSnaps(
model []byte, snapPaths, assertPaths []string) (changeID string, err error) {
// Check if all files exist before starting the go routine
snapFiles, err := checkAndOpenFiles(snapPaths)
if err != nil {
return "", err
}
assertsFiles, err := checkAndOpenFiles(assertPaths)
if err != nil {
return "", err
}
pr, pw := io.Pipe()
mw := multipart.NewWriter(pw)
go sendRemodelFiles(model, snapPaths, snapFiles, assertsFiles, pw, mw)
headers := map[string]string{
"Content-Type": mw.FormDataContentType(),
}
_, changeID, err = client.doAsyncFull("POST", "/v2/model", nil, headers, pr, doNoTimeoutAndRetry)
return changeID, err
}
func checkAndOpenFiles(paths []string) ([]*os.File, error) {
var files []*os.File
for _, path := range paths {
f, err := os.Open(path)
if err != nil {
for _, openFile := range files {
openFile.Close()
}
return nil, fmt.Errorf("cannot open %q: %w", path, err)
}
files = append(files, f)
}
return files, nil
}
func createAssertionPart(name string, mw *multipart.Writer) (io.Writer, error) {
h := make(textproto.MIMEHeader)
h.Set("Content-Disposition",
fmt.Sprintf(`form-data; name="%s"`, name))
h.Set("Content-Type", asserts.MediaType)
return mw.CreatePart(h)
}
func sendRemodelFiles(model []byte, paths []string, files, assertFiles []*os.File, pw *io.PipeWriter, mw *multipart.Writer) {
defer func() {
for _, f := range files {
f.Close()
}
}()
w, err := createAssertionPart("new-model", mw)
if err != nil {
pw.CloseWithError(err)
return
}
_, err = w.Write(model)
if err != nil {
pw.CloseWithError(err)
return
}
for _, file := range assertFiles {
if err := sendPartFromFile(file,
func() (io.Writer, error) {
return createAssertionPart("assertion", mw)
}); err != nil {
pw.CloseWithError(err)
return
}
}
for i, file := range files {
if err := sendPartFromFile(file,
func() (io.Writer, error) {
return mw.CreateFormFile("snap", filepath.Base(paths[i]))
}); err != nil {
pw.CloseWithError(err)
return
}
}
mw.Close()
pw.Close()
}
func sendPartFromFile(file *os.File, writeHeader func() (io.Writer, error)) error {
fw, err := writeHeader()
if err != nil {
return err
}
_, err = io.Copy(fw, file)
if err != nil {
return err
}
return nil
}
// CurrentModelAssertion returns the current model assertion
func (client *Client) CurrentModelAssertion() (*asserts.Model, error) {
assert, err := currentAssertion(client, "/v2/model")
if err != nil {
return nil, err
}
modelAssert, ok := assert.(*asserts.Model)
if !ok {
return nil, fmt.Errorf("unexpected assertion type (%s) returned", assert.Type().Name)
}
return modelAssert, nil
}
// CurrentSerialAssertion returns the current serial assertion
func (client *Client) CurrentSerialAssertion() (*asserts.Serial, error) {
assert, err := currentAssertion(client, "/v2/model/serial")
if err != nil {
return nil, err
}
serialAssert, ok := assert.(*asserts.Serial)
if !ok {
return nil, fmt.Errorf("unexpected assertion type (%s) returned", assert.Type().Name)
}
return serialAssert, nil
}
// helper function for getting assertions from the daemon via a REST path
func currentAssertion(client *Client, path string) (asserts.Assertion, error) {
q := url.Values{}
response, cancel, err := client.rawWithTimeout(context.Background(), "GET", path, q, nil, nil, nil)
if err != nil {
fmt := "failed to query current assertion: %w"
return nil, xerrors.Errorf(fmt, err)
}
defer cancel()
defer response.Body.Close()
if response.StatusCode != 200 {
return nil, parseError(response)
}
dec := asserts.NewDecoder(response.Body)
// only decode a single assertion - we can't ever get more than a single
// assertion through these endpoints by design
assert, err := dec.Decode()
if err != nil {
return nil, fmt.Errorf("failed to decode assertions: %v", err)
}
return assert, nil
}
|