Esempio n. 1
0
func (s *storageSuite) TestUnitStorageAttachments(c *gc.C) {
	storageAttachmentIds := []params.StorageAttachmentId{{
		StorageTag: "storage-whatever-0",
		UnitTag:    "unit-mysql-0",
	}}

	var called bool
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		c.Check(objType, gc.Equals, "Uniter")
		c.Check(version, gc.Equals, 2)
		c.Check(id, gc.Equals, "")
		c.Check(request, gc.Equals, "UnitStorageAttachments")
		c.Check(arg, gc.DeepEquals, params.Entities{
			Entities: []params.Entity{{Tag: "unit-mysql-0"}},
		})
		c.Assert(result, gc.FitsTypeOf, &params.StorageAttachmentIdsResults{})
		*(result.(*params.StorageAttachmentIdsResults)) = params.StorageAttachmentIdsResults{
			Results: []params.StorageAttachmentIdsResult{{
				Result: params.StorageAttachmentIds{storageAttachmentIds},
			}},
		}
		called = true
		return nil
	})

	st := uniter.NewState(apiCaller, names.NewUnitTag("mysql/0"))
	attachmentIds, err := st.UnitStorageAttachments(names.NewUnitTag("mysql/0"))
	c.Check(err, jc.ErrorIsNil)
	c.Check(called, jc.IsTrue)
	c.Assert(attachmentIds, gc.DeepEquals, storageAttachmentIds)
}
Esempio n. 2
0
func (s *storageSuite) TestRemoveStorageAttachment(c *gc.C) {
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		c.Check(objType, gc.Equals, "Uniter")
		c.Check(version, gc.Equals, 2)
		c.Check(id, gc.Equals, "")
		c.Check(request, gc.Equals, "RemoveStorageAttachments")
		c.Check(arg, gc.DeepEquals, params.StorageAttachmentIds{
			Ids: []params.StorageAttachmentId{{
				StorageTag: "storage-data-0",
				UnitTag:    "unit-mysql-0",
			}},
		})
		c.Assert(result, gc.FitsTypeOf, &params.ErrorResults{})
		*(result.(*params.ErrorResults)) = params.ErrorResults{
			Results: []params.ErrorResult{{
				Error: &params.Error{Message: "yoink"},
			}},
		}
		return nil
	})

	st := uniter.NewState(apiCaller, names.NewUnitTag("mysql/0"))
	err := st.RemoveStorageAttachment(names.NewStorageTag("data/0"), names.NewUnitTag("mysql/0"))
	c.Check(err, gc.ErrorMatches, "yoink")
}
Esempio n. 3
0
func (s *storageSuite) TestWatchStorageAttachments(c *gc.C) {
	var called bool
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		c.Check(objType, gc.Equals, "Uniter")
		c.Check(version, gc.Equals, 2)
		c.Check(id, gc.Equals, "")
		c.Check(request, gc.Equals, "WatchStorageAttachments")
		c.Check(arg, gc.DeepEquals, params.StorageAttachmentIds{
			Ids: []params.StorageAttachmentId{{
				StorageTag: "storage-data-0",
				UnitTag:    "unit-mysql-0",
			}},
		})
		c.Assert(result, gc.FitsTypeOf, &params.NotifyWatchResults{})
		*(result.(*params.NotifyWatchResults)) = params.NotifyWatchResults{
			Results: []params.NotifyWatchResult{{
				Error: &params.Error{Message: "FAIL"},
			}},
		}
		called = true
		return nil
	})

	st := uniter.NewState(apiCaller, names.NewUnitTag("mysql/0"))
	_, err := st.WatchStorageAttachment(names.NewStorageTag("data/0"), names.NewUnitTag("mysql/0"))
	c.Check(err, gc.ErrorMatches, "FAIL")
	c.Check(called, jc.IsTrue)
}
Esempio n. 4
0
func (s *storageSuite) TestAPIErrors(c *gc.C) {
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		return errors.New("bad")
	})
	st := uniter.NewState(apiCaller, names.NewUnitTag("mysql/0"))
	_, err := st.UnitStorageAttachments(names.NewUnitTag("mysql/0"))
	c.Check(err, gc.ErrorMatches, "bad")
}
Esempio n. 5
0
func (s *storageSuite) TestRemoveStorageAttachments(c *gc.C) {
	setMock := func(st *mockStorageState, f func(s names.StorageTag, u names.UnitTag) error) {
		st.remove = f
	}

	unitTag0 := names.NewUnitTag("mysql/0")
	unitTag1 := names.NewUnitTag("mysql/1")
	storageTag0 := names.NewStorageTag("data/0")
	storageTag1 := names.NewStorageTag("data/1")

	resources := common.NewResources()
	getCanAccess := func() (common.AuthFunc, error) {
		return func(tag names.Tag) bool {
			return tag == unitTag0
		}, nil
	}

	state := &mockStorageState{}
	setMock(state, func(s names.StorageTag, u names.UnitTag) error {
		c.Assert(u, gc.DeepEquals, unitTag0)
		if s == storageTag1 {
			return errors.New("badness")
		}
		return nil
	})

	storage, err := uniter.NewStorageAPI(state, resources, getCanAccess)
	c.Assert(err, jc.ErrorIsNil)
	errors, err := storage.RemoveStorageAttachments(params.StorageAttachmentIds{
		Ids: []params.StorageAttachmentId{{
			StorageTag: storageTag0.String(),
			UnitTag:    unitTag0.String(),
		}, {
			StorageTag: storageTag1.String(),
			UnitTag:    unitTag0.String(),
		}, {
			StorageTag: storageTag0.String(),
			UnitTag:    unitTag1.String(),
		}, {
			StorageTag: unitTag0.String(), // oops
			UnitTag:    unitTag0.String(),
		}, {
			StorageTag: storageTag0.String(),
			UnitTag:    storageTag0.String(), // oops
		}},
	})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(errors, jc.DeepEquals, params.ErrorResults{
		Results: []params.ErrorResult{
			{nil},
			{&params.Error{Message: "badness"}},
			{&params.Error{Code: params.CodeUnauthorized, Message: "permission denied"}},
			{&params.Error{Message: `"unit-mysql-0" is not a valid storage tag`}},
			{&params.Error{Message: `"storage-data-0" is not a valid unit tag`}},
		},
	})
}
Esempio n. 6
0
func (s *unitSuite) TestUnit(c *gc.C) {
	apiUnitFoo, err := s.firewaller.Unit(names.NewUnitTag("foo/42"))
	c.Assert(err, gc.ErrorMatches, `unit "foo/42" not found`)
	c.Assert(err, jc.Satisfies, params.IsCodeNotFound)
	c.Assert(apiUnitFoo, gc.IsNil)

	apiUnit0, err := s.firewaller.Unit(s.units[0].Tag().(names.UnitTag))
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(apiUnit0, gc.NotNil)
	c.Assert(apiUnit0.Name(), gc.Equals, s.units[0].Name())
	c.Assert(apiUnit0.Tag(), gc.Equals, names.NewUnitTag(s.units[0].Name()))
}
Esempio n. 7
0
func (s *storageSuite) TestStorageAttachmentResultCountMismatch(c *gc.C) {
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		*(result.(*params.StorageAttachmentIdsResults)) = params.StorageAttachmentIdsResults{
			[]params.StorageAttachmentIdsResult{{}, {}},
		}
		return nil
	})
	st := uniter.NewState(apiCaller, names.NewUnitTag("mysql/0"))
	c.Assert(func() {
		st.UnitStorageAttachments(names.NewUnitTag("mysql/0"))
	}, gc.PanicMatches, "expected 1 result, got 2")
}
Esempio n. 8
0
func (s *RsyslogSuite) TestNamespace(c *gc.C) {
	st := s.st
	// set the rsyslog cert
	err := s.APIState.Client().EnvironmentSet(map[string]interface{}{"rsyslog-ca-cert": coretesting.CACert})
	c.Assert(err, jc.ErrorIsNil)

	// namespace only takes effect in filenames
	// for machine-0; all others assume isolation.
	s.testNamespace(c, st, names.NewMachineTag("0"), "", "25-juju.conf", *rsyslog.LogDir)
	s.testNamespace(c, st, names.NewMachineTag("0"), "mynamespace", "25-juju-mynamespace.conf", *rsyslog.LogDir+"-mynamespace")
	s.testNamespace(c, st, names.NewMachineTag("1"), "", "25-juju.conf", *rsyslog.LogDir)
	s.testNamespace(c, st, names.NewMachineTag("1"), "mynamespace", "25-juju.conf", *rsyslog.LogDir)
	s.testNamespace(c, st, names.NewUnitTag("myservice/0"), "", "26-juju-unit-myservice-0.conf", *rsyslog.LogDir)
	s.testNamespace(c, st, names.NewUnitTag("myservice/0"), "mynamespace", "26-juju-unit-myservice-0.conf", *rsyslog.LogDir)
}
Esempio n. 9
0
func (testsuite) TestHandle(c *gc.C) {
	f := &fakeAPI{}
	ua := unitAssignerHandler{api: f}
	ids := []string{"foo/0", "bar/0"}
	err := ua.Handle(nil, ids)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(f.assignTags, gc.DeepEquals, []names.UnitTag{
		names.NewUnitTag("foo/0"),
		names.NewUnitTag("bar/0"),
	})

	f.err = errors.New("boo")
	err = ua.Handle(nil, ids)
	c.Assert(err, gc.Equals, f.err)
}
Esempio n. 10
0
func (s *PathsSuite) TestWorkerPathsWindows(c *gc.C) {
	s.PatchValue(&os.HostOS, func() os.OSType { return os.Windows })

	dataDir := c.MkDir()
	unitTag := names.NewUnitTag("some-service/323")
	worker := "some-worker"
	paths := uniter.NewWorkerPaths(dataDir, unitTag, worker)

	relData := relPathFunc(dataDir)
	relAgent := relPathFunc(relData("agents", "unit-some-service-323"))
	c.Assert(paths, jc.DeepEquals, uniter.Paths{
		ToolsDir: relData("tools/unit-some-service-323"),
		Runtime: uniter.RuntimePaths{
			JujuRunSocket:     `\\.\pipe\unit-some-service-323-some-worker-run`,
			JujucServerSocket: `\\.\pipe\unit-some-service-323-some-worker-agent`,
		},
		State: uniter.StatePaths{
			BaseDir:         relAgent(),
			CharmDir:        relAgent("charm"),
			OperationsFile:  relAgent("state", "uniter"),
			RelationsDir:    relAgent("state", "relations"),
			BundlesDir:      relAgent("state", "bundles"),
			DeployerDir:     relAgent("state", "deployer"),
			StorageDir:      relAgent("state", "storage"),
			MetricsSpoolDir: relAgent("state", "spool", "metrics"),
		},
	})
}
Esempio n. 11
0
// ReadSettings returns a map holding the settings of the unit with the
// supplied name within this relation. An error will be returned if the
// relation no longer exists, or if the unit's service is not part of the
// relation, or the settings are invalid; but mere non-existence of the
// unit is not grounds for an error, because the unit settings are
// guaranteed to persist for the lifetime of the relation, regardless
// of the lifetime of the unit.
func (ru *RelationUnit) ReadSettings(uname string) (params.RelationSettings, error) {
	if !names.IsValidUnit(uname) {
		return nil, errors.Errorf("%q is not a valid unit", uname)
	}
	tag := names.NewUnitTag(uname)
	var results params.RelationSettingsResults
	args := params.RelationUnitPairs{
		RelationUnitPairs: []params.RelationUnitPair{{
			Relation:   ru.relation.tag.String(),
			LocalUnit:  ru.unit.tag.String(),
			RemoteUnit: tag.String(),
		}},
	}
	err := ru.st.facade.FacadeCall("ReadRemoteSettings", args, &results)
	if err != nil {
		return nil, err
	}
	if len(results.Results) != 1 {
		return nil, fmt.Errorf("expected 1 result, got %d", len(results.Results))
	}
	result := results.Results[0]
	if result.Error != nil {
		return nil, result.Error
	}
	return result.Settings, nil
}
Esempio n. 12
0
func (s *metricsAdderSuite) TestAddMetricBatches(c *gc.C) {
	var called bool
	var callParams params.MetricBatchParams
	metricsadder.PatchFacadeCall(s, s.adder, func(request string, args, response interface{}) error {
		p, ok := args.(params.MetricBatchParams)
		c.Assert(ok, jc.IsTrue)
		callParams = p
		called = true
		c.Assert(request, gc.Equals, "AddMetricBatches")
		result := response.(*params.ErrorResults)
		result.Results = make([]params.ErrorResult, 1)
		return nil
	})

	batches := []params.MetricBatchParam{{
		Tag: names.NewUnitTag("test-unit/0").String(),
		Batch: params.MetricBatch{
			UUID:     utils.MustNewUUID().String(),
			CharmURL: "test-charm-url",
			Created:  time.Now(),
			Metrics:  []params.Metric{{Key: "pings", Value: "5", Time: time.Now().UTC()}},
		},
	}}

	_, err := s.adder.AddMetricBatches(batches)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(called, jc.IsTrue)
	c.Assert(callParams.Batches, gc.DeepEquals, batches)
}
Esempio n. 13
0
// Subordinates implements Unit.
func (u *unit) Subordinates() []names.UnitTag {
	var subordinates []names.UnitTag
	for _, s := range u.Subordinates_ {
		subordinates = append(subordinates, names.NewUnitTag(s))
	}
	return subordinates
}
Esempio n. 14
0
func (s *leadershipSuite) TestClaimLeadershipDeniedError(c *gc.C) {
	var ldrMgr stubLeadershipManager
	ldrMgr.ClaimLeadershipFn = func(sid, uid string, duration time.Duration) error {
		c.Check(sid, gc.Equals, StubServiceNm)
		c.Check(uid, gc.Equals, StubUnitNm)
		expectDuration := time.Duration(5.001 * float64(time.Second))
		checkDurationEquals(c, duration, expectDuration)
		return errors.Annotatef(leadership.ErrClaimDenied, "obfuscated")
	}

	ldrSvc := &leadershipService{LeadershipManager: &ldrMgr, authorizer: &stubAuthorizer{}}
	results, err := ldrSvc.ClaimLeadership(params.ClaimLeadershipBulkParams{
		Params: []params.ClaimLeadershipParams{
			{
				ServiceTag:      names.NewServiceTag(StubServiceNm).String(),
				UnitTag:         names.NewUnitTag(StubUnitNm).String(),
				DurationSeconds: 5.001,
			},
		},
	})

	c.Check(err, jc.ErrorIsNil)
	c.Assert(results.Results, gc.HasLen, 1)
	c.Check(results.Results[0].Error, jc.Satisfies, params.IsCodeLeadershipClaimDenied)
}
Esempio n. 15
0
func (s *storageSuite) TestWatchUnitStorageAttachments(c *gc.C) {
	resources := common.NewResources()
	getCanAccess := func() (common.AuthFunc, error) {
		return func(names.Tag) bool {
			return true
		}, nil
	}
	unitTag := names.NewUnitTag("mysql/0")
	watcher := &mockStringsWatcher{
		changes: make(chan []string, 1),
	}
	watcher.changes <- []string{"storage/0", "storage/1"}
	state := &mockStorageState{
		watchStorageAttachments: func(u names.UnitTag) state.StringsWatcher {
			c.Assert(u, gc.DeepEquals, unitTag)
			return watcher
		},
	}

	storage, err := uniter.NewStorageAPI(state, resources, getCanAccess)
	c.Assert(err, jc.ErrorIsNil)
	watches, err := storage.WatchUnitStorageAttachments(params.Entities{
		Entities: []params.Entity{{unitTag.String()}},
	})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(watches, gc.DeepEquals, params.StringsWatchResults{
		Results: []params.StringsWatchResult{{
			StringsWatcherId: "1",
			Changes:          []string{"storage/0", "storage/1"},
		}},
	})
	c.Assert(resources.Get("1"), gc.Equals, watcher)
}
Esempio n. 16
0
// changed ensures that the named unit is deployed, recalled, or removed, as
// indicated by its state.
func (d *Deployer) changed(unitName string) error {
	unitTag := names.NewUnitTag(unitName)
	// Determine unit life state, and whether we're responsible for it.
	logger.Infof("checking unit %q", unitName)
	var life params.Life
	unit, err := d.st.Unit(unitTag)
	if params.IsCodeNotFoundOrCodeUnauthorized(err) {
		life = params.Dead
	} else if err != nil {
		return err
	} else {
		life = unit.Life()
	}
	// Deployed units must be removed if they're Dead, or if the deployer
	// is no longer responsible for them.
	if d.deployed.Contains(unitName) {
		if life == params.Dead {
			if err := d.recall(unitName); err != nil {
				return err
			}
		}
	}
	// The only units that should be deployed are those that (1) we are responsible
	// for and (2) are Alive -- if we're responsible for a Dying unit that is not
	// yet deployed, we should remove it immediately rather than undergo the hassle
	// of deploying a unit agent purely so it can set itself to Dead.
	if !d.deployed.Contains(unitName) {
		if life == params.Alive {
			return d.deploy(unit)
		} else if unit != nil {
			return d.remove(unit)
		}
	}
	return nil
}
Esempio n. 17
0
// GetPrincipal returns the result of calling PrincipalName() and
// converting it to a tag, on each given unit.
func (u *UniterAPI) GetPrincipal(args params.Entities) (params.StringBoolResults, error) {
	result := params.StringBoolResults{
		Results: make([]params.StringBoolResult, len(args.Entities)),
	}
	canAccess, err := u.accessUnit()
	if err != nil {
		return params.StringBoolResults{}, err
	}
	for i, entity := range args.Entities {
		tag, err := names.ParseUnitTag(entity.Tag)
		if err != nil {
			result.Results[i].Error = common.ServerError(common.ErrPerm)
			continue
		}
		err = common.ErrPerm
		if canAccess(tag) {
			var unit *state.Unit
			unit, err = u.getUnit(tag)
			if err == nil {
				principal, ok := unit.PrincipalName()
				if principal != "" {
					result.Results[i].Result = names.NewUnitTag(principal).String()
				}
				result.Results[i].Ok = ok
			}
		}
		result.Results[i].Error = common.ServerError(err)
	}
	return result, nil
}
Esempio n. 18
0
func (s *retryStrategySuite) TestWatchRetryStrategyResultError(c *gc.C) {
	tag := names.NewUnitTag("wp/1")
	var called bool
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, response interface{}) error {
		called = true

		c.Check(objType, gc.Equals, "RetryStrategy")
		c.Check(version, gc.Equals, 0)
		c.Check(id, gc.Equals, "")
		c.Check(request, gc.Equals, "WatchRetryStrategy")
		c.Check(arg, gc.DeepEquals, params.Entities{
			Entities: []params.Entity{{Tag: tag.String()}},
		})
		c.Assert(response, gc.FitsTypeOf, &params.NotifyWatchResults{})
		result := response.(*params.NotifyWatchResults)
		result.Results = []params.NotifyWatchResult{{
			Error: &params.Error{
				Message: "rigged",
				Code:    params.CodeNotAssigned,
			},
		}}
		return nil
	})

	client := retrystrategy.NewClient(apiCaller)
	c.Assert(client, gc.NotNil)

	w, err := client.WatchRetryStrategy(tag)
	c.Assert(called, jc.IsTrue)
	c.Assert(err, gc.ErrorMatches, "rigged")
	c.Assert(w, gc.IsNil)
}
Esempio n. 19
0
func (s *leadershipSuite) TestClaimLeadershipTranslation(c *gc.C) {
	var ldrMgr stubLeadershipManager
	ldrMgr.ClaimLeadershipFn = func(sid, uid string, duration time.Duration) error {
		c.Check(sid, gc.Equals, StubServiceNm)
		c.Check(uid, gc.Equals, StubUnitNm)
		expectDuration := time.Duration(299.9 * float64(time.Second))
		checkDurationEquals(c, duration, expectDuration)
		return nil
	}

	ldrSvc := &leadershipService{LeadershipManager: &ldrMgr, authorizer: &stubAuthorizer{}}
	results, err := ldrSvc.ClaimLeadership(params.ClaimLeadershipBulkParams{
		Params: []params.ClaimLeadershipParams{
			{
				ServiceTag:      names.NewServiceTag(StubServiceNm).String(),
				UnitTag:         names.NewUnitTag(StubUnitNm).String(),
				DurationSeconds: 299.9,
			},
		},
	})

	c.Check(err, jc.ErrorIsNil)
	c.Assert(results.Results, gc.HasLen, 1)
	c.Check(results.Results[0].Error, gc.IsNil)
}
Esempio n. 20
0
func (s *retryStrategySuite) TestRetryStrategyMoreResults(c *gc.C) {
	tag := names.NewUnitTag("wp/1")
	var called bool
	apiCaller := testing.APICallerFunc(func(objType string, version int, id, request string, arg, response interface{}) error {
		called = true

		c.Check(objType, gc.Equals, "RetryStrategy")
		c.Check(version, gc.Equals, 0)
		c.Check(id, gc.Equals, "")
		c.Check(request, gc.Equals, "RetryStrategy")
		c.Check(arg, gc.DeepEquals, params.Entities{
			Entities: []params.Entity{{Tag: tag.String()}},
		})
		c.Assert(response, gc.FitsTypeOf, &params.RetryStrategyResults{})
		result := response.(*params.RetryStrategyResults)
		result.Results = make([]params.RetryStrategyResult, 2)
		return nil
	})

	client := retrystrategy.NewClient(apiCaller)
	c.Assert(client, gc.NotNil)

	retryStrategy, err := client.RetryStrategy(tag)
	c.Assert(called, jc.IsTrue)
	c.Assert(err, gc.ErrorMatches, "expected 1 result, got 2")
	c.Assert(retryStrategy, jc.DeepEquals, params.RetryStrategy{})
}
Esempio n. 21
0
func (st *State) checkCanUpgrade(currentVersion, newVersion string) error {
	matchCurrent := "^" + regexp.QuoteMeta(currentVersion) + "-"
	matchNew := "^" + regexp.QuoteMeta(newVersion) + "-"
	// Get all machines and units with a different or empty version.
	sel := bson.D{{"$or", []bson.D{
		{{"tools", bson.D{{"$exists", false}}}},
		{{"$and", []bson.D{
			{{"tools.version", bson.D{{"$not", bson.RegEx{matchCurrent, ""}}}}},
			{{"tools.version", bson.D{{"$not", bson.RegEx{matchNew, ""}}}}},
		}}},
	}}}
	var agentTags []string
	for _, collection := range []*mgo.Collection{st.machines, st.units} {
		var doc struct {
			Id string `bson:"_id"`
		}
		iter := collection.Find(sel).Select(bson.D{{"_id", 1}}).Iter()
		for iter.Next(&doc) {
			switch collection.Name {
			case "machines":
				agentTags = append(agentTags, names.NewMachineTag(doc.Id).String())
			case "units":
				agentTags = append(agentTags, names.NewUnitTag(doc.Id).String())
			}
		}
		if err := iter.Close(); err != nil {
			return err
		}
	}
	if len(agentTags) > 0 {
		return newVersionInconsistentError(version.MustParse(currentVersion), agentTags)
	}
	return nil
}
Esempio n. 22
0
func (s *watchStorageAttachmentSuite) SetUpTest(c *gc.C) {
	s.storageTag = names.NewStorageTag("osd-devices/0")
	s.machineTag = names.NewMachineTag("0")
	s.unitTag = names.NewUnitTag("ceph/0")
	s.storageInstance = &fakeStorageInstance{
		tag:   s.storageTag,
		owner: s.machineTag,
		kind:  state.StorageKindBlock,
	}
	s.volume = &fakeVolume{tag: names.NewVolumeTag("0")}
	s.volumeAttachmentWatcher = apiservertesting.NewFakeNotifyWatcher()
	s.volumeAttachmentWatcher.C <- struct{}{}
	s.blockDevicesWatcher = apiservertesting.NewFakeNotifyWatcher()
	s.blockDevicesWatcher.C <- struct{}{}
	s.storageAttachmentWatcher = apiservertesting.NewFakeNotifyWatcher()
	s.storageAttachmentWatcher.C <- struct{}{}
	s.st = &fakeStorage{
		storageInstance: func(tag names.StorageTag) (state.StorageInstance, error) {
			return s.storageInstance, nil
		},
		storageInstanceVolume: func(tag names.StorageTag) (state.Volume, error) {
			return s.volume, nil
		},
		watchVolumeAttachment: func(names.MachineTag, names.VolumeTag) state.NotifyWatcher {
			return s.volumeAttachmentWatcher
		},
		watchBlockDevices: func(names.MachineTag) state.NotifyWatcher {
			return s.blockDevicesWatcher
		},
		watchStorageAttachment: func(names.StorageTag, names.UnitTag) state.NotifyWatcher {
			return s.storageAttachmentWatcher
		},
	}
}
Esempio n. 23
0
func (s *metricsAdderSuite) TestAddMetricBatchesFails(c *gc.C) {
	var called bool
	metricsadder.PatchFacadeCall(s, s.adder, func(request string, args, response interface{}) error {
		_, ok := args.(params.MetricBatchParams)
		c.Assert(ok, jc.IsTrue)
		called = true
		c.Assert(request, gc.Equals, "AddMetricBatches")
		result := response.(*params.ErrorResults)
		result.Results = make([]params.ErrorResult, 1)
		result.Results[0].Error = common.ServerError(common.ErrPerm)
		return nil
	})

	batches := []params.MetricBatchParam{{
		Tag: names.NewUnitTag("test-unit/0").String(),
		Batch: params.MetricBatch{
			UUID:     utils.MustNewUUID().String(),
			CharmURL: "test-charm-url",
			Created:  time.Now(),
			Metrics:  []params.Metric{{Key: "pings", Value: "5", Time: time.Now().UTC()}},
		},
	}}

	results, err := s.adder.AddMetricBatches(batches)
	c.Assert(err, jc.ErrorIsNil)
	result, ok := results[batches[0].Batch.UUID]
	c.Assert(ok, jc.IsTrue)
	c.Assert(result.Error(), gc.Equals, "permission denied")
	c.Assert(called, jc.IsTrue)
}
Esempio n. 24
0
func (s *deployerSuite) TestUnit(c *gc.C) {
	// Try getting a missing unit and an invalid tag.
	unit, err := s.st.Unit(names.NewUnitTag("foo/42"))
	s.assertUnauthorized(c, err)
	c.Assert(unit, gc.IsNil)

	// Try getting a unit we're not responsible for.
	// First create a new machine and deploy another unit there.
	machine, err := s.State.AddMachine("quantal", state.JobHostUnits)
	c.Assert(err, gc.IsNil)
	principal1, err := s.service0.AddUnit()
	c.Assert(err, gc.IsNil)
	err = principal1.AssignToMachine(machine)
	c.Assert(err, gc.IsNil)
	unit, err = s.st.Unit(principal1.Tag().(names.UnitTag))
	s.assertUnauthorized(c, err)
	c.Assert(unit, gc.IsNil)

	// Get the principal and subordinate we're responsible for.
	unit, err = s.st.Unit(s.principal.Tag().(names.UnitTag))
	c.Assert(err, gc.IsNil)
	c.Assert(unit.Name(), gc.Equals, "mysql/0")
	unit, err = s.st.Unit(s.subordinate.Tag().(names.UnitTag))
	c.Assert(err, gc.IsNil)
	c.Assert(unit.Name(), gc.Equals, "logging/0")
}
Esempio n. 25
0
func newHookQueue(attached bool) storage.StorageHookQueue {
	return storage.NewStorageHookQueue(
		names.NewUnitTag("mysql/0"),
		names.NewStorageTag("data/0"),
		attached,
	)
}
Esempio n. 26
0
File: run.go Progetto: imoapps/juju
func (c *RunCommand) Init(args []string) error {
	// make sure we aren't in an existing hook context
	if contextId, err := getenv("JUJU_CONTEXT_ID"); err == nil && contextId != "" {
		return fmt.Errorf("juju-run cannot be called from within a hook, have context %q", contextId)
	}
	if !c.noContext {
		if len(args) < 1 {
			return fmt.Errorf("missing unit-name")
		}
		var unitName string
		unitName, args = args[0], args[1:]
		// If the command line param is a unit id (like service/2) we need to
		// change it to the unit tag as that is the format of the agent directory
		// on disk (unit-service-2).
		if names.IsValidUnit(unitName) {
			c.unit = names.NewUnitTag(unitName)
		} else {
			var err error
			c.unit, err = names.ParseUnitTag(unitName)
			if err != nil {
				return errors.Trace(err)
			}
		}
	}
	if len(args) < 1 {
		return fmt.Errorf("missing commands")
	}
	c.commands, args = args[0], args[1:]
	return cmd.CheckEmpty(args)
}
Esempio n. 27
0
func (s *modelManagerSuite) TestNewAPIRefusesNonClient(c *gc.C) {
	anAuthoriser := s.authoriser
	anAuthoriser.Tag = names.NewUnitTag("mysql/0")
	endPoint, err := modelmanager.NewModelManagerAPI(s.State, s.resources, anAuthoriser)
	c.Assert(endPoint, gc.IsNil)
	c.Assert(err, gc.ErrorMatches, "permission denied")
}
Esempio n. 28
0
func (s *metricsAdderSuite) TestNewMetricsAdderAPIRefusesNonAgent(c *gc.C) {
	tests := []struct {
		tag            names.Tag
		environManager bool
		expectedError  string
	}{
		// TODO(cmars): unit agent should get permission denied when callers are
		// moved to machine agent.
		{names.NewUnitTag("mysql/0"), false, ""},

		{names.NewLocalUserTag("admin"), true, "permission denied"},
		{names.NewMachineTag("0"), false, ""},
		{names.NewMachineTag("0"), true, ""},
	}
	for i, test := range tests {
		c.Logf("test %d", i)

		anAuthoriser := s.authorizer
		anAuthoriser.EnvironManager = test.environManager
		anAuthoriser.Tag = test.tag
		endPoint, err := metricsadder.NewMetricsAdderAPI(s.State, nil, anAuthoriser)
		if test.expectedError == "" {
			c.Assert(err, jc.ErrorIsNil)
			c.Assert(endPoint, gc.NotNil)
		} else {
			c.Assert(err, gc.ErrorMatches, test.expectedError)
			c.Assert(endPoint, gc.IsNil)
		}
	}
}
Esempio n. 29
0
func (s *PathsSuite) TestOther(c *gc.C) {
	s.PatchValue(&os.HostOS, func() os.OSType { return os.Unknown })

	dataDir := c.MkDir()
	unitTag := names.NewUnitTag("some-service/323")
	paths := uniter.NewPaths(dataDir, unitTag)

	relData := relPathFunc(dataDir)
	relAgent := relPathFunc(relData("agents", "unit-some-service-323"))
	c.Assert(paths, jc.DeepEquals, uniter.Paths{
		ToolsDir: relData("tools/unit-some-service-323"),
		Runtime: uniter.RuntimePaths{
			JujuRunSocket:     relAgent("run.socket"),
			JujucServerSocket: "@" + relAgent("agent.socket"),
		},
		State: uniter.StatePaths{
			BaseDir:         relAgent(),
			CharmDir:        relAgent("charm"),
			OperationsFile:  relAgent("state", "uniter"),
			RelationsDir:    relAgent("state", "relations"),
			BundlesDir:      relAgent("state", "bundles"),
			DeployerDir:     relAgent("state", "deployer"),
			StorageDir:      relAgent("state", "storage"),
			MetricsSpoolDir: relAgent("state", "spool", "metrics"),
		},
	})
}
Esempio n. 30
0
func (*volumesSuite) TestVolumeParamsStorageTags(c *gc.C) {
	volumeTag := names.NewVolumeTag("100")
	storageTag := names.NewStorageTag("mystore/0")
	unitTag := names.NewUnitTag("mysql/123")
	p, err := storagecommon.VolumeParams(
		&fakeVolume{tag: volumeTag, params: &state.VolumeParams{
			Pool: "loop", Size: 1024,
		}},
		&fakeStorageInstance{tag: storageTag, owner: unitTag},
		testing.CustomModelConfig(c, nil),
		&fakePoolManager{},
	)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(p, jc.DeepEquals, params.VolumeParams{
		VolumeTag: "volume-100",
		Provider:  "loop",
		Size:      1024,
		Tags: map[string]string{
			tags.JujuController:      testing.ModelTag.Id(),
			tags.JujuModel:           testing.ModelTag.Id(),
			tags.JujuStorageInstance: "mystore/0",
			tags.JujuStorageOwner:    "mysql/123",
		},
	})
}