/
conn.go
265 lines (248 loc) · 7.42 KB
/
conn.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
// Copyright 2012, 2013 Canonical Ltd.
// Licensed under the AGPLv3, see LICENCE file for details.
package juju
import (
stderrors "errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"time"
"github.com/juju/loggo"
"github.com/wallyworld/core/charm"
"github.com/wallyworld/core/environs"
"github.com/wallyworld/core/environs/configstore"
"github.com/wallyworld/core/errors"
"github.com/wallyworld/core/juju/osenv"
"github.com/wallyworld/core/state"
"github.com/wallyworld/core/utils"
"github.com/wallyworld/core/utils/ssh"
)
var logger = loggo.GetLogger("juju.conn")
// Conn holds a connection to a juju environment and its
// associated state.
type Conn struct {
Environ environs.Environ
State *state.State
}
var redialStrategy = utils.AttemptStrategy{
Total: 60 * time.Second,
Delay: 250 * time.Millisecond,
}
// NewConn returns a new Conn that uses the
// given environment. The environment must have already
// been bootstrapped.
func NewConn(environ environs.Environ) (*Conn, error) {
info, _, err := environ.StateInfo()
if err != nil {
return nil, err
}
password := environ.Config().AdminSecret()
if password == "" {
return nil, fmt.Errorf("cannot connect without admin-secret")
}
err = environs.CheckEnvironment(environ)
if err != nil {
return nil, err
}
info.Password = password
opts := state.DefaultDialOpts()
st, err := state.Open(info, opts, environs.NewStatePolicy())
if errors.IsUnauthorized(err) {
logger.Infof("authorization error while connecting to state server; retrying")
// We can't connect with the administrator password,;
// perhaps this was the first connection and the
// password has not been changed yet.
info.Password = utils.UserPasswordHash(password, utils.CompatSalt)
// We try for a while because we might succeed in
// connecting to mongo before the state has been
// initialized and the initial password set.
for a := redialStrategy.Start(); a.Next(); {
st, err = state.Open(info, opts, environs.NewStatePolicy())
if !errors.IsUnauthorized(err) {
break
}
}
if err != nil {
return nil, err
}
if err := st.SetAdminMongoPassword(password); err != nil {
return nil, err
}
} else if err != nil {
return nil, err
}
conn := &Conn{
Environ: environ,
State: st,
}
if err := conn.updateSecrets(); err != nil {
conn.Close()
return nil, fmt.Errorf("unable to push secrets: %v", err)
}
return conn, nil
}
// NewConnFromState returns a Conn that uses an Environ
// made by reading the environment configuration.
// The resulting Conn uses the given State - closing
// it will close that State.
func NewConnFromState(st *state.State) (*Conn, error) {
cfg, err := st.EnvironConfig()
if err != nil {
return nil, err
}
environ, err := environs.New(cfg)
if err != nil {
return nil, err
}
return &Conn{
Environ: environ,
State: st,
}, nil
}
// NewConnFromName returns a Conn pointing at the environName environment, or the
// default environment if not specified.
func NewConnFromName(environName string) (*Conn, error) {
store, err := configstore.Default()
if err != nil {
return nil, err
}
environ, err := environs.NewFromName(environName, store)
if err != nil {
return nil, err
}
return NewConn(environ)
}
// Close terminates the connection to the environment and releases
// any associated resources.
func (c *Conn) Close() error {
return c.State.Close()
}
// updateSecrets writes secrets into the environment when there are none.
// This is done because environments such as ec2 offer no way to securely
// deliver the secrets onto the machine, so the bootstrap is done with the
// whole environment configuration but without secrets, and then secrets
// are delivered on the first communication with the running environment.
func (c *Conn) updateSecrets() error {
secrets, err := c.Environ.Provider().SecretAttrs(c.Environ.Config())
if err != nil {
return err
}
cfg, err := c.State.EnvironConfig()
if err != nil {
return err
}
secretAttrs := make(map[string]interface{})
attrs := cfg.AllAttrs()
for k, v := range secrets {
if _, exists := attrs[k]; exists {
// Environment already has secrets. Won't send again.
return nil
} else {
secretAttrs[k] = v
}
}
return c.State.UpdateEnvironConfig(secretAttrs, nil, nil)
}
// PutCharm uploads the given charm to provider storage, and adds a
// state.Charm to the state. The charm is not uploaded if a charm with
// the same URL already exists in the state.
// If bumpRevision is true, the charm must be a local directory,
// and the revision number will be incremented before pushing.
func (conn *Conn) PutCharm(curl *charm.URL, repo charm.Repository, bumpRevision bool) (*state.Charm, error) {
if curl.Revision == -1 {
rev, err := charm.Latest(repo, curl)
if err != nil {
return nil, fmt.Errorf("cannot get latest charm revision: %v", err)
}
curl = curl.WithRevision(rev)
}
ch, err := repo.Get(curl)
if err != nil {
return nil, fmt.Errorf("cannot get charm: %v", err)
}
if bumpRevision {
chd, ok := ch.(*charm.Dir)
if !ok {
return nil, fmt.Errorf("cannot increment revision of charm %q: not a directory", curl)
}
if err = chd.SetDiskRevision(chd.Revision() + 1); err != nil {
return nil, fmt.Errorf("cannot increment revision of charm %q: %v", curl, err)
}
curl = curl.WithRevision(chd.Revision())
}
if sch, err := conn.State.Charm(curl); err == nil {
return sch, nil
}
return conn.addCharm(curl, ch)
}
func (conn *Conn) addCharm(curl *charm.URL, ch charm.Charm) (*state.Charm, error) {
var f *os.File
name := charm.Quote(curl.String())
switch ch := ch.(type) {
case *charm.Dir:
var err error
if f, err = ioutil.TempFile("", name); err != nil {
return nil, err
}
defer os.Remove(f.Name())
defer f.Close()
err = ch.BundleTo(f)
if err != nil {
return nil, fmt.Errorf("cannot bundle charm: %v", err)
}
if _, err := f.Seek(0, 0); err != nil {
return nil, err
}
case *charm.Bundle:
var err error
if f, err = os.Open(ch.Path); err != nil {
return nil, fmt.Errorf("cannot read charm bundle: %v", err)
}
defer f.Close()
default:
return nil, fmt.Errorf("unknown charm type %T", ch)
}
digest, size, err := utils.ReadSHA256(f)
if err != nil {
return nil, err
}
if _, err := f.Seek(0, 0); err != nil {
return nil, err
}
stor := conn.Environ.Storage()
logger.Infof("writing charm to storage [%d bytes]", size)
if err := stor.Put(name, f, size); err != nil {
return nil, fmt.Errorf("cannot put charm: %v", err)
}
ustr, err := stor.URL(name)
if err != nil {
return nil, fmt.Errorf("cannot get storage URL for charm: %v", err)
}
u, err := url.Parse(ustr)
if err != nil {
return nil, fmt.Errorf("cannot parse storage URL: %v", err)
}
logger.Infof("adding charm to state")
sch, err := conn.State.AddCharm(ch, curl, u, digest)
if err != nil {
return nil, fmt.Errorf("cannot add charm: %v", err)
}
return sch, nil
}
// InitJujuHome initializes the charm, environs/config and utils/ssh packages
// to use default paths based on the $JUJU_HOME or $HOME environment variables.
// This function should be called before calling NewConn or Conn.Deploy.
func InitJujuHome() error {
jujuHome := osenv.JujuHomeDir()
if jujuHome == "" {
return stderrors.New(
"cannot determine juju home, required environment variables are not set")
}
osenv.SetJujuHome(jujuHome)
charm.CacheDir = osenv.JujuHomePath("charmcache")
if err := ssh.LoadClientKeys(osenv.JujuHomePath("ssh")); err != nil {
return fmt.Errorf("cannot load ssh client keys: %v", err)
}
return nil
}