Example #1
0
func (s *MetricSuite) TestUnitMetricBatchesReturnsJustLocal(c *gc.C) {
	now := state.NowToTheSecond()
	m := state.Metric{"pings", "5", now}
	_, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)
	localMeteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "local:quantal/metered"})
	service := s.Factory.MakeService(c, &factory.ServiceParams{Name: "localmetered", Charm: localMeteredCharm})
	unit := s.Factory.MakeUnit(c, &factory.UnitParams{Service: service, SetCharmURL: true})
	_, err = s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: localMeteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     unit.UnitTag(),
		},
	)

	c.Assert(err, jc.ErrorIsNil)
	metricBatches, err := s.State.MetricBatchesForUnit("metered/0")
	c.Assert(metricBatches, gc.HasLen, 0)
	metricBatches, err = s.State.MetricBatchesForUnit("localmetered/0")
	c.Assert(metricBatches, gc.HasLen, 1)
}
Example #2
0
func (s *MetricSuite) TestCleanupMetrics(c *gc.C) {
	oldTime := time.Now().Add(-(time.Hour * 25))
	m := state.Metric{"pings", "5", oldTime}
	oldMetric1, err := s.unit.AddMetrics(utils.MustNewUUID().String(), oldTime, "", []state.Metric{m})
	c.Assert(err, jc.ErrorIsNil)
	oldMetric1.SetSent()

	oldMetric2, err := s.unit.AddMetrics(utils.MustNewUUID().String(), oldTime, "", []state.Metric{m})
	c.Assert(err, jc.ErrorIsNil)
	oldMetric2.SetSent()

	now := time.Now()
	m = state.Metric{"pings", "5", now}
	newMetric, err := s.unit.AddMetrics(utils.MustNewUUID().String(), now, "", []state.Metric{m})
	c.Assert(err, jc.ErrorIsNil)
	newMetric.SetSent()
	err = s.State.CleanupOldMetrics()
	c.Assert(err, jc.ErrorIsNil)

	_, err = s.State.MetricBatch(newMetric.UUID())
	c.Assert(err, jc.ErrorIsNil)

	_, err = s.State.MetricBatch(oldMetric1.UUID())
	c.Assert(err, jc.Satisfies, errors.IsNotFound)

	_, err = s.State.MetricBatch(oldMetric2.UUID())
	c.Assert(err, jc.Satisfies, errors.IsNotFound)
}
Example #3
0
func (s *OpenSuite) TestUpdateEnvInfo(c *gc.C) {
	store := jujuclienttesting.NewMemStore()
	ctx := envtesting.BootstrapContext(c)
	cfg, err := config.New(config.UseDefaults, map[string]interface{}{
		"type":            "dummy",
		"name":            "admin-model",
		"controller-uuid": utils.MustNewUUID().String(),
		"uuid":            utils.MustNewUUID().String(),
	})
	c.Assert(err, jc.ErrorIsNil)
	_, err = environs.Prepare(ctx, store, environs.PrepareParams{
		ControllerName: "controller-name",
		BaseConfig:     cfg.AllAttrs(),
		CloudName:      "dummy",
	})
	c.Assert(err, jc.ErrorIsNil)

	foundController, err := store.ControllerByName("controller-name")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(foundController.ControllerUUID, gc.Equals, cfg.ControllerUUID())
	c.Assert(foundController.CACert, gc.Not(gc.Equals), "")
	foundModel, err := store.ModelByName("controller-name", "admin@local", "admin-model")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(foundModel, jc.DeepEquals, &jujuclient.ModelDetails{
		ModelUUID: cfg.UUID(),
	})
}
Example #4
0
func (s *MetricLocalCharmSuite) TestUnitMetricBatchesReturnsAllCharms(c *gc.C) {
	now := s.State.NowToTheSecond()
	m := state.Metric{"pings", "5", now}
	_, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)
	csMeteredCharm := s.Factory.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "cs:quantal/metered"})
	application := s.Factory.MakeApplication(c, &factory.ApplicationParams{Name: "csmetered", Charm: csMeteredCharm})
	unit := s.Factory.MakeUnit(c, &factory.UnitParams{Application: application, SetCharmURL: true})
	_, err = s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: csMeteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     unit.UnitTag(),
		},
	)

	c.Assert(err, jc.ErrorIsNil)
	metricBatches, err := s.State.MetricBatchesForUnit("metered/0")
	c.Assert(metricBatches, gc.HasLen, 1)
	metricBatches, err = s.State.MetricBatchesForUnit("csmetered/0")
	c.Assert(metricBatches, gc.HasLen, 1)
}
Example #5
0
func (s *actionsSuite) TestAuthAndActionFromTagFn(c *gc.C) {
	notFoundActionTag := names.NewActionTag(utils.MustNewUUID().String())

	authorizedActionTag := names.NewActionTag(utils.MustNewUUID().String())
	authorizedMachineTag := names.NewMachineTag("1")
	authorizedAction := fakeAction{name: "action1", receiver: authorizedMachineTag.Id()}

	unauthorizedActionTag := names.NewActionTag(utils.MustNewUUID().String())
	unauthorizedMachineTag := names.NewMachineTag("10")
	unauthorizedAction := fakeAction{name: "action2", receiver: unauthorizedMachineTag.Id()}

	invalidReceiverActionTag := names.NewActionTag(utils.MustNewUUID().String())
	invalidReceiverAction := fakeAction{name: "action2", receiver: "masterexploder"}

	canAccess := makeCanAccess(map[names.Tag]bool{
		authorizedMachineTag: true,
	})
	getActionByTag := makeGetActionByTag(map[names.ActionTag]state.Action{
		authorizedActionTag:      authorizedAction,
		unauthorizedActionTag:    unauthorizedAction,
		invalidReceiverActionTag: invalidReceiverAction,
	})
	tagFn := common.AuthAndActionFromTagFn(canAccess, getActionByTag)

	for i, test := range []struct {
		tag            string
		errString      string
		err            error
		expectedAction state.Action
	}{{
		tag:       "invalid-action-tag",
		errString: `"invalid-action-tag" is not a valid tag`,
	}, {
		tag:       notFoundActionTag.String(),
		errString: "action not found",
	}, {
		tag:       invalidReceiverActionTag.String(),
		errString: `invalid actionreceiver name "masterexploder"`,
	}, {
		tag: unauthorizedActionTag.String(),
		err: common.ErrPerm,
	}, {
		tag:            authorizedActionTag.String(),
		expectedAction: authorizedAction,
	}} {
		c.Logf("test %d", i)
		action, err := tagFn(test.tag)
		if test.errString != "" {
			c.Check(err, gc.ErrorMatches, test.errString)
			c.Check(action, gc.IsNil)
		} else if test.err != nil {
			c.Check(err, gc.Equals, test.err)
			c.Check(action, gc.IsNil)
		} else {
			c.Check(err, jc.ErrorIsNil)
			c.Check(action, gc.Equals, action)
		}
	}
}
Example #6
0
func (s *MetricSuite) TestMetricsAcrossEnvironments(c *gc.C) {
	now := state.NowToTheSecond().Add(-48 * time.Hour)
	m := state.Metric{"pings", "5", now}
	m1, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)

	st := s.Factory.MakeEnvironment(c, nil)
	defer st.Close()
	f := factory.NewFactory(st)
	meteredCharm := f.MakeCharm(c, &factory.CharmParams{Name: "metered", URL: "cs:quantal/metered"})
	service := f.MakeService(c, &factory.ServiceParams{Charm: meteredCharm})
	unit := f.MakeUnit(c, &factory.UnitParams{Service: service, SetCharmURL: true})
	m2, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)

	batches, err := s.State.MetricBatches()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(batches, gc.HasLen, 2)

	unsent, err := s.State.CountOfUnsentMetrics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(unsent, gc.Equals, 2)

	toSend, err := s.State.MetricsToSend(10)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(toSend, gc.HasLen, 2)

	err = m1.SetSent(time.Now().Add(-25 * time.Hour))
	c.Assert(err, jc.ErrorIsNil)
	err = m2.SetSent(time.Now().Add(-25 * time.Hour))
	c.Assert(err, jc.ErrorIsNil)

	sent, err := s.State.CountOfSentMetrics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(sent, gc.Equals, 2)

	err = s.State.CleanupOldMetrics()
	c.Assert(err, jc.ErrorIsNil)

	batches, err = s.State.MetricBatches()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(batches, gc.HasLen, 0)
}
Example #7
0
func (s *CrossModelMetricSuite) TestMetricsAcrossEnvironments(c *gc.C) {
	now := s.State.NowToTheSecond().Add(-48 * time.Hour)
	m := state.Metric{"pings", "5", now}
	m1, err := s.models[0].state.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.models[0].meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.models[0].unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)

	m2, err := s.models[1].state.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.models[1].meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.models[1].unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)

	batches, err := s.State.AllMetricBatches()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(batches, gc.HasLen, 2)

	unsent, err := s.models[0].state.CountOfUnsentMetrics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(unsent, gc.Equals, 1)

	toSend, err := s.models[0].state.MetricsToSend(10)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(toSend, gc.HasLen, 1)

	err = m1.SetSent(testing.NonZeroTime().Add(-25 * time.Hour))
	c.Assert(err, jc.ErrorIsNil)
	err = m2.SetSent(testing.NonZeroTime().Add(-25 * time.Hour))
	c.Assert(err, jc.ErrorIsNil)

	sent, err := s.models[0].state.CountOfSentMetrics()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(sent, gc.Equals, 1)

	err = s.models[0].state.CleanupOldMetrics()
	c.Assert(err, jc.ErrorIsNil)

	// The metric from model s.models[1] should still be in place.
	batches, err = s.State.AllMetricBatches()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(batches, gc.HasLen, 1)
}
Example #8
0
func (s *MetricSuite) TestCleanupMetrics(c *gc.C) {
	oldTime := time.Now().Add(-(time.Hour * 25))
	now := time.Now()
	m := state.Metric{"pings", "5", oldTime}
	oldMetric1, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)
	oldMetric1.SetSent(time.Now().Add(-25 * time.Hour))

	oldMetric2, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)
	oldMetric2.SetSent(time.Now().Add(-25 * time.Hour))

	m = state.Metric{"pings", "5", now}
	newMetric, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     utils.MustNewUUID().String(),
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{m},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)
	newMetric.SetSent(time.Now())
	err = s.State.CleanupOldMetrics()
	c.Assert(err, jc.ErrorIsNil)

	_, err = s.State.MetricBatch(newMetric.UUID())
	c.Assert(err, jc.ErrorIsNil)

	_, err = s.State.MetricBatch(oldMetric1.UUID())
	c.Assert(err, jc.Satisfies, errors.IsNotFound)

	_, err = s.State.MetricBatch(oldMetric2.UUID())
	c.Assert(err, jc.Satisfies, errors.IsNotFound)
}
Example #9
0
func (s *ClientSuite) TestMigrationStatus(c *gc.C) {
	mac, err := macaroon.New([]byte("secret"), "id", "location")
	c.Assert(err, jc.ErrorIsNil)
	macs := []macaroon.Slice{{mac}}
	macsJSON, err := json.Marshal(macs)
	c.Assert(err, jc.ErrorIsNil)

	modelUUID := utils.MustNewUUID().String()
	controllerUUID := utils.MustNewUUID().String()
	controllerTag := names.NewControllerTag(controllerUUID)
	timestamp := time.Date(2016, 6, 22, 16, 42, 44, 0, time.UTC)
	apiCaller := apitesting.APICallerFunc(func(_ string, _ int, _, _ string, _, result interface{}) error {
		out := result.(*params.MasterMigrationStatus)
		*out = params.MasterMigrationStatus{
			Spec: params.MigrationSpec{
				ModelTag: names.NewModelTag(modelUUID).String(),
				TargetInfo: params.MigrationTargetInfo{
					ControllerTag: controllerTag.String(),
					Addrs:         []string{"2.2.2.2:2"},
					CACert:        "cert",
					AuthTag:       names.NewUserTag("admin").String(),
					Password:      "******",
					Macaroons:     string(macsJSON),
				},
				ExternalControl: true,
			},
			MigrationId:      "id",
			Phase:            "IMPORT",
			PhaseChangedTime: timestamp,
		}
		return nil
	})
	client := migrationmaster.NewClient(apiCaller, nil)

	status, err := client.MigrationStatus()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(status, gc.DeepEquals, migration.MigrationStatus{
		MigrationId:      "id",
		ModelUUID:        modelUUID,
		Phase:            migration.IMPORT,
		PhaseChangedTime: timestamp,
		ExternalControl:  true,
		TargetInfo: migration.TargetInfo{
			ControllerTag: controllerTag,
			Addrs:         []string{"2.2.2.2:2"},
			CACert:        "cert",
			AuthTag:       names.NewUserTag("admin"),
			Password:      "******",
			Macaroons:     macs,
		},
	})
}
Example #10
0
func (s *MetricLocalCharmSuite) TestMetricsSorted(c *gc.C) {
	newUnit, err := s.application.AddUnit()
	c.Assert(err, jc.ErrorIsNil)

	t0 := time.Date(2016, time.August, 16, 16, 00, 35, 0, time.Local)
	var times []time.Time
	for i := 0; i < 3; i++ {
		times = append(times, t0.Add(time.Minute*time.Duration(i)))
	}

	for _, t := range times {
		_, err := s.State.AddMetrics(
			state.BatchParam{
				UUID:     utils.MustNewUUID().String(),
				Created:  t,
				CharmURL: s.meteredCharm.URL().String(),
				Metrics:  []state.Metric{{"pings", "5", t}},
				Unit:     s.unit.UnitTag(),
			},
		)
		c.Assert(err, jc.ErrorIsNil)

		_, err = s.State.AddMetrics(
			state.BatchParam{
				UUID:     utils.MustNewUUID().String(),
				Created:  t,
				CharmURL: s.meteredCharm.URL().String(),
				Metrics:  []state.Metric{{"pings", "10", t}},
				Unit:     newUnit.UnitTag(),
			},
		)
		c.Assert(err, jc.ErrorIsNil)
	}

	metricBatches, err := s.State.MetricBatchesForUnit("metered/0")
	c.Assert(err, jc.ErrorIsNil)
	assertMetricBatchesTimeAscending(c, metricBatches)

	metricBatches, err = s.State.MetricBatchesForUnit("metered/1")
	c.Assert(err, jc.ErrorIsNil)
	assertMetricBatchesTimeAscending(c, metricBatches)

	metricBatches, err = s.State.MetricBatchesForApplication("metered")
	c.Assert(err, jc.ErrorIsNil)
	assertMetricBatchesTimeAscending(c, metricBatches)

	metricBatches, err = s.State.MetricBatchesForModel()
	c.Assert(err, jc.ErrorIsNil)
	assertMetricBatchesTimeAscending(c, metricBatches)

}
Example #11
0
func (s *ModelConfigCreatorSuite) TestCreateModelForAdminUserCopiesSecrets(c *gc.C) {
	var err error
	s.baseConfig, err = s.baseConfig.Apply(coretesting.Attrs{
		"username":        "******",
		"password":        "******",
		"authorized-keys": "ssh-key",
	})
	c.Assert(err, jc.ErrorIsNil)
	newModelUUID := utils.MustNewUUID().String()
	newAttrs := coretesting.Attrs{
		"name":       "new-model",
		"additional": "value",
		"uuid":       newModelUUID,
	}
	cfg, err := s.newModelConfigAdmin(newAttrs)
	c.Assert(err, jc.ErrorIsNil)
	expectedCfg, err := config.New(config.UseDefaults, newAttrs)
	c.Assert(err, jc.ErrorIsNil)
	expected := expectedCfg.AllAttrs()
	c.Assert(expected["username"], gc.Equals, "user")
	c.Assert(expected["password"], gc.Equals, "password")
	c.Assert(expected["authorized-keys"], gc.Equals, "ssh-key")
	c.Assert(cfg.AllAttrs(), jc.DeepEquals, expected)

	fake.Stub.CheckCallNames(c,
		"RestrictedConfigAttributes",
		"PrepareForCreateEnvironment",
		"Validate",
	)
	validateCall := fake.Stub.Calls()[2]
	c.Assert(validateCall.Args, gc.HasLen, 2)
	c.Assert(validateCall.Args[0], gc.Equals, cfg)
	c.Assert(validateCall.Args[1], gc.IsNil)
}
Example #12
0
// MakeMetric makes a metric with specified params, filling in
// sane defaults for missing values.
// If params is not specified, defaults are used.
func (factory *Factory) MakeMetric(c *gc.C, params *MetricParams) *state.MetricBatch {
	now := time.Now().Round(time.Second).UTC()
	if params == nil {
		params = &MetricParams{}
	}
	if params.Unit == nil {
		meteredCharm := factory.MakeCharm(c, &CharmParams{Name: "metered", URL: "cs:quantal/metered"})
		meteredService := factory.MakeService(c, &ServiceParams{Charm: meteredCharm})
		params.Unit = factory.MakeUnit(c, &UnitParams{Service: meteredService, SetCharmURL: true})
	}
	if params.Time == nil {
		params.Time = &now
	}
	if params.Metrics == nil {
		params.Metrics = []state.Metric{{"pings", strconv.Itoa(uniqueInteger()), *params.Time}}
	}

	chURL, ok := params.Unit.CharmURL()
	c.Assert(ok, gc.Equals, true)

	metric, err := params.Unit.AddMetrics(utils.MustNewUUID().String(), *params.Time, chURL.String(), params.Metrics)
	c.Assert(err, jc.ErrorIsNil)
	if params.Sent {
		err := metric.SetSent()
		c.Assert(err, jc.ErrorIsNil)
	}
	return metric
}
Example #13
0
func (s *metricsAdderSuite) TestAddMetricsBatch(c *gc.C) {
	metrics := []params.Metric{{Key: "pings", Value: "5", Time: time.Now().UTC()}}
	uuid := utils.MustNewUUID().String()

	result, err := s.adder.AddMetricBatches(params.MetricBatchParams{
		Batches: []params.MetricBatchParam{{
			Tag: s.meteredUnit.Tag().String(),
			Batch: params.MetricBatch{
				UUID:     uuid,
				CharmURL: s.meteredCharm.URL().String(),
				Created:  time.Now(),
				Metrics:  metrics,
			}}}},
	)
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(result, gc.DeepEquals, params.ErrorResults{
		Results: []params.ErrorResult{{nil}},
	})

	batches, err := s.State.MetricBatches()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(batches, gc.HasLen, 1)
	batch := batches[0]
	c.Assert(batch.UUID(), gc.Equals, uuid)
	c.Assert(batch.CharmURL(), gc.Equals, s.meteredCharm.URL().String())
	c.Assert(batch.Unit(), gc.Equals, s.meteredUnit.Name())
	storedMetrics := batch.Metrics()
	c.Assert(storedMetrics, gc.HasLen, 1)
	c.Assert(storedMetrics[0].Key, gc.Equals, metrics[0].Key)
	c.Assert(storedMetrics[0].Value, gc.Equals, metrics[0].Value)
}
Example #14
0
func (s *MetricSuite) TestAddMetricDeadUnit(c *gc.C) {
	assertUnitDead(c, s.unit)
	now := state.NowToTheSecond()
	m := state.Metric{"pings", "5", now}
	_, err := s.unit.AddMetrics(utils.MustNewUUID().String(), now, "", []state.Metric{m})
	c.Assert(err, gc.ErrorMatches, `metered/0 not found`)
}
Example #15
0
func (s *MetricSuite) TestAddMetric(c *gc.C) {
	now := state.NowToTheSecond()
	envUUID := s.State.EnvironUUID()
	m := state.Metric{"pings", "5", now}
	metricBatch, err := s.unit.AddMetrics(utils.MustNewUUID().String(), now, "", []state.Metric{m})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(metricBatch.Unit(), gc.Equals, "metered/0")
	c.Assert(metricBatch.EnvUUID(), gc.Equals, envUUID)
	c.Assert(metricBatch.CharmURL(), gc.Equals, "cs:quantal/metered")
	c.Assert(metricBatch.Sent(), jc.IsFalse)
	c.Assert(metricBatch.Created(), gc.Equals, now)
	c.Assert(metricBatch.Metrics(), gc.HasLen, 1)

	metric := metricBatch.Metrics()[0]
	c.Assert(metric.Key, gc.Equals, "pings")
	c.Assert(metric.Value, gc.Equals, "5")
	c.Assert(metric.Time.Equal(now), jc.IsTrue)

	saved, err := s.State.MetricBatch(metricBatch.UUID())
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(saved.Unit(), gc.Equals, "metered/0")
	c.Assert(metricBatch.CharmURL(), gc.Equals, "cs:quantal/metered")
	c.Assert(saved.Sent(), jc.IsFalse)
	c.Assert(saved.Metrics(), gc.HasLen, 1)
	metric = saved.Metrics()[0]
	c.Assert(metric.Key, gc.Equals, "pings")
	c.Assert(metric.Value, gc.Equals, "5")
	c.Assert(metric.Time.Equal(now), jc.IsTrue)
}
Example #16
0
func (s *ClientSuite) TestRunningActionsResultError(c *gc.C) {
	tag := names.NewMachineTag(utils.MustNewUUID().String())
	expectedCalls := []jujutesting.StubCall{{
		"MachineActions.RunningActions",
		[]interface{}{"", params.Entities{
			Entities: []params.Entity{{Tag: tag.String()}},
		}},
	}}
	expectedErr := &params.Error{
		Message: "rigged",
		Code:    params.CodeNotAssigned,
	}
	var stub jujutesting.Stub

	apiCaller := apitesting.APICallerFunc(func(objType string, version int, id, request string, arg, result interface{}) error {
		stub.AddCall(objType+"."+request, id, arg)
		c.Check(result, gc.FitsTypeOf, &params.ActionsByReceivers{})
		*(result.(*params.ActionsByReceivers)) = params.ActionsByReceivers{
			Actions: []params.ActionsByReceiver{{
				Error: expectedErr,
			}},
		}
		return nil
	})

	client := machineactions.NewClient(apiCaller)
	action, err := client.RunningActions(tag)
	c.Assert(errors.Cause(err), gc.Equals, expectedErr)
	c.Assert(action, gc.IsNil)
	stub.CheckCalls(c, expectedCalls)
}
Example #17
0
// BenchmarkCleanupMetrics needs to add metrics each time over the cycle.
// Because of this the benchmark includes addmetric time
func (*BenchmarkSuite) BenchmarkCleanupMetrics(c *gc.C) {
	numberOfMetrics := 50
	var s ConnSuite
	s.SetUpSuite(c)
	defer s.TearDownSuite(c)
	s.SetUpTest(c)
	defer s.TearDownTest(c)
	oldTime := time.Now().Add(-(state.CleanupAge))
	charm := s.AddTestingCharm(c, "wordpress")
	svc := s.AddTestingService(c, "wordpress", charm)
	unit, err := svc.AddUnit()
	c.Assert(err, jc.ErrorIsNil)
	serviceCharmURL, _ := svc.CharmURL()
	err = unit.SetCharmURL(serviceCharmURL)
	c.Assert(err, jc.ErrorIsNil)
	c.ResetTimer()
	for i := 0; i < c.N; i++ {
		for i := 0; i < numberOfMetrics; i++ {
			m, err := unit.AddMetrics(utils.MustNewUUID().String(), oldTime, "", []state.Metric{{}})
			c.Assert(err, jc.ErrorIsNil)
			err = m.SetSent()
			c.Assert(err, jc.ErrorIsNil)
		}
		err := s.State.CleanupOldMetrics()
		c.Assert(err, jc.ErrorIsNil)
	}
}
Example #18
0
func benchmarkAddMetrics(metricsPerBatch, batches int, c *gc.C) {
	var s ConnSuite
	s.SetUpSuite(c)
	defer s.TearDownSuite(c)
	s.SetUpTest(c)
	defer s.TearDownTest(c)
	now := time.Now()
	metrics := make([]state.Metric, metricsPerBatch)
	for i := range metrics {
		metrics[i] = state.Metric{
			Key:   "metricKey",
			Value: "keyValue",
			Time:  now,
		}
	}
	charm := s.AddTestingCharm(c, "wordpress")
	svc := s.AddTestingService(c, "wordpress", charm)
	unit, err := svc.AddUnit()
	c.Assert(err, jc.ErrorIsNil)
	serviceCharmURL, _ := svc.CharmURL()
	err = unit.SetCharmURL(serviceCharmURL)
	c.Assert(err, jc.ErrorIsNil)
	c.ResetTimer()
	for i := 0; i < c.N; i++ {
		for n := 0; n < batches; n++ {
			_, err := unit.AddMetrics(utils.MustNewUUID().String(), now, "", metrics)
			c.Assert(err, jc.ErrorIsNil)
		}
	}
}
Example #19
0
func (s *MigrationSuite) SetUpTest(c *gc.C) {
	s.ConnSuite.SetUpTest(c)
	s.clock = jujutesting.NewClock(time.Now().Truncate(time.Second))
	err := s.State.SetClockForTesting(s.clock)
	c.Assert(err, jc.ErrorIsNil)

	// Create a hosted model to migrate.
	s.State2 = s.Factory.MakeModel(c, nil)
	s.AddCleanup(func(*gc.C) { s.State2.Close() })

	targetControllerTag := names.NewControllerTag(utils.MustNewUUID().String())

	mac, err := macaroon.New([]byte("secret"), "id", "location")
	c.Assert(err, jc.ErrorIsNil)

	// Plausible migration arguments to test with.
	s.stdSpec = state.MigrationSpec{
		InitiatedBy: names.NewUserTag("admin"),
		TargetInfo: migration.TargetInfo{
			ControllerTag: targetControllerTag,
			Addrs:         []string{"1.2.3.4:5555", "4.3.2.1:6666"},
			CACert:        "cert",
			AuthTag:       names.NewUserTag("user"),
			Password:      "******",
			Macaroons:     []macaroon.Slice{{mac}},
		},
	}
}
Example #20
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)
}
Example #21
0
func (s *metricsAdderIntegrationSuite) TestAddMetricBatches(c *gc.C) {
	batches := []params.MetricBatchParam{{
		Tag: s.unitTag.String(),
		Batch: params.MetricBatch{
			UUID:     utils.MustNewUUID().String(),
			CharmURL: "cs:quantal/metered",
			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)
	c.Assert(results, gc.HasLen, 1)
	result, ok := results[batches[0].Batch.UUID]
	c.Assert(ok, jc.IsTrue)
	c.Assert(result, gc.IsNil)

	stateBatches, err := s.State.AllMetricBatches()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(stateBatches, gc.HasLen, 1)
	c.Assert(stateBatches[0].CharmURL(), gc.Equals, batches[0].Batch.CharmURL)
	c.Assert(stateBatches[0].UUID(), gc.Equals, batches[0].Batch.UUID)
	c.Assert(stateBatches[0].ModelUUID(), gc.Equals, s.State.ModelUUID())
	c.Assert(stateBatches[0].Unit(), gc.Equals, s.unitTag.Id())
}
Example #22
0
func (s *OpenSuite) TestUpdateEnvInfo(c *gc.C) {
	store := jujuclienttesting.NewMemStore()
	ctx := envtesting.BootstrapContext(c)
	uuid := utils.MustNewUUID().String()
	cfg, err := config.New(config.UseDefaults, map[string]interface{}{
		"type": "dummy",
		"name": "admin-model",
		"uuid": uuid,
	})
	c.Assert(err, jc.ErrorIsNil)
	controllerCfg := testing.FakeControllerConfig()
	_, err = bootstrap.Prepare(ctx, store, bootstrap.PrepareParams{
		ControllerConfig: controllerCfg,
		ControllerName:   "controller-name",
		ModelConfig:      cfg.AllAttrs(),
		Cloud:            dummy.SampleCloudSpec(),
		AdminSecret:      "admin-secret",
	})
	c.Assert(err, jc.ErrorIsNil)

	foundController, err := store.ControllerByName("controller-name")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(foundController.ControllerUUID, gc.Not(gc.Equals), "")
	c.Assert(foundController.CACert, gc.Not(gc.Equals), "")
	foundModel, err := store.ModelByName("controller-name", "admin/admin-model")
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(foundModel, jc.DeepEquals, &jujuclient.ModelDetails{
		ModelUUID: cfg.UUID(),
	})
}
Example #23
0
func (s *ModelConfigCreatorSuite) TestCreateModelValidatesConfig(c *gc.C) {
	newModelUUID := utils.MustNewUUID().String()
	cfg, err := s.newModelConfig(coretesting.Attrs(
		s.baseConfig.AllAttrs(),
	).Merge(coretesting.Attrs{
		"name":       "new-model",
		"additional": "value",
		"uuid":       newModelUUID,
	}))
	c.Assert(err, jc.ErrorIsNil)
	expected := s.baseConfig.AllAttrs()
	expected["name"] = "new-model"
	expected["additional"] = "value"
	expected["uuid"] = newModelUUID
	c.Assert(cfg.AllAttrs(), jc.DeepEquals, expected)

	fake.Stub.CheckCallNames(c,
		"RestrictedConfigAttributes",
		"PrepareForCreateEnvironment",
		"Validate",
	)
	validateCall := fake.Stub.Calls()[2]
	c.Assert(validateCall.Args, gc.HasLen, 2)
	c.Assert(validateCall.Args[0], gc.Equals, cfg)
	c.Assert(validateCall.Args[1], gc.IsNil)
}
Example #24
0
func (s *ImportSuite) TestImportModel(c *gc.C) {
	model, err := s.State.Export()
	c.Check(err, jc.ErrorIsNil)

	// Update the config values in the exported model for different values for
	// "state-port", "api-port", and "ca-cert". Also give the model a new UUID
	// and name so we can import it nicely.
	uuid := utils.MustNewUUID().String()
	model.UpdateConfig(map[string]interface{}{
		"name": "new-model",
		"uuid": uuid,
	})

	bytes, err := description.Serialize(model)
	c.Check(err, jc.ErrorIsNil)

	dbModel, dbState, err := migration.ImportModel(s.State, bytes)
	c.Check(err, jc.ErrorIsNil)
	defer dbState.Close()

	dbConfig, err := dbModel.Config()
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(dbConfig.UUID(), gc.Equals, uuid)
	c.Assert(dbConfig.Name(), gc.Equals, "new-model")
}
Example #25
0
func (s *MetricSuite) TestAddMetricDuplicateUUID(c *gc.C) {
	now := state.NowToTheSecond()
	mUUID := utils.MustNewUUID().String()
	_, err := s.State.AddMetrics(
		state.BatchParam{
			UUID:     mUUID,
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{{"pings", "5", now}},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, jc.ErrorIsNil)

	_, err = s.State.AddMetrics(
		state.BatchParam{
			UUID:     mUUID,
			Created:  now,
			CharmURL: s.meteredCharm.URL().String(),
			Metrics:  []state.Metric{{"pings", "10", now}},
			Unit:     s.unit.UnitTag(),
		},
	)
	c.Assert(err, gc.ErrorMatches, "metrics batch .* already exists")
}
Example #26
0
func (s *unitMetricBatchesSuite) TestSendMetricBatchFail(c *gc.C) {
	var called bool
	uniter.PatchUnitResponse(s, s.apiUnit, "AddMetricBatches",
		func(response interface{}) error {
			called = true
			result := response.(*params.ErrorResults)
			result.Results = make([]params.ErrorResult, 1)
			result.Results[0].Error = common.ServerError(common.ErrPerm)
			return nil
		})
	metrics := []params.Metric{{"pings", "5", time.Now().UTC()}}
	uuid := utils.MustNewUUID().String()
	batch := params.MetricBatch{
		UUID:     uuid,
		CharmURL: s.charm.URL().String(),
		Created:  time.Now(),
		Metrics:  metrics,
	}

	results, err := s.apiUnit.AddMetricBatches([]params.MetricBatch{batch})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(results, gc.HasLen, 1)
	c.Assert(results[batch.UUID], gc.ErrorMatches, "permission denied")
	c.Assert(called, jc.IsTrue)
}
Example #27
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)
}
Example #28
0
func (s *unitMetricBatchesSuite) TestSendMetricBatchNotImplemented(c *gc.C) {
	var called bool
	uniter.PatchUnitFacadeCall(s, s.apiUnit, func(request string, args, response interface{}) error {
		switch request {
		case "AddMetricBatches":
			result := response.(*params.ErrorResults)
			result.Results = make([]params.ErrorResult, 1)
			return &params.Error{"not implemented", params.CodeNotImplemented}
		case "AddMetrics":
			called = true
			result := response.(*params.ErrorResults)
			result.Results = make([]params.ErrorResult, 1)
			return nil
		default:
			panic(fmt.Errorf("unexpected request %q received", request))
		}
	})

	metrics := []params.Metric{{"pings", "5", time.Now().UTC()}}
	uuid := utils.MustNewUUID().String()
	batch := params.MetricBatch{
		UUID:     uuid,
		CharmURL: s.charm.URL().String(),
		Created:  time.Now(),
		Metrics:  metrics,
	}

	results, err := s.apiUnit.AddMetricBatches([]params.MetricBatch{batch})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(called, jc.IsTrue)
	c.Assert(results, gc.HasLen, 1)
	c.Assert(results[batch.UUID], gc.IsNil)
}
Example #29
0
func (s *ImportSuite) TestImportModel(c *gc.C) {
	model, err := s.State.Export()
	c.Check(err, jc.ErrorIsNil)

	controllerConfig, err := s.State.ModelConfig()
	c.Check(err, jc.ErrorIsNil)

	// Update the config values in the exported model for different values for
	// "state-port", "api-port", and "ca-cert". Also give the model a new UUID
	// and name so we can import it nicely.
	model.UpdateConfig(map[string]interface{}{
		"name":       "new-model",
		"uuid":       utils.MustNewUUID().String(),
		"state-port": 12345,
		"api-port":   54321,
		"ca-cert":    "not really a cert",
	})

	bytes, err := description.Serialize(model)
	c.Check(err, jc.ErrorIsNil)

	dbModel, dbState, err := migration.ImportModel(s.State, bytes)
	c.Check(err, jc.ErrorIsNil)
	defer dbState.Close()

	dbConfig, err := dbModel.Config()
	c.Assert(err, jc.ErrorIsNil)
	attrs := dbConfig.AllAttrs()
	c.Assert(attrs["state-port"], gc.Equals, controllerConfig.StatePort())
	c.Assert(attrs["api-port"], gc.Equals, controllerConfig.APIPort())
	cacert, ok := controllerConfig.CACert()
	c.Assert(ok, jc.IsTrue)
	c.Assert(attrs["ca-cert"], gc.Equals, cacert)
	c.Assert(attrs["controller-uuid"], gc.Equals, controllerConfig.UUID())
}
Example #30
0
func (s *unitMetricBatchesSuite) TestSendMetricBatch(c *gc.C) {
	uuid := utils.MustNewUUID().String()
	now := time.Now().Round(time.Second).UTC()
	metrics := []params.Metric{{"pings", "5", now}}
	batch := params.MetricBatch{
		UUID:     uuid,
		CharmURL: s.charm.URL().String(),
		Created:  now,
		Metrics:  metrics,
	}

	results, err := s.apiUnit.AddMetricBatches([]params.MetricBatch{batch})
	c.Assert(err, jc.ErrorIsNil)
	c.Assert(results, gc.HasLen, 1)
	c.Assert(results[batch.UUID], gc.IsNil)

	batches, err := s.State.MetricBatches()
	c.Assert(err, gc.IsNil)
	c.Assert(batches, gc.HasLen, 1)
	c.Assert(batches[0].UUID(), gc.Equals, uuid)
	c.Assert(batches[0].Sent(), jc.IsFalse)
	c.Assert(batches[0].CharmURL(), gc.Equals, s.charm.URL().String())
	c.Assert(batches[0].Metrics(), gc.HasLen, 1)
	c.Assert(batches[0].Metrics()[0].Key, gc.Equals, "pings")
	c.Assert(batches[0].Metrics()[0].Key, gc.Equals, "pings")
	c.Assert(batches[0].Metrics()[0].Value, gc.Equals, "5")
}