コード例 #1
0
func TestWatch(t *testing.T) {
	isWatcherCalled = 0

	err := kva.Watch(testAlertsWatcher)
	require.NoError(t, err, "Failed to subscribe a watch function")

	raiseAlert1, err := kva.RaiseWithGenerateId(api.Alerts{Resource: api.ResourceType_CLUSTER, Severity: api.SeverityType_NOTIFY}, mockGenerateId)

	// Sleep for sometime so that we pass on some previous watch callbacks
	time.Sleep(time.Millisecond * 100)

	require.Equal(t, 1, isWatcherCalled, "Callback function not called")
	require.Equal(t, AlertCreateAction, watcherAction, "action mismatch for create")
	require.Equal(t, raiseAlert1.Id, watcherAlert.Id, "alert id mismatch")
	require.Equal(t, "alerts/cluster/"+strconv.FormatInt(raiseAlert1.Id, 10), watcherKey, "key mismatch")

	err = kva.Clear(api.ResourceType_CLUSTER, raiseAlert1.Id)

	// Sleep for sometime so that we pass on some previous watch callbacks
	time.Sleep(time.Millisecond * 100)

	require.Equal(t, AlertUpdateAction, watcherAction, "action mismatch for update")
	require.Equal(t, "alerts/cluster/"+strconv.FormatInt(raiseAlert1.Id, 10), watcherKey, "key mismatch")

	err = kva.Erase(api.ResourceType_CLUSTER, raiseAlert1.Id)

	// Sleep for sometime so that we pass on some previous watch callbacks
	time.Sleep(time.Millisecond * 100)

	require.Equal(t, AlertDeleteAction, watcherAction, "action mismatch for delete")
	require.Equal(t, "alerts/cluster/"+strconv.FormatInt(raiseAlert1.Id, 10), watcherKey, "key mismatch")
}
コード例 #2
0
// Watch on all alerts
func (kva *KvAlerts) Watch(alertsWatcherFunc AlertsWatcherFunc) error {

	prefix := alertsKey
	alertsWatcher = watcher{status: watchBootstrap, cb: alertsWatcherFunc, kvcb: kvdbWatch}

	if err := subscribeWatch(); err != nil {
		return err
	}

	// Subscribe for a watch is in a goroutine. Bootsrap by writing to the key and waiting for an update
	retries := 0
	kv := kvdb.Instance()
	for alertsWatcher.status == watchBootstrap {
		_, err := kv.Put(prefix+bootstrap, time.Now(), 1)
		if err != nil {
			return err
		}
		if alertsWatcher.status == watchBootstrap {
			retries++
			time.Sleep(time.Millisecond * 100)
		}
	}
	if alertsWatcher.status != watchReady {
		return fmt.Errorf("Failed to watch on %v", prefix)
	}

	return nil
}