~nskaggs/+junk/xenial-test

« back to all changes in this revision

Viewing changes to src/github.com/juju/juju/worker/uniter/uniter_test.go

  • Committer: Nicholas Skaggs
  • Date: 2016-10-24 20:56:05 UTC
  • Revision ID: nicholas.skaggs@canonical.com-20161024205605-z8lta0uvuhtxwzwl
Initi with beta15

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
// Copyright 2012-2015 Canonical Ltd.
 
2
// Licensed under the AGPLv3, see LICENCE file for details.
 
3
 
 
4
package uniter_test
 
5
 
 
6
import (
 
7
        "fmt"
 
8
        "io"
 
9
        "io/ioutil"
 
10
        "os"
 
11
        "os/exec"
 
12
        "path/filepath"
 
13
        "runtime"
 
14
        "strings"
 
15
        "syscall"
 
16
        "time"
 
17
 
 
18
        "github.com/juju/errors"
 
19
        "github.com/juju/mutex"
 
20
        jc "github.com/juju/testing/checkers"
 
21
        ft "github.com/juju/testing/filetesting"
 
22
        "github.com/juju/utils/clock"
 
23
        gc "gopkg.in/check.v1"
 
24
        corecharm "gopkg.in/juju/charm.v6-unstable"
 
25
 
 
26
        "github.com/juju/juju/agent/tools"
 
27
        "github.com/juju/juju/apiserver/params"
 
28
        "github.com/juju/juju/component/all"
 
29
        "github.com/juju/juju/juju/testing"
 
30
        "github.com/juju/juju/state"
 
31
        "github.com/juju/juju/status"
 
32
        "github.com/juju/juju/testcharms"
 
33
        coretesting "github.com/juju/juju/testing"
 
34
        "github.com/juju/juju/worker/uniter/operation"
 
35
)
 
36
 
 
37
type UniterSuite struct {
 
38
        coretesting.GitSuite
 
39
        testing.JujuConnSuite
 
40
        dataDir  string
 
41
        oldLcAll string
 
42
        unitDir  string
 
43
 
 
44
        updateStatusHookTicker *manualTicker
 
45
}
 
46
 
 
47
var _ = gc.Suite(&UniterSuite{})
 
48
 
 
49
var leaseClock *coretesting.Clock
 
50
 
 
51
// This guarantees that we get proper platform
 
52
// specific error directly from their source
 
53
// This works on both windows and unix
 
54
var errNotDir = syscall.ENOTDIR.Error()
 
55
 
 
56
func (s *UniterSuite) SetUpSuite(c *gc.C) {
 
57
        s.GitSuite.SetUpSuite(c)
 
58
        s.JujuConnSuite.SetUpSuite(c)
 
59
        s.dataDir = c.MkDir()
 
60
        toolsDir := tools.ToolsDir(s.dataDir, "unit-u-0")
 
61
        err := os.MkdirAll(toolsDir, 0755)
 
62
        c.Assert(err, jc.ErrorIsNil)
 
63
        // TODO(fwereade) GAAAAAAAAAAAAAAAAAH this is LUDICROUS.
 
64
        cmd := exec.Command(jujudBuildArgs[0], jujudBuildArgs[1:]...)
 
65
        cmd.Dir = toolsDir
 
66
        out, err := cmd.CombinedOutput()
 
67
        c.Logf(string(out))
 
68
        c.Assert(err, jc.ErrorIsNil)
 
69
        s.oldLcAll = os.Getenv("LC_ALL")
 
70
        os.Setenv("LC_ALL", "en_US")
 
71
        s.unitDir = filepath.Join(s.dataDir, "agents", "unit-u-0")
 
72
 
 
73
        zone, err := time.LoadLocation("")
 
74
        c.Assert(err, jc.ErrorIsNil)
 
75
        now := time.Date(2030, 11, 11, 11, 11, 11, 11, zone)
 
76
        leaseClock = coretesting.NewClock(now)
 
77
        oldGetClock := state.GetClock
 
78
        state.GetClock = func() clock.Clock {
 
79
                return leaseClock
 
80
        }
 
81
        s.AddCleanup(func(*gc.C) { state.GetClock = oldGetClock })
 
82
        all.RegisterForServer()
 
83
}
 
84
 
 
85
func (s *UniterSuite) TearDownSuite(c *gc.C) {
 
86
        os.Setenv("LC_ALL", s.oldLcAll)
 
87
        s.JujuConnSuite.TearDownSuite(c)
 
88
        s.GitSuite.TearDownSuite(c)
 
89
}
 
90
 
 
91
func (s *UniterSuite) SetUpTest(c *gc.C) {
 
92
        s.updateStatusHookTicker = newManualTicker()
 
93
        s.GitSuite.SetUpTest(c)
 
94
        s.JujuConnSuite.SetUpTest(c)
 
95
}
 
96
 
 
97
func (s *UniterSuite) TearDownTest(c *gc.C) {
 
98
        s.ResetContext(c)
 
99
        s.JujuConnSuite.TearDownTest(c)
 
100
        s.GitSuite.TearDownTest(c)
 
101
}
 
102
 
 
103
func (s *UniterSuite) Reset(c *gc.C) {
 
104
        s.JujuConnSuite.Reset(c)
 
105
        s.ResetContext(c)
 
106
}
 
107
 
 
108
func (s *UniterSuite) ResetContext(c *gc.C) {
 
109
        err := os.RemoveAll(s.unitDir)
 
110
        c.Assert(err, jc.ErrorIsNil)
 
111
}
 
112
 
 
113
func (s *UniterSuite) runUniterTests(c *gc.C, uniterTests []uniterTest) {
 
114
        for i, t := range uniterTests {
 
115
                c.Logf("\ntest %d: %s\n", i, t.summary)
 
116
                func() {
 
117
                        defer s.Reset(c)
 
118
                        env, err := s.State.Model()
 
119
                        c.Assert(err, jc.ErrorIsNil)
 
120
                        ctx := &context{
 
121
                                s:                      s,
 
122
                                st:                     s.State,
 
123
                                uuid:                   env.UUID(),
 
124
                                path:                   s.unitDir,
 
125
                                dataDir:                s.dataDir,
 
126
                                charms:                 make(map[string][]byte),
 
127
                                updateStatusHookTicker: s.updateStatusHookTicker,
 
128
                                charmDirGuard:          &mockCharmDirGuard{},
 
129
                        }
 
130
                        ctx.run(c, t.steps)
 
131
                }()
 
132
        }
 
133
}
 
134
 
 
135
func (s *UniterSuite) TestUniterStartup(c *gc.C) {
 
136
        s.runUniterTests(c, []uniterTest{
 
137
                // Check conditions that can cause the uniter to fail to start.
 
138
                ut(
 
139
                        "unable to create state dir",
 
140
                        writeFile{"state", 0644},
 
141
                        createCharm{},
 
142
                        createServiceAndUnit{},
 
143
                        startUniter{},
 
144
                        waitUniterDead{err: `failed to initialize uniter for "unit-u-0": .*` + errNotDir},
 
145
                ), ut(
 
146
                        "unknown unit",
 
147
                        // We still need to create a unit, because that's when we also
 
148
                        // connect to the API, but here we use a different service
 
149
                        // (and hence unit) name.
 
150
                        createCharm{},
 
151
                        createServiceAndUnit{serviceName: "w"},
 
152
                        startUniter{unitTag: "unit-u-0"},
 
153
                        waitUniterDead{err: `failed to initialize uniter for "unit-u-0": permission denied`},
 
154
                ),
 
155
        })
 
156
}
 
157
 
 
158
func (s *UniterSuite) TestUniterBootstrap(c *gc.C) {
 
159
        //TODO(bogdanteleaga): Fix this on windows
 
160
        if runtime.GOOS == "windows" {
 
161
                c.Skip("bug 1403084: currently does not work on windows")
 
162
        }
 
163
        s.runUniterTests(c, []uniterTest{
 
164
                // Check error conditions during unit bootstrap phase.
 
165
                ut(
 
166
                        "insane deployment",
 
167
                        createCharm{},
 
168
                        serveCharm{},
 
169
                        writeFile{"charm", 0644},
 
170
                        createUniter{},
 
171
                        waitUniterDead{err: `executing operation "install cs:quantal/wordpress-0": open .*` + errNotDir},
 
172
                ), ut(
 
173
                        "charm cannot be downloaded",
 
174
                        createCharm{},
 
175
                        // don't serve charm
 
176
                        createUniter{},
 
177
                        waitUniterDead{err: `preparing operation "install cs:quantal/wordpress-0": failed to download charm .* not found`},
 
178
                ),
 
179
        })
 
180
}
 
181
 
 
182
func (s *UniterSuite) TestUniterInstallHook(c *gc.C) {
 
183
        s.runUniterTests(c, []uniterTest{
 
184
                ut(
 
185
                        "install hook fail and resolve",
 
186
                        startupError{"install"},
 
187
                        verifyWaiting{},
 
188
 
 
189
                        resolveError{state.ResolvedNoHooks},
 
190
                        waitUnitAgent{
 
191
                                status: status.StatusIdle,
 
192
                        },
 
193
                        waitUnitAgent{
 
194
                                statusGetter: unitStatusGetter,
 
195
                                status:       status.StatusUnknown,
 
196
                        },
 
197
                        waitHooks{"leader-elected", "config-changed", "start"},
 
198
                ), ut(
 
199
                        "install hook fail and retry",
 
200
                        startupError{"install"},
 
201
                        verifyWaiting{},
 
202
 
 
203
                        resolveError{state.ResolvedRetryHooks},
 
204
                        waitUnitAgent{
 
205
                                statusGetter: unitStatusGetter,
 
206
                                status:       status.StatusError,
 
207
                                info:         `hook failed: "install"`,
 
208
                                data: map[string]interface{}{
 
209
                                        "hook": "install",
 
210
                                },
 
211
                        },
 
212
                        waitHooks{"fail-install"},
 
213
                        fixHook{"install"},
 
214
                        verifyWaiting{},
 
215
 
 
216
                        resolveError{state.ResolvedRetryHooks},
 
217
                        waitUnitAgent{
 
218
                                status: status.StatusIdle,
 
219
                        },
 
220
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
221
                ),
 
222
        })
 
223
}
 
224
 
 
225
func (s *UniterSuite) TestUniterUpdateStatusHook(c *gc.C) {
 
226
        s.runUniterTests(c, []uniterTest{
 
227
                ut(
 
228
                        "update status hook runs on timer",
 
229
                        createCharm{},
 
230
                        serveCharm{},
 
231
                        createUniter{},
 
232
                        waitHooks(startupHooks(false)),
 
233
                        waitUnitAgent{status: status.StatusIdle},
 
234
                        updateStatusHookTick{},
 
235
                        waitHooks{"update-status"},
 
236
                ),
 
237
        })
 
238
}
 
239
 
 
240
func (s *UniterSuite) TestNoUniterUpdateStatusHookInError(c *gc.C) {
 
241
        s.runUniterTests(c, []uniterTest{
 
242
                ut(
 
243
                        "update status hook doesn't run if in error",
 
244
                        startupError{"start"},
 
245
                        waitHooks{},
 
246
                        updateStatusHookTick{},
 
247
                        waitHooks{},
 
248
 
 
249
                        // Resolve and hook should run.
 
250
                        resolveError{state.ResolvedNoHooks},
 
251
                        waitUnitAgent{
 
252
                                status: status.StatusIdle,
 
253
                        },
 
254
                        waitHooks{},
 
255
                        updateStatusHookTick{},
 
256
                        waitHooks{"update-status"},
 
257
                ),
 
258
        })
 
259
}
 
260
 
 
261
func (s *UniterSuite) TestUniterStartHook(c *gc.C) {
 
262
        s.runUniterTests(c, []uniterTest{
 
263
                ut(
 
264
                        "start hook fail and resolve",
 
265
                        startupError{"start"},
 
266
                        verifyWaiting{},
 
267
 
 
268
                        resolveError{state.ResolvedNoHooks},
 
269
                        waitUnitAgent{
 
270
                                status: status.StatusIdle,
 
271
                        },
 
272
                        waitUnitAgent{
 
273
                                statusGetter: unitStatusGetter,
 
274
                                status:       status.StatusMaintenance,
 
275
                                info:         "installing charm software",
 
276
                        },
 
277
                        waitHooks{"config-changed"},
 
278
                        verifyRunning{},
 
279
                ), ut(
 
280
                        "start hook fail and retry",
 
281
                        startupError{"start"},
 
282
                        verifyWaiting{},
 
283
 
 
284
                        resolveError{state.ResolvedRetryHooks},
 
285
                        waitUnitAgent{
 
286
                                statusGetter: unitStatusGetter,
 
287
                                status:       status.StatusError,
 
288
                                info:         `hook failed: "start"`,
 
289
                                data: map[string]interface{}{
 
290
                                        "hook": "start",
 
291
                                },
 
292
                        },
 
293
                        waitHooks{"fail-start"},
 
294
                        verifyWaiting{},
 
295
 
 
296
                        fixHook{"start"},
 
297
                        resolveError{state.ResolvedRetryHooks},
 
298
                        waitUnitAgent{
 
299
                                status: status.StatusIdle,
 
300
                        },
 
301
                        waitHooks{"start", "config-changed"},
 
302
                        verifyRunning{},
 
303
                ),
 
304
        })
 
305
}
 
306
 
 
307
func (s *UniterSuite) TestUniterMultipleErrors(c *gc.C) {
 
308
        s.runUniterTests(c, []uniterTest{
 
309
                ut(
 
310
                        "resolved is cleared before moving on to next hook",
 
311
                        createCharm{badHooks: []string{"install", "leader-elected", "config-changed", "start"}},
 
312
                        serveCharm{},
 
313
                        createUniter{},
 
314
                        waitUnitAgent{
 
315
                                statusGetter: unitStatusGetter,
 
316
                                status:       status.StatusError,
 
317
                                info:         `hook failed: "install"`,
 
318
                                data: map[string]interface{}{
 
319
                                        "hook": "install",
 
320
                                },
 
321
                        },
 
322
                        resolveError{state.ResolvedNoHooks},
 
323
                        waitUnitAgent{
 
324
                                statusGetter: unitStatusGetter,
 
325
                                status:       status.StatusError,
 
326
                                info:         `hook failed: "leader-elected"`,
 
327
                                data: map[string]interface{}{
 
328
                                        "hook": "leader-elected",
 
329
                                },
 
330
                        },
 
331
                        resolveError{state.ResolvedNoHooks},
 
332
                        waitUnitAgent{
 
333
                                statusGetter: unitStatusGetter,
 
334
                                status:       status.StatusError,
 
335
                                info:         `hook failed: "config-changed"`,
 
336
                                data: map[string]interface{}{
 
337
                                        "hook": "config-changed",
 
338
                                },
 
339
                        },
 
340
                        resolveError{state.ResolvedNoHooks},
 
341
                        waitUnitAgent{
 
342
                                statusGetter: unitStatusGetter,
 
343
                                status:       status.StatusError,
 
344
                                info:         `hook failed: "start"`,
 
345
                                data: map[string]interface{}{
 
346
                                        "hook": "start",
 
347
                                },
 
348
                        },
 
349
                ),
 
350
        })
 
351
}
 
352
 
 
353
func (s *UniterSuite) TestUniterConfigChangedHook(c *gc.C) {
 
354
        s.runUniterTests(c, []uniterTest{
 
355
                ut(
 
356
                        "config-changed hook fail and resolve",
 
357
                        startupError{"config-changed"},
 
358
                        verifyWaiting{},
 
359
 
 
360
                        // Note: we'll run another config-changed as soon as we hit the
 
361
                        // started state, so the broken hook would actually prevent us
 
362
                        // from advancing at all if we didn't fix it.
 
363
                        fixHook{"config-changed"},
 
364
                        resolveError{state.ResolvedNoHooks},
 
365
                        waitUnitAgent{
 
366
                                status: status.StatusIdle,
 
367
                        },
 
368
                        waitUnitAgent{
 
369
                                statusGetter: unitStatusGetter,
 
370
                                status:       status.StatusUnknown,
 
371
                        },
 
372
                        // TODO(axw) confirm with fwereade that this is correct.
 
373
                        // Previously we would see "start", "config-changed".
 
374
                        // I don't think we should see another config-changed,
 
375
                        // since config did not change since we resolved the
 
376
                        // failed one above.
 
377
                        waitHooks{"start"},
 
378
                        // If we'd accidentally retried that hook, somehow, we would get
 
379
                        // an extra config-changed as we entered started; see that we don't.
 
380
                        waitHooks{},
 
381
                        verifyRunning{},
 
382
                ), ut(
 
383
                        "config-changed hook fail and retry",
 
384
                        startupError{"config-changed"},
 
385
                        verifyWaiting{},
 
386
 
 
387
                        resolveError{state.ResolvedRetryHooks},
 
388
                        waitUnitAgent{
 
389
                                statusGetter: unitStatusGetter,
 
390
                                status:       status.StatusError,
 
391
                                info:         `hook failed: "config-changed"`,
 
392
                                data: map[string]interface{}{
 
393
                                        "hook": "config-changed",
 
394
                                },
 
395
                        },
 
396
                        waitHooks{"fail-config-changed"},
 
397
                        verifyWaiting{},
 
398
 
 
399
                        fixHook{"config-changed"},
 
400
                        resolveError{state.ResolvedRetryHooks},
 
401
                        waitUnitAgent{
 
402
                                status: status.StatusIdle,
 
403
                        },
 
404
                        waitHooks{"config-changed", "start"},
 
405
                        verifyRunning{},
 
406
                ), ut(
 
407
                        "steady state config change with config-get verification",
 
408
                        createCharm{
 
409
                                customize: func(c *gc.C, ctx *context, path string) {
 
410
                                        appendHook(c, path, "config-changed", appendConfigChanged)
 
411
                                },
 
412
                        },
 
413
                        serveCharm{},
 
414
                        createUniter{},
 
415
                        waitUnitAgent{
 
416
                                status: status.StatusIdle,
 
417
                        },
 
418
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
419
                        assertYaml{"charm/config.out", map[string]interface{}{
 
420
                                "blog-title": "My Title",
 
421
                        }},
 
422
                        changeConfig{"blog-title": "Goodness Gracious Me"},
 
423
                        waitHooks{"config-changed"},
 
424
                        verifyRunning{},
 
425
                        assertYaml{"charm/config.out", map[string]interface{}{
 
426
                                "blog-title": "Goodness Gracious Me",
 
427
                        }},
 
428
                ),
 
429
        })
 
430
}
 
431
 
 
432
func (s *UniterSuite) TestUniterHookSynchronisation(c *gc.C) {
 
433
        var lock hookLock
 
434
        s.runUniterTests(c, []uniterTest{
 
435
                ut(
 
436
                        "verify config change hook not run while lock held",
 
437
                        quickStart{},
 
438
                        lock.acquire(),
 
439
                        changeConfig{"blog-title": "Goodness Gracious Me"},
 
440
                        waitHooks{},
 
441
                        lock.release(),
 
442
                        waitHooks{"config-changed"},
 
443
                ), ut(
 
444
                        "verify held lock by another unit is not broken",
 
445
                        lock.acquire(),
 
446
                        // Can't use quickstart as it has a built in waitHooks.
 
447
                        createCharm{},
 
448
                        serveCharm{},
 
449
                        ensureStateWorker{},
 
450
                        createServiceAndUnit{},
 
451
                        startUniter{},
 
452
                        waitAddresses{},
 
453
                        waitHooks{},
 
454
                        lock.release(),
 
455
                        waitUnitAgent{status: status.StatusIdle},
 
456
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
457
                ),
 
458
        })
 
459
}
 
460
 
 
461
func (s *UniterSuite) TestUniterDyingReaction(c *gc.C) {
 
462
        s.runUniterTests(c, []uniterTest{
 
463
                // Reaction to entity deaths.
 
464
                ut(
 
465
                        "steady state unit dying",
 
466
                        quickStart{},
 
467
                        unitDying,
 
468
                        waitHooks{"leader-settings-changed", "stop"},
 
469
                        waitUniterDead{},
 
470
                ), ut(
 
471
                        "steady state unit dead",
 
472
                        quickStart{},
 
473
                        unitDead,
 
474
                        waitUniterDead{},
 
475
                        waitHooks{},
 
476
                ), ut(
 
477
                        "hook error unit dying",
 
478
                        startupError{"start"},
 
479
                        unitDying,
 
480
                        verifyWaiting{},
 
481
                        fixHook{"start"},
 
482
                        resolveError{state.ResolvedRetryHooks},
 
483
                        waitHooks{"start", "leader-settings-changed", "stop"},
 
484
                        waitUniterDead{},
 
485
                ), ut(
 
486
                        "hook error unit dead",
 
487
                        startupError{"start"},
 
488
                        unitDead,
 
489
                        waitUniterDead{},
 
490
                        waitHooks{},
 
491
                ),
 
492
        })
 
493
}
 
494
 
 
495
func (s *UniterSuite) TestUniterSteadyStateUpgrade(c *gc.C) {
 
496
        s.runUniterTests(c, []uniterTest{
 
497
                // Upgrade scenarios from steady state.
 
498
                ut(
 
499
                        "steady state upgrade",
 
500
                        quickStart{},
 
501
                        createCharm{revision: 1},
 
502
                        upgradeCharm{revision: 1},
 
503
                        waitUnitAgent{
 
504
                                status: status.StatusIdle,
 
505
                                charm:  1,
 
506
                        },
 
507
                        waitUnitAgent{
 
508
                                statusGetter: unitStatusGetter,
 
509
                                status:       status.StatusUnknown,
 
510
                                charm:        1,
 
511
                        },
 
512
                        waitHooks{"upgrade-charm", "config-changed"},
 
513
                        verifyCharm{revision: 1},
 
514
                        verifyRunning{},
 
515
                ),
 
516
        })
 
517
}
 
518
 
 
519
func (s *UniterSuite) TestUniterSteadyStateUpgradeForce(c *gc.C) {
 
520
        s.runUniterTests(c, []uniterTest{
 
521
                ut(
 
522
                        "steady state forced upgrade (identical behaviour)",
 
523
                        quickStart{},
 
524
                        createCharm{revision: 1},
 
525
                        upgradeCharm{revision: 1, forced: true},
 
526
                        waitUnitAgent{
 
527
                                status: status.StatusIdle,
 
528
                                charm:  1,
 
529
                        },
 
530
                        waitUnitAgent{
 
531
                                statusGetter: unitStatusGetter,
 
532
                                status:       status.StatusUnknown,
 
533
                                charm:        1,
 
534
                        },
 
535
                        waitHooks{"upgrade-charm", "config-changed"},
 
536
                        verifyCharm{revision: 1},
 
537
                        verifyRunning{},
 
538
                ),
 
539
        })
 
540
}
 
541
 
 
542
func (s *UniterSuite) TestUniterSteadyStateUpgradeResolve(c *gc.C) {
 
543
        s.runUniterTests(c, []uniterTest{
 
544
                ut(
 
545
                        "steady state upgrade hook fail and resolve",
 
546
                        quickStart{},
 
547
                        createCharm{revision: 1, badHooks: []string{"upgrade-charm"}},
 
548
                        upgradeCharm{revision: 1},
 
549
                        waitUnitAgent{
 
550
                                statusGetter: unitStatusGetter,
 
551
                                status:       status.StatusError,
 
552
                                info:         `hook failed: "upgrade-charm"`,
 
553
                                data: map[string]interface{}{
 
554
                                        "hook": "upgrade-charm",
 
555
                                },
 
556
                                charm: 1,
 
557
                        },
 
558
                        waitHooks{"fail-upgrade-charm"},
 
559
                        verifyCharm{revision: 1},
 
560
                        verifyWaiting{},
 
561
 
 
562
                        resolveError{state.ResolvedNoHooks},
 
563
                        waitUnitAgent{
 
564
                                status: status.StatusIdle,
 
565
                                charm:  1,
 
566
                        },
 
567
                        waitUnitAgent{
 
568
                                statusGetter: unitStatusGetter,
 
569
                                status:       status.StatusUnknown,
 
570
                                charm:        1,
 
571
                        },
 
572
                        waitHooks{"config-changed"},
 
573
                        verifyRunning{},
 
574
                ),
 
575
        })
 
576
}
 
577
 
 
578
func (s *UniterSuite) TestUniterSteadyStateUpgradeRetry(c *gc.C) {
 
579
        s.runUniterTests(c, []uniterTest{
 
580
                ut(
 
581
                        "steady state upgrade hook fail and retry",
 
582
                        quickStart{},
 
583
                        createCharm{revision: 1, badHooks: []string{"upgrade-charm"}},
 
584
                        upgradeCharm{revision: 1},
 
585
                        waitUnitAgent{
 
586
                                statusGetter: unitStatusGetter,
 
587
                                status:       status.StatusError,
 
588
                                info:         `hook failed: "upgrade-charm"`,
 
589
                                data: map[string]interface{}{
 
590
                                        "hook": "upgrade-charm",
 
591
                                },
 
592
                                charm: 1,
 
593
                        },
 
594
                        waitHooks{"fail-upgrade-charm"},
 
595
                        verifyCharm{revision: 1},
 
596
                        verifyWaiting{},
 
597
 
 
598
                        resolveError{state.ResolvedRetryHooks},
 
599
                        waitUnitAgent{
 
600
                                statusGetter: unitStatusGetter,
 
601
                                status:       status.StatusError,
 
602
                                info:         `hook failed: "upgrade-charm"`,
 
603
                                data: map[string]interface{}{
 
604
                                        "hook": "upgrade-charm",
 
605
                                },
 
606
                                charm: 1,
 
607
                        },
 
608
                        waitHooks{"fail-upgrade-charm"},
 
609
                        verifyWaiting{},
 
610
 
 
611
                        fixHook{"upgrade-charm"},
 
612
                        resolveError{state.ResolvedRetryHooks},
 
613
                        waitUnitAgent{
 
614
                                status: status.StatusIdle,
 
615
                                charm:  1,
 
616
                        },
 
617
                        waitHooks{"upgrade-charm", "config-changed"},
 
618
                        verifyRunning{},
 
619
                ),
 
620
        })
 
621
}
 
622
 
 
623
func (s *UniterSuite) TestUniterSteadyStateUpgradeRelations(c *gc.C) {
 
624
        s.runUniterTests(c, []uniterTest{
 
625
                ut(
 
626
                        // This test does an add-relation as quickly as possible
 
627
                        // after an upgrade-charm, in the hope that the scheduler will
 
628
                        // deliver the events in the wrong order. The observed
 
629
                        // behaviour should be the same in either case.
 
630
                        "ignore unknown relations until upgrade is done",
 
631
                        quickStart{},
 
632
                        createCharm{
 
633
                                revision: 2,
 
634
                                customize: func(c *gc.C, ctx *context, path string) {
 
635
                                        renameRelation(c, path, "db", "db2")
 
636
                                        hpath := filepath.Join(path, "hooks", "db2-relation-joined")
 
637
                                        ctx.writeHook(c, hpath, true)
 
638
                                },
 
639
                        },
 
640
                        serveCharm{},
 
641
                        upgradeCharm{revision: 2},
 
642
                        addRelation{},
 
643
                        addRelationUnit{},
 
644
                        waitHooks{"upgrade-charm", "config-changed", "db2-relation-joined mysql/0 db2:0"},
 
645
                        verifyCharm{revision: 2},
 
646
                ),
 
647
        })
 
648
}
 
649
 
 
650
func (s *UniterSuite) TestUpdateResourceCausesUpgrade(c *gc.C) {
 
651
        // appendStorageMetadata customises the wordpress charm's metadata,
 
652
        // adding a "wp-content" filesystem store. We do it here rather
 
653
        // than in the charm itself to avoid modifying all of the other
 
654
        // scenarios.
 
655
        appendResource := func(c *gc.C, ctx *context, path string) {
 
656
                f, err := os.OpenFile(filepath.Join(path, "metadata.yaml"), os.O_RDWR|os.O_APPEND, 0644)
 
657
                c.Assert(err, jc.ErrorIsNil)
 
658
                defer func() {
 
659
                        err := f.Close()
 
660
                        c.Assert(err, jc.ErrorIsNil)
 
661
                }()
 
662
                _, err = io.WriteString(f, `
 
663
resources:
 
664
  data:
 
665
    Type: file
 
666
    filename: filename.tgz
 
667
    comment: One line that is useful when operators need to push it.`)
 
668
                c.Assert(err, jc.ErrorIsNil)
 
669
        }
 
670
        s.runUniterTests(c, []uniterTest{
 
671
                ut(
 
672
                        "update resource causes upgrade",
 
673
 
 
674
                        // These steps are just copied from quickstart with a customized
 
675
                        // createCharm.
 
676
                        createCharm{customize: appendResource},
 
677
                        serveCharm{},
 
678
                        createUniter{},
 
679
                        waitUnitAgent{status: status.StatusIdle},
 
680
                        waitHooks(startupHooks(false)),
 
681
                        verifyCharm{},
 
682
 
 
683
                        pushResource{},
 
684
                        waitHooks{"upgrade-charm", "config-changed"},
 
685
                ),
 
686
        })
 
687
}
 
688
 
 
689
func (s *UniterSuite) TestUniterUpgradeOverwrite(c *gc.C) {
 
690
        //TODO(bogdanteleaga): Fix this on windows
 
691
        if runtime.GOOS == "windows" {
 
692
                c.Skip("bug 1403084: currently does not work on windows")
 
693
        }
 
694
        makeTest := func(description string, content, extraChecks ft.Entries) uniterTest {
 
695
                return ut(description,
 
696
                        createCharm{
 
697
                                // This is the base charm which all upgrade tests start out running.
 
698
                                customize: func(c *gc.C, ctx *context, path string) {
 
699
                                        ft.Entries{
 
700
                                                ft.Dir{"dir", 0755},
 
701
                                                ft.File{"file", "blah", 0644},
 
702
                                                ft.Symlink{"symlink", "file"},
 
703
                                        }.Create(c, path)
 
704
                                        // Note that it creates "dir/user-file" at runtime, which may be
 
705
                                        // preserved or removed depending on the test.
 
706
                                        script := "echo content > dir/user-file && chmod 755 dir/user-file"
 
707
                                        appendHook(c, path, "start", script)
 
708
                                },
 
709
                        },
 
710
                        serveCharm{},
 
711
                        createUniter{},
 
712
                        waitUnitAgent{
 
713
                                status: status.StatusIdle,
 
714
                        },
 
715
                        waitUnitAgent{
 
716
                                statusGetter: unitStatusGetter,
 
717
                                status:       status.StatusUnknown,
 
718
                        },
 
719
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
720
 
 
721
                        createCharm{
 
722
                                revision: 1,
 
723
                                customize: func(c *gc.C, _ *context, path string) {
 
724
                                        content.Create(c, path)
 
725
                                },
 
726
                        },
 
727
                        serveCharm{},
 
728
                        upgradeCharm{revision: 1},
 
729
                        waitUnitAgent{
 
730
                                status: status.StatusIdle,
 
731
                                charm:  1,
 
732
                        },
 
733
                        waitUnitAgent{
 
734
                                statusGetter: unitStatusGetter,
 
735
                                status:       status.StatusUnknown,
 
736
                                charm:        1,
 
737
                        },
 
738
                        waitHooks{"upgrade-charm", "config-changed"},
 
739
                        verifyCharm{revision: 1},
 
740
                        custom{func(c *gc.C, ctx *context) {
 
741
                                path := filepath.Join(ctx.path, "charm")
 
742
                                content.Check(c, path)
 
743
                                extraChecks.Check(c, path)
 
744
                        }},
 
745
                        verifyRunning{},
 
746
                )
 
747
        }
 
748
 
 
749
        s.runUniterTests(c, []uniterTest{
 
750
                makeTest(
 
751
                        "files overwite files, dirs, symlinks",
 
752
                        ft.Entries{
 
753
                                ft.File{"file", "new", 0755},
 
754
                                ft.File{"dir", "new", 0755},
 
755
                                ft.File{"symlink", "new", 0755},
 
756
                        },
 
757
                        ft.Entries{
 
758
                                ft.Removed{"dir/user-file"},
 
759
                        },
 
760
                ), makeTest(
 
761
                        "symlinks overwite files, dirs, symlinks",
 
762
                        ft.Entries{
 
763
                                ft.Symlink{"file", "new"},
 
764
                                ft.Symlink{"dir", "new"},
 
765
                                ft.Symlink{"symlink", "new"},
 
766
                        },
 
767
                        ft.Entries{
 
768
                                ft.Removed{"dir/user-file"},
 
769
                        },
 
770
                ), makeTest(
 
771
                        "dirs overwite files, symlinks; merge dirs",
 
772
                        ft.Entries{
 
773
                                ft.Dir{"file", 0755},
 
774
                                ft.Dir{"dir", 0755},
 
775
                                ft.File{"dir/charm-file", "charm-content", 0644},
 
776
                                ft.Dir{"symlink", 0755},
 
777
                        },
 
778
                        ft.Entries{
 
779
                                ft.File{"dir/user-file", "content\n", 0755},
 
780
                        },
 
781
                ),
 
782
        })
 
783
}
 
784
 
 
785
func (s *UniterSuite) TestUniterErrorStateUnforcedUpgrade(c *gc.C) {
 
786
        s.runUniterTests(c, []uniterTest{
 
787
                // Upgrade scenarios from error state.
 
788
                ut(
 
789
                        "error state unforced upgrade (ignored until started state)",
 
790
                        startupError{"start"},
 
791
                        createCharm{revision: 1},
 
792
                        upgradeCharm{revision: 1},
 
793
                        waitUnitAgent{
 
794
                                statusGetter: unitStatusGetter,
 
795
                                status:       status.StatusError,
 
796
                                info:         `hook failed: "start"`,
 
797
                                data: map[string]interface{}{
 
798
                                        "hook": "start",
 
799
                                },
 
800
                        },
 
801
                        waitHooks{},
 
802
                        verifyCharm{},
 
803
                        verifyWaiting{},
 
804
 
 
805
                        resolveError{state.ResolvedNoHooks},
 
806
                        waitUnitAgent{
 
807
                                status: status.StatusIdle,
 
808
                                charm:  1,
 
809
                        },
 
810
                        waitUnitAgent{
 
811
                                statusGetter: unitStatusGetter,
 
812
                                status:       status.StatusMaintenance,
 
813
                                info:         "installing charm software",
 
814
                                charm:        1,
 
815
                        },
 
816
                        waitHooks{"upgrade-charm", "config-changed"},
 
817
                        verifyCharm{revision: 1},
 
818
                        verifyRunning{},
 
819
                )})
 
820
}
 
821
 
 
822
func (s *UniterSuite) TestUniterErrorStateForcedUpgrade(c *gc.C) {
 
823
        s.runUniterTests(c, []uniterTest{
 
824
                ut(
 
825
                        "error state forced upgrade",
 
826
                        startupError{"start"},
 
827
                        createCharm{revision: 1},
 
828
                        upgradeCharm{revision: 1, forced: true},
 
829
                        // It's not possible to tell directly from state when the upgrade is
 
830
                        // complete, because the new unit charm URL is set at the upgrade
 
831
                        // process's point of no return (before actually deploying, but after
 
832
                        // the charm has been downloaded and verified). However, it's still
 
833
                        // useful to wait until that point...
 
834
                        waitUnitAgent{
 
835
                                statusGetter: unitStatusGetter,
 
836
                                status:       status.StatusError,
 
837
                                info:         `hook failed: "start"`,
 
838
                                data: map[string]interface{}{
 
839
                                        "hook": "start",
 
840
                                },
 
841
                                charm: 1,
 
842
                        },
 
843
                        // ...because the uniter *will* complete a started deployment even if
 
844
                        // we stop it from outside. So, by stopping and starting, we can be
 
845
                        // sure that the operation has completed and can safely verify that
 
846
                        // the charm state on disk is as we expect.
 
847
                        verifyWaiting{},
 
848
                        verifyCharm{revision: 1},
 
849
 
 
850
                        resolveError{state.ResolvedNoHooks},
 
851
                        waitUnitAgent{
 
852
                                status: status.StatusIdle,
 
853
                                charm:  1,
 
854
                        },
 
855
                        waitHooks{"config-changed"},
 
856
                        verifyRunning{},
 
857
                ),
 
858
        })
 
859
}
 
860
 
 
861
func (s *UniterSuite) TestUniterDeployerConversion(c *gc.C) {
 
862
        coretesting.SkipIfGitNotAvailable(c)
 
863
 
 
864
        deployerConversionTests := []uniterTest{
 
865
                ut(
 
866
                        "install normally, check not using git",
 
867
                        quickStart{},
 
868
                        verifyCharm{
 
869
                                checkFiles: ft.Entries{ft.Removed{".git"}},
 
870
                        },
 
871
                ), ut(
 
872
                        "install with git, restart in steady state",
 
873
                        prepareGitUniter{[]stepper{
 
874
                                quickStart{},
 
875
                                verifyGitCharm{},
 
876
                                stopUniter{},
 
877
                        }},
 
878
                        startUniter{},
 
879
                        waitHooks{"config-changed"},
 
880
 
 
881
                        // At this point, the deployer has been converted, but the
 
882
                        // charm directory itself hasn't; the *next* deployment will
 
883
                        // actually hit the charm directory and strip out the git
 
884
                        // stuff.
 
885
                        createCharm{revision: 1},
 
886
                        upgradeCharm{revision: 1},
 
887
                        waitHooks{"upgrade-charm", "config-changed"},
 
888
                        waitUnitAgent{
 
889
                                status: status.StatusIdle,
 
890
                                charm:  1,
 
891
                        },
 
892
                        waitUnitAgent{
 
893
                                statusGetter: unitStatusGetter,
 
894
                                status:       status.StatusUnknown,
 
895
                                charm:        1,
 
896
                        },
 
897
                        verifyCharm{
 
898
                                revision:   1,
 
899
                                checkFiles: ft.Entries{ft.Removed{".git"}},
 
900
                        },
 
901
                        verifyRunning{},
 
902
                ), ut(
 
903
                        "install with git, get conflicted, mark resolved",
 
904
                        prepareGitUniter{[]stepper{
 
905
                                startGitUpgradeError{},
 
906
                                stopUniter{},
 
907
                        }},
 
908
                        startUniter{},
 
909
 
 
910
                        resolveError{state.ResolvedNoHooks},
 
911
                        waitHooks{"upgrade-charm", "config-changed"},
 
912
                        waitUnitAgent{
 
913
                                status: status.StatusIdle,
 
914
                                charm:  1,
 
915
                        },
 
916
                        waitUnitAgent{
 
917
                                statusGetter: unitStatusGetter,
 
918
                                status:       status.StatusUnknown,
 
919
                                charm:        1,
 
920
                        },
 
921
                        verifyCharm{revision: 1},
 
922
                        verifyRunning{},
 
923
 
 
924
                        // Due to the uncertainties around marking upgrade conflicts resolved,
 
925
                        // the charm directory again remains unconverted, although the deployer
 
926
                        // should have been fixed. Again, we check this by running another
 
927
                        // upgrade and verifying the .git dir is then removed.
 
928
                        createCharm{revision: 2},
 
929
                        upgradeCharm{revision: 2},
 
930
                        waitHooks{"upgrade-charm", "config-changed"},
 
931
                        waitUnitAgent{
 
932
                                status: status.StatusIdle,
 
933
                                charm:  2,
 
934
                        },
 
935
                        waitUnitAgent{
 
936
                                statusGetter: unitStatusGetter,
 
937
                                status:       status.StatusUnknown,
 
938
                                charm:        2,
 
939
                        },
 
940
                        verifyCharm{
 
941
                                revision:   2,
 
942
                                checkFiles: ft.Entries{ft.Removed{".git"}},
 
943
                        },
 
944
                        verifyRunning{},
 
945
                ), ut(
 
946
                        "install with git, get conflicted, force an upgrade",
 
947
                        prepareGitUniter{[]stepper{
 
948
                                startGitUpgradeError{},
 
949
                                stopUniter{},
 
950
                        }},
 
951
                        startUniter{},
 
952
 
 
953
                        createCharm{
 
954
                                revision: 2,
 
955
                                customize: func(c *gc.C, ctx *context, path string) {
 
956
                                        ft.File{"data", "OVERWRITE!", 0644}.Create(c, path)
 
957
                                },
 
958
                        },
 
959
                        serveCharm{},
 
960
                        upgradeCharm{revision: 2, forced: true},
 
961
                        waitHooks{"upgrade-charm", "config-changed"},
 
962
                        waitUnitAgent{
 
963
                                status: status.StatusIdle,
 
964
                                charm:  2,
 
965
                        },
 
966
 
 
967
                        // A forced upgrade allows us to swap out the git deployer *and*
 
968
                        // the .git dir inside the charm immediately; check we did so.
 
969
                        verifyCharm{
 
970
                                revision: 2,
 
971
                                checkFiles: ft.Entries{
 
972
                                        ft.Removed{".git"},
 
973
                                        ft.File{"data", "OVERWRITE!", 0644},
 
974
                                },
 
975
                        },
 
976
                        verifyRunning{},
 
977
                ),
 
978
        }
 
979
        s.runUniterTests(c, deployerConversionTests)
 
980
}
 
981
 
 
982
func (s *UniterSuite) TestUniterUpgradeConflicts(c *gc.C) {
 
983
        coretesting.SkipIfPPC64EL(c, "lp:1448308")
 
984
        //TODO(bogdanteleaga): Fix this on windows
 
985
        if runtime.GOOS == "windows" {
 
986
                c.Skip("bug 1403084: currently does not work on windows")
 
987
        }
 
988
        s.runUniterTests(c, []uniterTest{
 
989
                // Upgrade scenarios - handling conflicts.
 
990
                ut(
 
991
                        "upgrade: resolving doesn't help until underlying problem is fixed",
 
992
                        startUpgradeError{},
 
993
                        resolveError{state.ResolvedNoHooks},
 
994
                        verifyWaitingUpgradeError{revision: 1},
 
995
                        fixUpgradeError{},
 
996
                        resolveError{state.ResolvedNoHooks},
 
997
                        waitHooks{"upgrade-charm", "config-changed"},
 
998
                        waitUnitAgent{
 
999
                                status: status.StatusIdle,
 
1000
                                charm:  1,
 
1001
                        },
 
1002
                        waitUnitAgent{
 
1003
                                statusGetter: unitStatusGetter,
 
1004
                                status:       status.StatusUnknown,
 
1005
                                charm:        1,
 
1006
                        },
 
1007
                        verifyCharm{revision: 1},
 
1008
                ), ut(
 
1009
                        `upgrade: forced upgrade does work without explicit resolution if underlying problem was fixed`,
 
1010
                        startUpgradeError{},
 
1011
                        resolveError{state.ResolvedNoHooks},
 
1012
                        verifyWaitingUpgradeError{revision: 1},
 
1013
                        fixUpgradeError{},
 
1014
                        createCharm{revision: 2},
 
1015
                        serveCharm{},
 
1016
                        upgradeCharm{revision: 2, forced: true},
 
1017
                        waitHooks{"upgrade-charm", "config-changed"},
 
1018
                        waitUnitAgent{
 
1019
                                status: status.StatusIdle,
 
1020
                                charm:  2,
 
1021
                        },
 
1022
                        waitUnitAgent{
 
1023
                                statusGetter: unitStatusGetter,
 
1024
                                status:       status.StatusUnknown,
 
1025
                                charm:        2,
 
1026
                        },
 
1027
                        verifyCharm{revision: 2},
 
1028
                ), ut(
 
1029
                        "upgrade conflict unit dying",
 
1030
                        startUpgradeError{},
 
1031
                        unitDying,
 
1032
                        verifyWaitingUpgradeError{revision: 1},
 
1033
                        fixUpgradeError{},
 
1034
                        resolveError{state.ResolvedNoHooks},
 
1035
                        waitHooks{"upgrade-charm", "config-changed", "leader-settings-changed", "stop"},
 
1036
                        waitUniterDead{},
 
1037
                ), ut(
 
1038
                        "upgrade conflict unit dead",
 
1039
                        startUpgradeError{},
 
1040
                        unitDead,
 
1041
                        waitUniterDead{},
 
1042
                        waitHooks{},
 
1043
                        fixUpgradeError{},
 
1044
                ),
 
1045
        })
 
1046
}
 
1047
 
 
1048
func (s *UniterSuite) TestUniterUpgradeGitConflicts(c *gc.C) {
 
1049
        coretesting.SkipIfGitNotAvailable(c)
 
1050
 
 
1051
        // These tests are copies of the old git-deployer-related tests, to test that
 
1052
        // the uniter with the manifest-deployer work patched out still works how it
 
1053
        // used to; thus demonstrating that the *other* tests that verify manifest
 
1054
        // deployer behaviour in the presence of an old git deployer are working against
 
1055
        // an accurate representation of the base state.
 
1056
        // The only actual behaviour change is that we no longer commit changes after
 
1057
        // each hook execution; this is reflected by checking that it's dirty in a couple
 
1058
        // of places where we once checked it was not.
 
1059
 
 
1060
        s.runUniterTests(c, []uniterTest{
 
1061
                // Upgrade scenarios - handling conflicts.
 
1062
                ugt(
 
1063
                        "upgrade: conflicting files",
 
1064
                        startGitUpgradeError{},
 
1065
 
 
1066
                        // NOTE: this is just dumbly committing the conflicts, but AFAICT this
 
1067
                        // is the only reasonable solution; if the user tells us it's resolved
 
1068
                        // we have to take their word for it.
 
1069
                        resolveError{state.ResolvedNoHooks},
 
1070
                        waitHooks{"upgrade-charm", "config-changed"},
 
1071
                        waitUnitAgent{
 
1072
                                status: status.StatusIdle,
 
1073
                                charm:  1,
 
1074
                        },
 
1075
                        waitUnitAgent{
 
1076
                                statusGetter: unitStatusGetter,
 
1077
                                status:       status.StatusUnknown,
 
1078
                                charm:        1,
 
1079
                        },
 
1080
                        verifyGitCharm{revision: 1},
 
1081
                ), ugt(
 
1082
                        `upgrade: conflicting directories`,
 
1083
                        createCharm{
 
1084
                                customize: func(c *gc.C, ctx *context, path string) {
 
1085
                                        err := os.Mkdir(filepath.Join(path, "data"), 0755)
 
1086
                                        c.Assert(err, jc.ErrorIsNil)
 
1087
                                        appendHook(c, path, "start", "echo DATA > data/newfile")
 
1088
                                },
 
1089
                        },
 
1090
                        serveCharm{},
 
1091
                        createUniter{},
 
1092
                        waitUnitAgent{
 
1093
                                status: status.StatusIdle,
 
1094
                        },
 
1095
                        waitUnitAgent{
 
1096
                                statusGetter: unitStatusGetter,
 
1097
                                status:       status.StatusUnknown,
 
1098
                        },
 
1099
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1100
                        verifyGitCharm{dirty: true},
 
1101
 
 
1102
                        createCharm{
 
1103
                                revision: 1,
 
1104
                                customize: func(c *gc.C, ctx *context, path string) {
 
1105
                                        data := filepath.Join(path, "data")
 
1106
                                        err := ioutil.WriteFile(data, []byte("<nelson>ha ha</nelson>"), 0644)
 
1107
                                        c.Assert(err, jc.ErrorIsNil)
 
1108
                                },
 
1109
                        },
 
1110
                        serveCharm{},
 
1111
                        upgradeCharm{revision: 1},
 
1112
                        waitUnitAgent{
 
1113
                                statusGetter: unitStatusGetter,
 
1114
                                status:       status.StatusError,
 
1115
                                info:         "upgrade failed",
 
1116
                                charm:        1,
 
1117
                        },
 
1118
                        verifyWaiting{},
 
1119
                        verifyGitCharm{dirty: true},
 
1120
 
 
1121
                        resolveError{state.ResolvedNoHooks},
 
1122
                        waitHooks{"upgrade-charm", "config-changed"},
 
1123
                        waitUnitAgent{
 
1124
                                status: status.StatusIdle,
 
1125
                                charm:  1,
 
1126
                        },
 
1127
                        verifyGitCharm{revision: 1},
 
1128
                ), ugt(
 
1129
                        "upgrade conflict resolved with forced upgrade",
 
1130
                        startGitUpgradeError{},
 
1131
                        createCharm{
 
1132
                                revision: 2,
 
1133
                                customize: func(c *gc.C, ctx *context, path string) {
 
1134
                                        otherdata := filepath.Join(path, "otherdata")
 
1135
                                        err := ioutil.WriteFile(otherdata, []byte("blah"), 0644)
 
1136
                                        c.Assert(err, jc.ErrorIsNil)
 
1137
                                },
 
1138
                        },
 
1139
                        serveCharm{},
 
1140
                        upgradeCharm{revision: 2, forced: true},
 
1141
                        waitUnitAgent{
 
1142
                                status: status.StatusIdle,
 
1143
                                charm:  2,
 
1144
                        }, waitUnitAgent{
 
1145
                                statusGetter: unitStatusGetter,
 
1146
                                status:       status.StatusUnknown,
 
1147
                                charm:        2,
 
1148
                        },
 
1149
                        waitHooks{"upgrade-charm", "config-changed"},
 
1150
                        verifyGitCharm{revision: 2},
 
1151
                        custom{func(c *gc.C, ctx *context) {
 
1152
                                // otherdata should exist (in v2)
 
1153
                                otherdata, err := ioutil.ReadFile(filepath.Join(ctx.path, "charm", "otherdata"))
 
1154
                                c.Assert(err, jc.ErrorIsNil)
 
1155
                                c.Assert(string(otherdata), gc.Equals, "blah")
 
1156
 
 
1157
                                // ignore should not (only in v1)
 
1158
                                _, err = os.Stat(filepath.Join(ctx.path, "charm", "ignore"))
 
1159
                                c.Assert(err, jc.Satisfies, os.IsNotExist)
 
1160
 
 
1161
                                // data should contain what was written in the start hook
 
1162
                                data, err := ioutil.ReadFile(filepath.Join(ctx.path, "charm", "data"))
 
1163
                                c.Assert(err, jc.ErrorIsNil)
 
1164
                                c.Assert(string(data), gc.Equals, "STARTDATA\n")
 
1165
                        }},
 
1166
                ), ugt(
 
1167
                        "upgrade conflict unit dying",
 
1168
                        startGitUpgradeError{},
 
1169
                        unitDying,
 
1170
                        verifyWaiting{},
 
1171
                        resolveError{state.ResolvedNoHooks},
 
1172
                        waitHooks{"upgrade-charm", "config-changed", "leader-settings-changed", "stop"},
 
1173
                        waitUniterDead{},
 
1174
                ), ugt(
 
1175
                        "upgrade conflict unit dead",
 
1176
                        startGitUpgradeError{},
 
1177
                        unitDead,
 
1178
                        waitUniterDead{},
 
1179
                        waitHooks{},
 
1180
                ),
 
1181
        })
 
1182
}
 
1183
 
 
1184
func (s *UniterSuite) TestUniterRelations(c *gc.C) {
 
1185
        waitDyingHooks := custom{func(c *gc.C, ctx *context) {
 
1186
                // There is no ordering relationship between relation hooks and
 
1187
                // leader-settings-changed hooks; and while we're dying we may
 
1188
                // never get to leader-settings-changed before it's time to run
 
1189
                // the stop (as we might not react to a config change in time).
 
1190
                // It's actually clearer to just list the possible orders:
 
1191
                possibles := [][]string{{
 
1192
                        "leader-settings-changed",
 
1193
                        "db-relation-departed mysql/0 db:0",
 
1194
                        "db-relation-broken db:0",
 
1195
                        "stop",
 
1196
                }, {
 
1197
                        "db-relation-departed mysql/0 db:0",
 
1198
                        "leader-settings-changed",
 
1199
                        "db-relation-broken db:0",
 
1200
                        "stop",
 
1201
                }, {
 
1202
                        "db-relation-departed mysql/0 db:0",
 
1203
                        "db-relation-broken db:0",
 
1204
                        "leader-settings-changed",
 
1205
                        "stop",
 
1206
                }, {
 
1207
                        "db-relation-departed mysql/0 db:0",
 
1208
                        "db-relation-broken db:0",
 
1209
                        "stop",
 
1210
                }}
 
1211
                unchecked := ctx.hooksCompleted[len(ctx.hooks):]
 
1212
                for _, possible := range possibles {
 
1213
                        if ok, _ := jc.DeepEqual(unchecked, possible); ok {
 
1214
                                return
 
1215
                        }
 
1216
                }
 
1217
                c.Fatalf("unexpected hooks: %v", unchecked)
 
1218
        }}
 
1219
        s.runUniterTests(c, []uniterTest{
 
1220
                // Relations.
 
1221
                ut(
 
1222
                        "simple joined/changed/departed",
 
1223
                        quickStartRelation{},
 
1224
                        addRelationUnit{},
 
1225
                        waitHooks{
 
1226
                                "db-relation-joined mysql/1 db:0",
 
1227
                                "db-relation-changed mysql/1 db:0",
 
1228
                        },
 
1229
                        changeRelationUnit{"mysql/0"},
 
1230
                        waitHooks{"db-relation-changed mysql/0 db:0"},
 
1231
                        removeRelationUnit{"mysql/1"},
 
1232
                        waitHooks{"db-relation-departed mysql/1 db:0"},
 
1233
                        verifyRunning{},
 
1234
                ), ut(
 
1235
                        "relation becomes dying; unit is not last remaining member",
 
1236
                        quickStartRelation{},
 
1237
                        relationDying,
 
1238
                        waitHooks{
 
1239
                                "db-relation-departed mysql/0 db:0",
 
1240
                                "db-relation-broken db:0",
 
1241
                        },
 
1242
                        verifyRunning{},
 
1243
                        relationState{life: state.Dying},
 
1244
                        removeRelationUnit{"mysql/0"},
 
1245
                        verifyRunning{},
 
1246
                        relationState{removed: true},
 
1247
                        verifyRunning{},
 
1248
                ), ut(
 
1249
                        "relation becomes dying; unit is last remaining member",
 
1250
                        quickStartRelation{},
 
1251
                        removeRelationUnit{"mysql/0"},
 
1252
                        waitHooks{"db-relation-departed mysql/0 db:0"},
 
1253
                        relationDying,
 
1254
                        waitHooks{"db-relation-broken db:0"},
 
1255
                        verifyRunning{},
 
1256
                        relationState{removed: true},
 
1257
                        verifyRunning{},
 
1258
                ), ut(
 
1259
                        "unit becomes dying while in a relation",
 
1260
                        quickStartRelation{},
 
1261
                        unitDying,
 
1262
                        waitUniterDead{},
 
1263
                        waitDyingHooks,
 
1264
                        relationState{life: state.Alive},
 
1265
                        removeRelationUnit{"mysql/0"},
 
1266
                        relationState{life: state.Alive},
 
1267
                ), ut(
 
1268
                        "unit becomes dead while in a relation",
 
1269
                        quickStartRelation{},
 
1270
                        unitDead,
 
1271
                        waitUniterDead{},
 
1272
                        waitHooks{},
 
1273
                        // TODO BUG(?): the unit doesn't leave the scope, leaving the relation
 
1274
                        // unkillable without direct intervention. I'm pretty sure it's not a
 
1275
                        // uniter bug -- it should be the responsibility of `juju remove-unit
 
1276
                        // --force` to cause the unit to leave any relation scopes it may be
 
1277
                        // in -- but it's worth noting here all the same.
 
1278
                ), ut(
 
1279
                        "unknown local relation dir is removed",
 
1280
                        quickStartRelation{},
 
1281
                        stopUniter{},
 
1282
                        custom{func(c *gc.C, ctx *context) {
 
1283
                                ft.Dir{"state/relations/90210", 0755}.Create(c, ctx.path)
 
1284
                        }},
 
1285
                        startUniter{},
 
1286
                        waitHooks{"config-changed"},
 
1287
                        custom{func(c *gc.C, ctx *context) {
 
1288
                                ft.Removed{"state/relations/90210"}.Check(c, ctx.path)
 
1289
                        }},
 
1290
                ), ut(
 
1291
                        "all relations are available to config-changed on bounce, even if state dir is missing",
 
1292
                        createCharm{
 
1293
                                customize: func(c *gc.C, ctx *context, path string) {
 
1294
                                        script := uniterRelationsCustomizeScript
 
1295
                                        appendHook(c, path, "config-changed", script)
 
1296
                                },
 
1297
                        },
 
1298
                        serveCharm{},
 
1299
                        createUniter{},
 
1300
                        waitUnitAgent{
 
1301
                                status: status.StatusIdle,
 
1302
                        },
 
1303
                        waitUnitAgent{
 
1304
                                statusGetter: unitStatusGetter,
 
1305
                                status:       status.StatusUnknown,
 
1306
                        },
 
1307
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1308
                        addRelation{waitJoin: true},
 
1309
                        stopUniter{},
 
1310
                        custom{func(c *gc.C, ctx *context) {
 
1311
                                // Check the state dir was created, and remove it.
 
1312
                                path := fmt.Sprintf("state/relations/%d", ctx.relation.Id())
 
1313
                                ft.Dir{path, 0755}.Check(c, ctx.path)
 
1314
                                ft.Removed{path}.Create(c, ctx.path)
 
1315
 
 
1316
                                // Check that config-changed didn't record any relations, because
 
1317
                                // they shouldn't been available until after the start hook.
 
1318
                                ft.File{"charm/relations.out", "", 0644}.Check(c, ctx.path)
 
1319
                        }},
 
1320
                        startUniter{},
 
1321
                        waitHooks{"config-changed"},
 
1322
                        custom{func(c *gc.C, ctx *context) {
 
1323
                                // Check the state dir was recreated.
 
1324
                                path := fmt.Sprintf("state/relations/%d", ctx.relation.Id())
 
1325
                                ft.Dir{path, 0755}.Check(c, ctx.path)
 
1326
 
 
1327
                                // Check that config-changed did record the joined relations.
 
1328
                                data := fmt.Sprintf("db:%d\n", ctx.relation.Id())
 
1329
                                ft.File{"charm/relations.out", data, 0644}.Check(c, ctx.path)
 
1330
                        }},
 
1331
                ),
 
1332
        })
 
1333
}
 
1334
 
 
1335
func (s *UniterSuite) TestUniterRelationErrors(c *gc.C) {
 
1336
        s.runUniterTests(c, []uniterTest{
 
1337
                ut(
 
1338
                        "hook error during join of a relation",
 
1339
                        startupRelationError{"db-relation-joined"},
 
1340
                        waitUnitAgent{
 
1341
                                statusGetter: unitStatusGetter,
 
1342
                                status:       status.StatusError,
 
1343
                                info:         `hook failed: "db-relation-joined"`,
 
1344
                                data: map[string]interface{}{
 
1345
                                        "hook":        "db-relation-joined",
 
1346
                                        "relation-id": 0,
 
1347
                                        "remote-unit": "mysql/0",
 
1348
                                },
 
1349
                        },
 
1350
                ), ut(
 
1351
                        "hook error during change of a relation",
 
1352
                        startupRelationError{"db-relation-changed"},
 
1353
                        waitUnitAgent{
 
1354
                                statusGetter: unitStatusGetter,
 
1355
                                status:       status.StatusError,
 
1356
                                info:         `hook failed: "db-relation-changed"`,
 
1357
                                data: map[string]interface{}{
 
1358
                                        "hook":        "db-relation-changed",
 
1359
                                        "relation-id": 0,
 
1360
                                        "remote-unit": "mysql/0",
 
1361
                                },
 
1362
                        },
 
1363
                ), ut(
 
1364
                        "hook error after a unit departed",
 
1365
                        startupRelationError{"db-relation-departed"},
 
1366
                        waitHooks{"db-relation-joined mysql/0 db:0", "db-relation-changed mysql/0 db:0"},
 
1367
                        removeRelationUnit{"mysql/0"},
 
1368
                        waitUnitAgent{
 
1369
                                statusGetter: unitStatusGetter,
 
1370
                                status:       status.StatusError,
 
1371
                                info:         `hook failed: "db-relation-departed"`,
 
1372
                                data: map[string]interface{}{
 
1373
                                        "hook":        "db-relation-departed",
 
1374
                                        "relation-id": 0,
 
1375
                                        "remote-unit": "mysql/0",
 
1376
                                },
 
1377
                        },
 
1378
                ),
 
1379
                ut(
 
1380
                        "hook error after a relation died",
 
1381
                        startupRelationError{"db-relation-broken"},
 
1382
                        waitHooks{"db-relation-joined mysql/0 db:0", "db-relation-changed mysql/0 db:0"},
 
1383
                        relationDying,
 
1384
                        waitUnitAgent{
 
1385
                                statusGetter: unitStatusGetter,
 
1386
                                status:       status.StatusError,
 
1387
                                info:         `hook failed: "db-relation-broken"`,
 
1388
                                data: map[string]interface{}{
 
1389
                                        "hook":        "db-relation-broken",
 
1390
                                        "relation-id": 0,
 
1391
                                },
 
1392
                        },
 
1393
                ),
 
1394
        })
 
1395
}
 
1396
 
 
1397
func (s *UniterSuite) TestActionEvents(c *gc.C) {
 
1398
        s.runUniterTests(c, []uniterTest{
 
1399
                ut(
 
1400
                        "simple action event: defined in actions.yaml, no args",
 
1401
                        createCharm{
 
1402
                                customize: func(c *gc.C, ctx *context, path string) {
 
1403
                                        ctx.writeAction(c, path, "action-log")
 
1404
                                        ctx.writeActionsYaml(c, path, "action-log")
 
1405
                                },
 
1406
                        },
 
1407
                        serveCharm{},
 
1408
                        ensureStateWorker{},
 
1409
                        createServiceAndUnit{},
 
1410
                        startUniter{},
 
1411
                        waitAddresses{},
 
1412
                        waitUnitAgent{status: status.StatusIdle},
 
1413
                        waitUnitAgent{
 
1414
                                statusGetter: unitStatusGetter,
 
1415
                                status:       status.StatusUnknown,
 
1416
                        },
 
1417
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1418
                        verifyCharm{},
 
1419
                        addAction{"action-log", nil},
 
1420
                        waitActionResults{[]actionResult{{
 
1421
                                name:    "action-log",
 
1422
                                results: map[string]interface{}{},
 
1423
                                status:  params.ActionCompleted,
 
1424
                        }}},
 
1425
                        waitUnitAgent{status: status.StatusIdle},
 
1426
                        waitUnitAgent{
 
1427
                                statusGetter: unitStatusGetter,
 
1428
                                status:       status.StatusUnknown,
 
1429
                        },
 
1430
                ), ut(
 
1431
                        "action-fail causes the action to fail with a message",
 
1432
                        createCharm{
 
1433
                                customize: func(c *gc.C, ctx *context, path string) {
 
1434
                                        ctx.writeAction(c, path, "action-log-fail")
 
1435
                                        ctx.writeActionsYaml(c, path, "action-log-fail")
 
1436
                                },
 
1437
                        },
 
1438
                        serveCharm{},
 
1439
                        ensureStateWorker{},
 
1440
                        createServiceAndUnit{},
 
1441
                        startUniter{},
 
1442
                        waitAddresses{},
 
1443
                        waitUnitAgent{status: status.StatusIdle},
 
1444
                        waitUnitAgent{
 
1445
                                statusGetter: unitStatusGetter,
 
1446
                                status:       status.StatusUnknown,
 
1447
                        },
 
1448
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1449
                        verifyCharm{},
 
1450
                        addAction{"action-log-fail", nil},
 
1451
                        waitActionResults{[]actionResult{{
 
1452
                                name: "action-log-fail",
 
1453
                                results: map[string]interface{}{
 
1454
                                        "foo": "still works",
 
1455
                                },
 
1456
                                message: "I'm afraid I can't let you do that, Dave.",
 
1457
                                status:  params.ActionFailed,
 
1458
                        }}},
 
1459
                        waitUnitAgent{status: status.StatusIdle}, waitUnitAgent{
 
1460
                                statusGetter: unitStatusGetter,
 
1461
                                status:       status.StatusUnknown,
 
1462
                        },
 
1463
                ), ut(
 
1464
                        "action-fail with the wrong arguments fails but is not an error",
 
1465
                        createCharm{
 
1466
                                customize: func(c *gc.C, ctx *context, path string) {
 
1467
                                        ctx.writeAction(c, path, "action-log-fail-error")
 
1468
                                        ctx.writeActionsYaml(c, path, "action-log-fail-error")
 
1469
                                },
 
1470
                        },
 
1471
                        serveCharm{},
 
1472
                        ensureStateWorker{},
 
1473
                        createServiceAndUnit{},
 
1474
                        startUniter{},
 
1475
                        waitAddresses{},
 
1476
                        waitUnitAgent{status: status.StatusIdle},
 
1477
                        waitUnitAgent{
 
1478
                                statusGetter: unitStatusGetter,
 
1479
                                status:       status.StatusUnknown,
 
1480
                        },
 
1481
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1482
                        verifyCharm{},
 
1483
                        addAction{"action-log-fail-error", nil},
 
1484
                        waitActionResults{[]actionResult{{
 
1485
                                name: "action-log-fail-error",
 
1486
                                results: map[string]interface{}{
 
1487
                                        "foo": "still works",
 
1488
                                },
 
1489
                                message: "A real message",
 
1490
                                status:  params.ActionFailed,
 
1491
                        }}},
 
1492
                        waitUnitAgent{status: status.StatusIdle},
 
1493
                        waitUnitAgent{
 
1494
                                statusGetter: unitStatusGetter,
 
1495
                                status:       status.StatusUnknown,
 
1496
                        },
 
1497
                ), ut(
 
1498
                        "actions with correct params passed are not an error",
 
1499
                        createCharm{
 
1500
                                customize: func(c *gc.C, ctx *context, path string) {
 
1501
                                        ctx.writeAction(c, path, "snapshot")
 
1502
                                        ctx.writeActionsYaml(c, path, "snapshot")
 
1503
                                },
 
1504
                        },
 
1505
                        serveCharm{},
 
1506
                        ensureStateWorker{},
 
1507
                        createServiceAndUnit{},
 
1508
                        startUniter{},
 
1509
                        waitAddresses{},
 
1510
                        waitUnitAgent{status: status.StatusIdle},
 
1511
                        waitUnitAgent{
 
1512
                                statusGetter: unitStatusGetter,
 
1513
                                status:       status.StatusUnknown,
 
1514
                        },
 
1515
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1516
                        verifyCharm{},
 
1517
                        addAction{
 
1518
                                name:   "snapshot",
 
1519
                                params: map[string]interface{}{"outfile": "foo.bar"},
 
1520
                        },
 
1521
                        waitActionResults{[]actionResult{{
 
1522
                                name: "snapshot",
 
1523
                                results: map[string]interface{}{
 
1524
                                        "outfile": map[string]interface{}{
 
1525
                                                "name": "snapshot-01.tar",
 
1526
                                                "size": map[string]interface{}{
 
1527
                                                        "magnitude": "10.3",
 
1528
                                                        "units":     "GB",
 
1529
                                                },
 
1530
                                        },
 
1531
                                        "completion": "yes",
 
1532
                                },
 
1533
                                status: params.ActionCompleted,
 
1534
                        }}},
 
1535
                        waitUnitAgent{status: status.StatusIdle},
 
1536
                        waitUnitAgent{
 
1537
                                statusGetter: unitStatusGetter,
 
1538
                                status:       status.StatusUnknown,
 
1539
                        },
 
1540
                ), ut(
 
1541
                        "actions with incorrect params passed are not an error but fail",
 
1542
                        createCharm{
 
1543
                                customize: func(c *gc.C, ctx *context, path string) {
 
1544
                                        ctx.writeAction(c, path, "snapshot")
 
1545
                                        ctx.writeActionsYaml(c, path, "snapshot")
 
1546
                                },
 
1547
                        },
 
1548
                        serveCharm{},
 
1549
                        ensureStateWorker{},
 
1550
                        createServiceAndUnit{},
 
1551
                        startUniter{},
 
1552
                        waitAddresses{},
 
1553
                        waitUnitAgent{status: status.StatusIdle},
 
1554
                        waitUnitAgent{
 
1555
                                statusGetter: unitStatusGetter,
 
1556
                                status:       status.StatusUnknown,
 
1557
                        },
 
1558
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1559
                        verifyCharm{},
 
1560
                        addAction{
 
1561
                                name:   "snapshot",
 
1562
                                params: map[string]interface{}{"outfile": 2},
 
1563
                        },
 
1564
                        waitActionResults{[]actionResult{{
 
1565
                                name:    "snapshot",
 
1566
                                results: map[string]interface{}{},
 
1567
                                status:  params.ActionFailed,
 
1568
                                message: `cannot run "snapshot" action: validation failed: (root).outfile : must be of type string, given 2`,
 
1569
                        }}},
 
1570
                        waitUnitAgent{status: status.StatusIdle},
 
1571
                        waitUnitAgent{
 
1572
                                statusGetter: unitStatusGetter,
 
1573
                                status:       status.StatusUnknown,
 
1574
                        },
 
1575
                ), ut(
 
1576
                        "actions not defined in actions.yaml fail without causing a uniter error",
 
1577
                        createCharm{
 
1578
                                customize: func(c *gc.C, ctx *context, path string) {
 
1579
                                        ctx.writeAction(c, path, "snapshot")
 
1580
                                },
 
1581
                        },
 
1582
                        serveCharm{},
 
1583
                        ensureStateWorker{},
 
1584
                        createServiceAndUnit{},
 
1585
                        startUniter{},
 
1586
                        waitAddresses{},
 
1587
                        waitUnitAgent{status: status.StatusIdle},
 
1588
                        waitUnitAgent{
 
1589
                                statusGetter: unitStatusGetter,
 
1590
                                status:       status.StatusUnknown,
 
1591
                        },
 
1592
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1593
                        verifyCharm{},
 
1594
                        addAction{"snapshot", map[string]interface{}{"outfile": "foo.bar"}},
 
1595
                        waitActionResults{[]actionResult{{
 
1596
                                name:    "snapshot",
 
1597
                                results: map[string]interface{}{},
 
1598
                                status:  params.ActionFailed,
 
1599
                                message: `cannot run "snapshot" action: not defined`,
 
1600
                        }}},
 
1601
                        waitUnitAgent{status: status.StatusIdle},
 
1602
                        waitUnitAgent{
 
1603
                                statusGetter: unitStatusGetter,
 
1604
                                status:       status.StatusUnknown,
 
1605
                        },
 
1606
                ), ut(
 
1607
                        "pending actions get consumed",
 
1608
                        createCharm{
 
1609
                                customize: func(c *gc.C, ctx *context, path string) {
 
1610
                                        ctx.writeAction(c, path, "action-log")
 
1611
                                        ctx.writeActionsYaml(c, path, "action-log")
 
1612
                                },
 
1613
                        },
 
1614
                        serveCharm{},
 
1615
                        ensureStateWorker{},
 
1616
                        createServiceAndUnit{},
 
1617
                        addAction{"action-log", nil},
 
1618
                        addAction{"action-log", nil},
 
1619
                        addAction{"action-log", nil},
 
1620
                        startUniter{},
 
1621
                        waitAddresses{},
 
1622
                        waitUnitAgent{status: status.StatusIdle},
 
1623
                        waitUnitAgent{
 
1624
                                statusGetter: unitStatusGetter,
 
1625
                                status:       status.StatusUnknown,
 
1626
                        },
 
1627
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1628
                        verifyCharm{},
 
1629
                        waitActionResults{[]actionResult{{
 
1630
                                name:    "action-log",
 
1631
                                results: map[string]interface{}{},
 
1632
                                status:  params.ActionCompleted,
 
1633
                        }, {
 
1634
                                name:    "action-log",
 
1635
                                results: map[string]interface{}{},
 
1636
                                status:  params.ActionCompleted,
 
1637
                        }, {
 
1638
                                name:    "action-log",
 
1639
                                results: map[string]interface{}{},
 
1640
                                status:  params.ActionCompleted,
 
1641
                        }}},
 
1642
                        waitUnitAgent{status: status.StatusIdle},
 
1643
                        waitUnitAgent{
 
1644
                                statusGetter: unitStatusGetter,
 
1645
                                status:       status.StatusUnknown,
 
1646
                        },
 
1647
                ), ut(
 
1648
                        "actions not implemented fail but are not errors",
 
1649
                        createCharm{
 
1650
                                customize: func(c *gc.C, ctx *context, path string) {
 
1651
                                        ctx.writeActionsYaml(c, path, "action-log")
 
1652
                                },
 
1653
                        },
 
1654
                        serveCharm{},
 
1655
                        ensureStateWorker{},
 
1656
                        createServiceAndUnit{},
 
1657
                        startUniter{},
 
1658
                        waitAddresses{},
 
1659
                        waitUnitAgent{status: status.StatusIdle},
 
1660
                        waitUnitAgent{
 
1661
                                statusGetter: unitStatusGetter,
 
1662
                                status:       status.StatusUnknown,
 
1663
                        },
 
1664
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1665
                        verifyCharm{},
 
1666
                        addAction{"action-log", nil},
 
1667
                        waitActionResults{[]actionResult{{
 
1668
                                name:    "action-log",
 
1669
                                results: map[string]interface{}{},
 
1670
                                status:  params.ActionFailed,
 
1671
                                message: `action not implemented on unit "u/0"`,
 
1672
                        }}},
 
1673
                        waitUnitAgent{status: status.StatusIdle},
 
1674
                        waitUnitAgent{
 
1675
                                statusGetter: unitStatusGetter,
 
1676
                                status:       status.StatusUnknown,
 
1677
                        },
 
1678
                ), ut(
 
1679
                        "actions may run from ModeHookError, but do not clear the error",
 
1680
                        startupErrorWithCustomCharm{
 
1681
                                badHook: "start",
 
1682
                                customize: func(c *gc.C, ctx *context, path string) {
 
1683
                                        ctx.writeAction(c, path, "action-log")
 
1684
                                        ctx.writeActionsYaml(c, path, "action-log")
 
1685
                                },
 
1686
                        },
 
1687
                        addAction{"action-log", nil},
 
1688
                        waitUnitAgent{
 
1689
                                statusGetter: unitStatusGetter,
 
1690
                                status:       status.StatusError,
 
1691
                                info:         `hook failed: "start"`,
 
1692
                                data: map[string]interface{}{
 
1693
                                        "hook": "start",
 
1694
                                },
 
1695
                        },
 
1696
                        waitActionResults{[]actionResult{{
 
1697
                                name:    "action-log",
 
1698
                                results: map[string]interface{}{},
 
1699
                                status:  params.ActionCompleted,
 
1700
                        }}},
 
1701
                        waitUnitAgent{
 
1702
                                statusGetter: unitStatusGetter,
 
1703
                                status:       status.StatusError,
 
1704
                                info:         `hook failed: "start"`,
 
1705
                                data:         map[string]interface{}{"hook": "start"},
 
1706
                        },
 
1707
                        verifyWaiting{},
 
1708
                        resolveError{state.ResolvedNoHooks},
 
1709
                        waitUnitAgent{status: status.StatusIdle},
 
1710
                        waitUnitAgent{
 
1711
                                statusGetter: unitStatusGetter,
 
1712
                                status:       status.StatusMaintenance,
 
1713
                                info:         "installing charm software",
 
1714
                        },
 
1715
                ),
 
1716
        })
 
1717
}
 
1718
 
 
1719
func (s *UniterSuite) TestUniterSubordinates(c *gc.C) {
 
1720
        s.runUniterTests(c, []uniterTest{
 
1721
                // Subordinates.
 
1722
                ut(
 
1723
                        "unit becomes dying while subordinates exist",
 
1724
                        quickStart{},
 
1725
                        addSubordinateRelation{"juju-info"},
 
1726
                        waitSubordinateExists{"logging/0"},
 
1727
                        unitDying,
 
1728
                        waitSubordinateDying{},
 
1729
                        waitHooks{"leader-settings-changed", "stop"},
 
1730
                        verifyWaiting{},
 
1731
                        removeSubordinate{},
 
1732
                        waitUniterDead{},
 
1733
                ), ut(
 
1734
                        "new subordinate becomes necessary while old one is dying",
 
1735
                        quickStart{},
 
1736
                        addSubordinateRelation{"juju-info"},
 
1737
                        waitSubordinateExists{"logging/0"},
 
1738
                        removeSubordinateRelation{"juju-info"},
 
1739
                        // The subordinate Uniter would usually set Dying in this situation.
 
1740
                        subordinateDying,
 
1741
                        addSubordinateRelation{"logging-dir"},
 
1742
                        verifyRunning{},
 
1743
                        removeSubordinate{},
 
1744
                        waitSubordinateExists{"logging/1"},
 
1745
                ),
 
1746
        })
 
1747
}
 
1748
 
 
1749
func (s *UniterSuite) TestSubordinateDying(c *gc.C) {
 
1750
        // Create a test context for later use.
 
1751
        ctx := &context{
 
1752
                s:                      s,
 
1753
                st:                     s.State,
 
1754
                path:                   filepath.Join(s.dataDir, "agents", "unit-u-0"),
 
1755
                dataDir:                s.dataDir,
 
1756
                charms:                 make(map[string][]byte),
 
1757
                updateStatusHookTicker: s.updateStatusHookTicker,
 
1758
                charmDirGuard:          &mockCharmDirGuard{},
 
1759
        }
 
1760
 
 
1761
        addControllerMachine(c, ctx.st)
 
1762
 
 
1763
        // Create the subordinate service.
 
1764
        dir := testcharms.Repo.ClonedDir(c.MkDir(), "logging")
 
1765
        curl, err := corecharm.ParseURL("cs:quantal/logging")
 
1766
        c.Assert(err, jc.ErrorIsNil)
 
1767
        curl = curl.WithRevision(dir.Revision())
 
1768
        step(c, ctx, addCharm{dir, curl})
 
1769
        ctx.svc = s.AddTestingService(c, "u", ctx.sch)
 
1770
 
 
1771
        // Create the principal service and add a relation.
 
1772
        wps := s.AddTestingService(c, "wordpress", s.AddTestingCharm(c, "wordpress"))
 
1773
        wpu, err := wps.AddUnit()
 
1774
        c.Assert(err, jc.ErrorIsNil)
 
1775
        eps, err := s.State.InferEndpoints("wordpress", "u")
 
1776
        c.Assert(err, jc.ErrorIsNil)
 
1777
        rel, err := s.State.AddRelation(eps...)
 
1778
        c.Assert(err, jc.ErrorIsNil)
 
1779
        assertAssignUnit(c, s.State, wpu)
 
1780
 
 
1781
        // Create the subordinate unit by entering scope as the principal.
 
1782
        wpru, err := rel.Unit(wpu)
 
1783
        c.Assert(err, jc.ErrorIsNil)
 
1784
        err = wpru.EnterScope(nil)
 
1785
        c.Assert(err, jc.ErrorIsNil)
 
1786
        ctx.unit, err = s.State.Unit("u/0")
 
1787
        c.Assert(err, jc.ErrorIsNil)
 
1788
        ctx.apiLogin(c)
 
1789
 
 
1790
        // Run the actual test.
 
1791
        ctx.run(c, []stepper{
 
1792
                serveCharm{},
 
1793
                startUniter{},
 
1794
                waitAddresses{},
 
1795
                custom{func(c *gc.C, ctx *context) {
 
1796
                        c.Assert(rel.Destroy(), gc.IsNil)
 
1797
                }},
 
1798
                waitUniterDead{},
 
1799
        })
 
1800
}
 
1801
 
 
1802
func (s *UniterSuite) TestRebootDisabledInActions(c *gc.C) {
 
1803
        s.runUniterTests(c, []uniterTest{
 
1804
                ut(
 
1805
                        "test that juju-reboot disabled in actions",
 
1806
                        createCharm{
 
1807
                                customize: func(c *gc.C, ctx *context, path string) {
 
1808
                                        ctx.writeAction(c, path, "action-reboot")
 
1809
                                        ctx.writeActionsYaml(c, path, "action-reboot")
 
1810
                                },
 
1811
                        },
 
1812
                        serveCharm{},
 
1813
                        ensureStateWorker{},
 
1814
                        createServiceAndUnit{},
 
1815
                        addAction{"action-reboot", nil},
 
1816
                        startUniter{},
 
1817
                        waitAddresses{},
 
1818
                        waitUnitAgent{
 
1819
                                status: status.StatusIdle,
 
1820
                        },
 
1821
                        waitUnitAgent{
 
1822
                                statusGetter: unitStatusGetter,
 
1823
                                status:       status.StatusUnknown,
 
1824
                        },
 
1825
                        waitActionResults{[]actionResult{{
 
1826
                                name: "action-reboot",
 
1827
                                results: map[string]interface{}{
 
1828
                                        "reboot-delayed": "good",
 
1829
                                        "reboot-now":     "good",
 
1830
                                },
 
1831
                                status: params.ActionCompleted,
 
1832
                        }}},
 
1833
                )})
 
1834
}
 
1835
 
 
1836
func (s *UniterSuite) TestRebootFinishesHook(c *gc.C) {
 
1837
        s.runUniterTests(c, []uniterTest{
 
1838
                ut(
 
1839
                        "test that juju-reboot finishes hook, and reboots",
 
1840
                        createCharm{
 
1841
                                customize: func(c *gc.C, ctx *context, path string) {
 
1842
                                        hpath := filepath.Join(path, "hooks", "install")
 
1843
                                        ctx.writeExplicitHook(c, hpath, rebootHook)
 
1844
                                },
 
1845
                        },
 
1846
                        serveCharm{},
 
1847
                        ensureStateWorker{},
 
1848
                        createServiceAndUnit{},
 
1849
                        startUniter{},
 
1850
                        waitAddresses{},
 
1851
                        waitUniterDead{err: "machine needs to reboot"},
 
1852
                        waitHooks{"install"},
 
1853
                        startUniter{},
 
1854
                        waitUnitAgent{
 
1855
                                status: status.StatusIdle,
 
1856
                        },
 
1857
                        waitUnitAgent{
 
1858
                                statusGetter: unitStatusGetter,
 
1859
                                status:       status.StatusUnknown,
 
1860
                        },
 
1861
                        waitHooks{"leader-elected", "config-changed", "start"},
 
1862
                )})
 
1863
}
 
1864
 
 
1865
func (s *UniterSuite) TestRebootNowKillsHook(c *gc.C) {
 
1866
        s.runUniterTests(c, []uniterTest{
 
1867
                ut(
 
1868
                        "test that juju-reboot --now kills hook and exits",
 
1869
                        createCharm{
 
1870
                                customize: func(c *gc.C, ctx *context, path string) {
 
1871
                                        hpath := filepath.Join(path, "hooks", "install")
 
1872
                                        ctx.writeExplicitHook(c, hpath, rebootNowHook)
 
1873
                                },
 
1874
                        },
 
1875
                        serveCharm{},
 
1876
                        ensureStateWorker{},
 
1877
                        createServiceAndUnit{},
 
1878
                        startUniter{},
 
1879
                        waitAddresses{},
 
1880
                        waitUniterDead{err: "machine needs to reboot"},
 
1881
                        waitHooks{"install"},
 
1882
                        startUniter{},
 
1883
                        waitUnitAgent{
 
1884
                                status: status.StatusIdle,
 
1885
                        },
 
1886
                        waitUnitAgent{
 
1887
                                statusGetter: unitStatusGetter,
 
1888
                                status:       status.StatusUnknown,
 
1889
                        },
 
1890
                        waitHooks{"install", "leader-elected", "config-changed", "start"},
 
1891
                )})
 
1892
}
 
1893
 
 
1894
func (s *UniterSuite) TestRebootDisabledOnHookError(c *gc.C) {
 
1895
        s.runUniterTests(c, []uniterTest{
 
1896
                ut(
 
1897
                        "test juju-reboot will not happen if hook errors out",
 
1898
                        createCharm{
 
1899
                                customize: func(c *gc.C, ctx *context, path string) {
 
1900
                                        hpath := filepath.Join(path, "hooks", "install")
 
1901
                                        ctx.writeExplicitHook(c, hpath, badRebootHook)
 
1902
                                },
 
1903
                        },
 
1904
                        serveCharm{},
 
1905
                        ensureStateWorker{},
 
1906
                        createServiceAndUnit{},
 
1907
                        startUniter{},
 
1908
                        waitAddresses{},
 
1909
                        waitUnitAgent{
 
1910
                                statusGetter: unitStatusGetter,
 
1911
                                status:       status.StatusError,
 
1912
                                info:         fmt.Sprintf(`hook failed: "install"`),
 
1913
                        },
 
1914
                ),
 
1915
        })
 
1916
}
 
1917
 
 
1918
func (s *UniterSuite) TestJujuRunExecutionSerialized(c *gc.C) {
 
1919
        s.runUniterTests(c, []uniterTest{
 
1920
                ut(
 
1921
                        "hook failed status should stay around after juju run",
 
1922
                        createCharm{badHooks: []string{"config-changed"}},
 
1923
                        serveCharm{},
 
1924
                        createUniter{},
 
1925
                        waitUnitAgent{
 
1926
                                statusGetter: unitStatusGetter,
 
1927
                                status:       status.StatusError,
 
1928
                                info:         `hook failed: "config-changed"`,
 
1929
                                data: map[string]interface{}{
 
1930
                                        "hook": "config-changed",
 
1931
                                },
 
1932
                        },
 
1933
                        runCommands{"exit 0"},
 
1934
                        waitUnitAgent{
 
1935
                                statusGetter: unitStatusGetter,
 
1936
                                status:       status.StatusError,
 
1937
                                info:         `hook failed: "config-changed"`,
 
1938
                                data: map[string]interface{}{
 
1939
                                        "hook": "config-changed",
 
1940
                                },
 
1941
                        },
 
1942
                )})
 
1943
}
 
1944
 
 
1945
func (s *UniterSuite) TestRebootFromJujuRun(c *gc.C) {
 
1946
        //TODO(bogdanteleaga): Fix this on windows
 
1947
        if runtime.GOOS == "windows" {
 
1948
                c.Skip("bug 1403084: currently does not work on windows")
 
1949
        }
 
1950
        s.runUniterTests(c, []uniterTest{
 
1951
                ut(
 
1952
                        "test juju-reboot",
 
1953
                        quickStart{},
 
1954
                        runCommands{"juju-reboot"},
 
1955
                        waitUniterDead{err: "machine needs to reboot"},
 
1956
                        startUniter{},
 
1957
                        waitHooks{"config-changed"},
 
1958
                ), ut(
 
1959
                        "test juju-reboot with bad hook",
 
1960
                        startupError{"install"},
 
1961
                        runCommands{"juju-reboot"},
 
1962
                        waitUniterDead{err: "machine needs to reboot"},
 
1963
                        startUniter{},
 
1964
                        waitHooks{},
 
1965
                ), ut(
 
1966
                        "test juju-reboot --now",
 
1967
                        quickStart{},
 
1968
                        runCommands{"juju-reboot --now"},
 
1969
                        waitUniterDead{err: "machine needs to reboot"},
 
1970
                        startUniter{},
 
1971
                        waitHooks{"config-changed"},
 
1972
                ), ut(
 
1973
                        "test juju-reboot --now with bad hook",
 
1974
                        startupError{"install"},
 
1975
                        runCommands{"juju-reboot --now"},
 
1976
                        waitUniterDead{err: "machine needs to reboot"},
 
1977
                        startUniter{},
 
1978
                        waitHooks{},
 
1979
                ),
 
1980
        })
 
1981
}
 
1982
 
 
1983
func (s *UniterSuite) TestLeadership(c *gc.C) {
 
1984
        s.runUniterTests(c, []uniterTest{
 
1985
                ut(
 
1986
                        "hook tools when leader",
 
1987
                        quickStart{},
 
1988
                        runCommands{"leader-set foo=bar baz=qux"},
 
1989
                        verifyLeaderSettings{"foo": "bar", "baz": "qux"},
 
1990
                ), ut(
 
1991
                        "hook tools when not leader",
 
1992
                        quickStart{minion: true},
 
1993
                        runCommands{leadershipScript},
 
1994
                ), ut(
 
1995
                        "leader-elected triggers when elected",
 
1996
                        quickStart{minion: true},
 
1997
                        forceLeader{},
 
1998
                        waitHooks{"leader-elected"},
 
1999
                ), ut(
 
2000
                        "leader-settings-changed triggers when leader settings change",
 
2001
                        quickStart{minion: true},
 
2002
                        setLeaderSettings{"ping": "pong"},
 
2003
                        waitHooks{"leader-settings-changed"},
 
2004
                ), ut(
 
2005
                        "leader-settings-changed triggers when bounced",
 
2006
                        quickStart{minion: true},
 
2007
                        verifyRunning{minion: true},
 
2008
                ), ut(
 
2009
                        "leader-settings-changed triggers when deposed (while stopped)",
 
2010
                        quickStart{},
 
2011
                        stopUniter{},
 
2012
                        forceMinion{},
 
2013
                        verifyRunning{minion: true},
 
2014
                ),
 
2015
        })
 
2016
}
 
2017
 
 
2018
func (s *UniterSuite) TestLeadershipUnexpectedDepose(c *gc.C) {
 
2019
        s.runUniterTests(c, []uniterTest{
 
2020
                ut(
 
2021
                        // NOTE: this is a strange and ugly test, intended to detect what
 
2022
                        // *would* happen if the uniter suddenly failed to renew its lease;
 
2023
                        // it depends on an artificially shortened tracker refresh time to
 
2024
                        // run in a reasonable amount of time.
 
2025
                        "leader-settings-changed triggers when deposed (while running)",
 
2026
                        quickStart{},
 
2027
                        forceMinion{},
 
2028
                        waitHooks{"leader-settings-changed"},
 
2029
                ),
 
2030
        })
 
2031
}
 
2032
 
 
2033
func (s *UniterSuite) TestStorage(c *gc.C) {
 
2034
        // appendStorageMetadata customises the wordpress charm's metadata,
 
2035
        // adding a "wp-content" filesystem store. We do it here rather
 
2036
        // than in the charm itself to avoid modifying all of the other
 
2037
        // scenarios.
 
2038
        appendStorageMetadata := func(c *gc.C, ctx *context, path string) {
 
2039
                f, err := os.OpenFile(filepath.Join(path, "metadata.yaml"), os.O_RDWR|os.O_APPEND, 0644)
 
2040
                c.Assert(err, jc.ErrorIsNil)
 
2041
                defer func() {
 
2042
                        err := f.Close()
 
2043
                        c.Assert(err, jc.ErrorIsNil)
 
2044
                }()
 
2045
                _, err = io.WriteString(f, "storage:\n  wp-content:\n    type: filesystem\n")
 
2046
                c.Assert(err, jc.ErrorIsNil)
 
2047
        }
 
2048
        s.runUniterTests(c, []uniterTest{
 
2049
                ut(
 
2050
                        "test that storage-attached is called",
 
2051
                        createCharm{customize: appendStorageMetadata},
 
2052
                        serveCharm{},
 
2053
                        ensureStateWorker{},
 
2054
                        createServiceAndUnit{},
 
2055
                        provisionStorage{},
 
2056
                        startUniter{},
 
2057
                        waitAddresses{},
 
2058
                        waitHooks{"wp-content-storage-attached"},
 
2059
                        waitHooks(startupHooks(false)),
 
2060
                ), ut(
 
2061
                        "test that storage-detaching is called before stop",
 
2062
                        createCharm{customize: appendStorageMetadata},
 
2063
                        serveCharm{},
 
2064
                        ensureStateWorker{},
 
2065
                        createServiceAndUnit{},
 
2066
                        provisionStorage{},
 
2067
                        startUniter{},
 
2068
                        waitAddresses{},
 
2069
                        waitHooks{"wp-content-storage-attached"},
 
2070
                        waitHooks(startupHooks(false)),
 
2071
                        unitDying,
 
2072
                        waitHooks{"leader-settings-changed"},
 
2073
                        // "stop" hook is not called until storage is detached
 
2074
                        waitHooks{"wp-content-storage-detaching", "stop"},
 
2075
                        verifyStorageDetached{},
 
2076
                        waitUniterDead{},
 
2077
                ), ut(
 
2078
                        "test that storage-detaching is called only if previously attached",
 
2079
                        createCharm{customize: appendStorageMetadata},
 
2080
                        serveCharm{},
 
2081
                        ensureStateWorker{},
 
2082
                        createServiceAndUnit{},
 
2083
                        // provision and destroy the storage before the uniter starts,
 
2084
                        // to ensure it never sees the storage as attached
 
2085
                        provisionStorage{},
 
2086
                        destroyStorageAttachment{},
 
2087
                        startUniter{},
 
2088
                        waitHooks(startupHooks(false)),
 
2089
                        unitDying,
 
2090
                        // storage-detaching is not called because it was never attached
 
2091
                        waitHooks{"leader-settings-changed", "stop"},
 
2092
                        verifyStorageDetached{},
 
2093
                        waitUniterDead{},
 
2094
                ), ut(
 
2095
                        "test that delay-provisioned storage does not block forever",
 
2096
                        createCharm{customize: appendStorageMetadata},
 
2097
                        serveCharm{},
 
2098
                        ensureStateWorker{},
 
2099
                        createServiceAndUnit{},
 
2100
                        startUniter{},
 
2101
                        // no hooks should be run, as storage isn't provisioned
 
2102
                        waitHooks{},
 
2103
                        provisionStorage{},
 
2104
                        waitHooks{"wp-content-storage-attached"},
 
2105
                        waitHooks(startupHooks(false)),
 
2106
                ), ut(
 
2107
                        "test that unprovisioned storage does not block unit termination",
 
2108
                        createCharm{customize: appendStorageMetadata},
 
2109
                        serveCharm{},
 
2110
                        ensureStateWorker{},
 
2111
                        createServiceAndUnit{},
 
2112
                        unitDying,
 
2113
                        startUniter{},
 
2114
                        // no hooks should be run, and unit agent should terminate
 
2115
                        waitHooks{},
 
2116
                        waitUniterDead{},
 
2117
                ),
 
2118
                // TODO(axw) test that storage-attached is run for new
 
2119
                // storage attachments before upgrade-charm is run. This
 
2120
                // requires additions to state to add storage when a charm
 
2121
                // is upgraded.
 
2122
        })
 
2123
}
 
2124
 
 
2125
type mockExecutor struct {
 
2126
        operation.Executor
 
2127
}
 
2128
 
 
2129
func (m *mockExecutor) Run(op operation.Operation) error {
 
2130
        // want to allow charm unpacking to occur
 
2131
        if strings.HasPrefix(op.String(), "install") {
 
2132
                return m.Executor.Run(op)
 
2133
        }
 
2134
        // but hooks should error
 
2135
        return errors.New("some error occurred")
 
2136
}
 
2137
 
 
2138
func (s *UniterSuite) TestOperationErrorReported(c *gc.C) {
 
2139
        executorFunc := func(stateFilePath string, getInstallCharm func() (*corecharm.URL, error), acquireLock func() (mutex.Releaser, error)) (operation.Executor, error) {
 
2140
                e, err := operation.NewExecutor(stateFilePath, getInstallCharm, acquireLock)
 
2141
                c.Assert(err, jc.ErrorIsNil)
 
2142
                return &mockExecutor{e}, nil
 
2143
        }
 
2144
        s.runUniterTests(c, []uniterTest{
 
2145
                ut(
 
2146
                        "error running operations are reported",
 
2147
                        createCharm{},
 
2148
                        serveCharm{},
 
2149
                        createUniter{executorFunc: executorFunc},
 
2150
                        waitUnitAgent{
 
2151
                                status: status.StatusFailed,
 
2152
                                info:   "resolver loop error",
 
2153
                        },
 
2154
                        expectError{".*some error occurred.*"},
 
2155
                ),
 
2156
        })
 
2157
}