/
common.go
280 lines (257 loc) · 8.65 KB
/
common.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
// Copyright 2014 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package commands
import (
"fmt"
"net/http"
"path"
"time"
"github.com/juju/cmd"
"github.com/juju/errors"
"github.com/juju/loggo"
"github.com/juju/persistent-cookiejar"
"github.com/juju/utils"
"golang.org/x/net/publicsuffix"
"gopkg.in/juju/charm.v5"
"gopkg.in/juju/charm.v5/charmrepo"
"gopkg.in/juju/charmstore.v4/csclient"
"gopkg.in/macaroon-bakery.v0/httpbakery"
"gopkg.in/macaroon.v1"
"github.com/juju/juju/api"
"github.com/juju/juju/apiserver/params"
"github.com/juju/juju/cmd/envcmd"
"github.com/juju/juju/environs"
"github.com/juju/juju/environs/config"
"github.com/juju/juju/environs/configstore"
)
// destroyPreparedEnviron destroys the environment and logs an error
// if it fails.
var destroyPreparedEnviron = destroyPreparedEnvironProductionFunc
var logger = loggo.GetLogger("juju.cmd.juju")
func destroyPreparedEnvironProductionFunc(
ctx *cmd.Context,
env environs.Environ,
store configstore.Storage,
action string,
) {
ctx.Infof("%s failed, destroying environment", action)
if err := environs.Destroy(env, store); err != nil {
logger.Errorf("the environment could not be destroyed: %v", err)
}
}
var destroyEnvInfo = destroyEnvInfoProductionFunc
func destroyEnvInfoProductionFunc(
ctx *cmd.Context,
cfgName string,
store configstore.Storage,
action string,
) {
ctx.Infof("%s failed, cleaning up the environment.", action)
if err := environs.DestroyInfo(cfgName, store); err != nil {
logger.Errorf("the environment jenv file could not be cleaned up: %v", err)
}
}
// environFromName loads an existing environment or prepares a new
// one. If there are no errors, it returns the environ and a closure to
// clean up in case we need to further up the stack. If an error has
// occurred, the environment and cleanup function will be nil, and the
// error will be filled in.
var environFromName = environFromNameProductionFunc
func environFromNameProductionFunc(
ctx *cmd.Context,
envName string,
action string,
ensureNotBootstrapped func(environs.Environ) error,
) (env environs.Environ, cleanup func(), err error) {
store, err := configstore.Default()
if err != nil {
return nil, nil, err
}
envExisted := false
if environInfo, err := store.ReadInfo(envName); err == nil {
envExisted = true
logger.Warningf(
"ignoring environments.yaml: using bootstrap config in %s",
environInfo.Location(),
)
} else if !errors.IsNotFound(err) {
return nil, nil, err
}
cleanup = func() {
// Distinguish b/t removing the jenv file or tearing down the
// environment. We want to remove the jenv file if preparation
// was not successful. We want to tear down the environment
// only in the case where the environment didn't already
// exist.
if env == nil {
logger.Debugf("Destroying environment info.")
destroyEnvInfo(ctx, envName, store, action)
} else if !envExisted && ensureNotBootstrapped(env) != environs.ErrAlreadyBootstrapped {
logger.Debugf("Destroying environment.")
destroyPreparedEnviron(ctx, env, store, action)
}
}
if env, err = environs.PrepareFromName(envName, envcmd.BootstrapContext(ctx), store); err != nil {
return nil, cleanup, err
}
return env, cleanup, err
}
// resolveCharmURL resolves the given charm URL string
// by looking it up in the appropriate charm repository.
// If it is a charm store charm URL, the given csParams will
// be used to access the charm store repository.
// If it is a local charm URL, the local charm repository at
// the given repoPath will be used. The given configuration
// will be used to add any necessary attributes to the repo
// and to resolve the default series if possible.
//
// resolveCharmURL also returns the charm repository holding
// the charm.
func resolveCharmURL(curlStr string, csParams charmrepo.NewCharmStoreParams, repoPath string, conf *config.Config) (*charm.URL, charmrepo.Interface, error) {
ref, err := charm.ParseReference(curlStr)
if err != nil {
return nil, nil, errors.Trace(err)
}
repo, err := charmrepo.InferRepository(ref, csParams, repoPath)
if err != nil {
return nil, nil, errors.Trace(err)
}
repo = config.SpecializeCharmRepo(repo, conf)
if ref.Series == "" {
if defaultSeries, ok := conf.DefaultSeries(); ok {
ref.Series = defaultSeries
}
}
if ref.Schema == "local" && ref.Series == "" {
possibleURL := *ref
possibleURL.Series = "trusty"
logger.Errorf("The series is not specified in the environment (default-series) or with the charm. Did you mean:\n\t%s", &possibleURL)
return nil, nil, errors.Errorf("cannot resolve series for charm: %q", ref)
}
if ref.Series != "" && ref.Revision != -1 {
// The URL is already fully resolved; do not
// bother with an unnecessary round-trip to the
// charm store.
curl, err := ref.URL("")
if err != nil {
panic(err)
}
return curl, repo, nil
}
curl, err := repo.Resolve(ref)
if err != nil {
return nil, nil, errors.Trace(err)
}
return curl, repo, nil
}
// addCharmViaAPI calls the appropriate client API calls to add the
// given charm URL to state. For non-public charm URLs, this function also
// handles the macaroon authorization process using the given csClient.
// The resulting charm URL of the added charm is displayed on stdout.
func addCharmViaAPI(client *api.Client, ctx *cmd.Context, curl *charm.URL, repo charmrepo.Interface, csclient *csClient) (*charm.URL, error) {
switch curl.Schema {
case "local":
ch, err := repo.Get(curl)
if err != nil {
return nil, err
}
stateCurl, err := client.AddLocalCharm(curl, ch)
if err != nil {
return nil, err
}
curl = stateCurl
case "cs":
if err := client.AddCharm(curl); err != nil {
if !params.IsCodeUnauthorized(err) {
return nil, errors.Mask(err)
}
m, err := csclient.authorize(curl)
if err != nil {
return nil, errors.Mask(err)
}
if err := client.AddCharmWithAuthorization(curl, m); err != nil {
return nil, errors.Mask(err)
}
}
default:
return nil, fmt.Errorf("unsupported charm URL schema: %q", curl.Schema)
}
ctx.Infof("Added charm %q to the environment.", curl)
return curl, nil
}
// csClient gives access to the charm store server and provides parameters
// for connecting to the charm store.
type csClient struct {
jar *cookiejar.Jar
params charmrepo.NewCharmStoreParams
}
// newCharmStoreClient is called to obtain a charm store client
// including the parameters for connecting to the charm store, and
// helpers to save the local authorization cookies and to authorize
// non-public charm deployments. It is defined as a variable so it can
// be changed for testing purposes.
var newCharmStoreClient = func() (*csClient, error) {
jar, client, err := newHTTPClient()
if err != nil {
return nil, errors.Mask(err)
}
return &csClient{
jar: jar,
params: charmrepo.NewCharmStoreParams{
HTTPClient: client,
VisitWebPage: httpbakery.OpenWebBrowser,
},
}, nil
}
func newHTTPClient() (*cookiejar.Jar, *http.Client, error) {
cookieFile := path.Join(utils.Home(), ".go-cookies")
jar, err := cookiejar.New(&cookiejar.Options{
PublicSuffixList: publicsuffix.List,
})
if err != nil {
panic(err)
}
if err := jar.Load(cookieFile); err != nil {
return nil, nil, err
}
client := httpbakery.NewHTTPClient()
client.Jar = jar
return jar, client, nil
}
// authorize acquires and return the charm store delegatable macaroon to be
// used to add the charm corresponding to the given URL.
// The macaroon is properly attenuated so that it can only be used to deploy
// the given charm URL.
func (c *csClient) authorize(curl *charm.URL) (*macaroon.Macaroon, error) {
client := csclient.New(csclient.Params{
URL: c.params.URL,
HTTPClient: c.params.HTTPClient,
VisitWebPage: c.params.VisitWebPage,
})
var m *macaroon.Macaroon
if err := client.Get("/delegatable-macaroon", &m); err != nil {
return nil, errors.Trace(err)
}
if err := m.AddFirstPartyCaveat("is-entity " + curl.String()); err != nil {
return nil, errors.Trace(err)
}
return m, nil
}
// formatStatusTime returns a string with the local time
// formatted in an arbitrary format used for status or
// and localized tz or in utc timezone and format RFC3339
// if u is specified.
func formatStatusTime(t *time.Time, formatISO bool) string {
if formatISO {
// If requested, use ISO time format.
// The format we use is RFC3339 without the "T". From the spec:
// NOTE: ISO 8601 defines date and time separated by "T".
// Applications using this syntax may choose, for the sake of
// readability, to specify a full-date and full-time separated by
// (say) a space character.
return t.UTC().Format("2006-01-02 15:04:05Z")
} else {
// Otherwise use local time.
return t.Local().Format("02 Jan 2006 15:04:05Z07:00")
}
}