本文整理汇总了Golang中github.com/hashicorp/consul/api.Client类的典型用法代码示例。如果您正苦于以下问题:Golang Client类的具体用法?Golang Client怎么用?Golang Client使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了Client类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: NewAgent
// NewAgent returns an initalized Agent.
func NewAgent(prefix string, c *consul.Client, d *docker.Client) *Agent {
return &Agent{
KV: c.KV(),
Docker: d,
Prefix: prefix,
}
}
示例2: getAttributes
func getAttributes(keys []string, overwriteAttributes map[string]interface{}) (map[string]interface{}, error) {
var attributes map[string]interface{}
var c *api.Client = util.Consul()
attributes = make(map[string]interface{})
// Get attributes from consul KVS
for _, key := range keys {
list, _, err := c.KV().List(key, &api.QueryOptions{})
if err != nil {
return nil, err
}
for _, kv := range list {
var a map[string]interface{}
if err := json.Unmarshal(kv.Value, &a); err != nil {
return nil, err
}
if err := mergo.MergeWithOverwrite(&attributes, a); err != nil {
return nil, errors.New(fmt.Sprintf("Failed to merge attributes(%v)", err))
}
}
}
// Overwrite some attributes by specified parameter in task.yml
if err := mergo.MergeWithOverwrite(&attributes, overwriteAttributes); err != nil {
return nil, err
}
return attributes, nil
}
示例3: NewConsulClient
func NewConsulClient(config *consulAPI.Config) (KVClient, error) {
var (
c *consulAPI.Client
err error
)
if config != nil {
c, err = consulAPI.NewClient(config)
} else {
c, err = consulAPI.NewClient(consulAPI.DefaultConfig())
}
if err != nil {
return nil, err
}
maxRetries := 30
i := 0
for {
leader, err := c.Status().Leader()
if err != nil || leader == "" {
log.Info("Waiting for consul client to be ready...")
time.Sleep(2 * time.Second)
i++
if i > maxRetries {
e := fmt.Errorf("Unable to contact consul: %s", err)
log.Error(e)
return nil, e
}
} else {
log.Info("Consul client ready")
break
}
}
return &ConsulClient{c}, nil
}
示例4: setupSemaphore
// setupSemaphore is used to setup a new Semaphore given the API client, key
// prefix, session name, and slot holder limit. If oneshot is true then we will
// set up for a single attempt at acquisition, using the given wait time. The
// retry parameter sets how many 500 errors the lock monitor will tolerate
// before giving up the semaphore.
func (c *LockCommand) setupSemaphore(client *api.Client, limit int, prefix, name string,
oneshot bool, wait time.Duration, retry int) (*LockUnlock, error) {
if c.verbose {
c.Ui.Info(fmt.Sprintf("Setting up semaphore (limit %d) at prefix: %s", limit, prefix))
}
opts := api.SemaphoreOptions{
Prefix: prefix,
Limit: limit,
SessionName: name,
MonitorRetries: retry,
MonitorRetryTime: defaultMonitorRetryTime,
}
if oneshot {
opts.SemaphoreTryOnce = true
opts.SemaphoreWaitTime = wait
}
s, err := client.SemaphoreOpts(&opts)
if err != nil {
return nil, err
}
lu := &LockUnlock{
lockFn: s.Acquire,
unlockFn: s.Release,
cleanupFn: s.Destroy,
inUseErr: api.ErrSemaphoreInUse,
rawOpts: &opts,
}
return lu, nil
}
示例5: setupLock
// setupLock is used to setup a new Lock given the API client, the key prefix to
// operate on, and an optional session name. If oneshot is true then we will set
// up for a single attempt at acquisition, using the given wait time. The retry
// parameter sets how many 500 errors the lock monitor will tolerate before
// giving up the lock.
func (c *LockCommand) setupLock(client *api.Client, prefix, name string,
oneshot bool, wait time.Duration, retry int) (*LockUnlock, error) {
// Use the DefaultSemaphoreKey extension, this way if a lock and
// semaphore are both used at the same prefix, we will get a conflict
// which we can report to the user.
key := path.Join(prefix, api.DefaultSemaphoreKey)
if c.verbose {
c.Ui.Info(fmt.Sprintf("Setting up lock at path: %s", key))
}
opts := api.LockOptions{
Key: key,
SessionName: name,
MonitorRetries: retry,
MonitorRetryTime: defaultMonitorRetryTime,
}
if oneshot {
opts.LockTryOnce = true
opts.LockWaitTime = wait
}
l, err := client.LockOpts(&opts)
if err != nil {
return nil, err
}
lu := &LockUnlock{
lockFn: l.Lock,
unlockFn: l.Unlock,
cleanupFn: l.Destroy,
inUseErr: api.ErrLockInUse,
rawOpts: &opts,
}
return lu, nil
}
示例6: writeToConsul
func writeToConsul(t *testing.T, prefix, key string, client *consulapi.Client) []byte {
token := os.Getenv("TOKEN")
dc := os.Getenv("DC")
if dc == "" {
dc = "dc1"
}
kv := client.KV()
writeOptions := &consulapi.WriteOptions{Token: token, Datacenter: dc}
// Delete all keys in the prefixed KV space
if _, err := kv.DeleteTree(prefix, writeOptions); err != nil {
t.Fatalf("err: %v", err)
}
// Put a test KV
encodedValue := make([]byte, base64.StdEncoding.EncodedLen(1024))
base64.StdEncoding.Encode(encodedValue, createRandomBytes(1024))
p := &consulapi.KVPair{Key: key, Flags: 42, Value: encodedValue}
if _, err := kv.Put(p, writeOptions); err != nil {
t.Fatalf("err: %v", err)
}
return encodedValue
}
示例7: NewWaiter
// NewWaiter creates a new Wait entry with a sensible default isReady function if
// nil is provided in its place.
func NewWaiter(client *api.Client, prefix string, minimumNodes int, isReady func(n *WaitNode) bool) *Wait {
if isReady == nil {
isReady = func(n *WaitNode) bool {
return true
}
}
nodeUpdateCh := make(chan WaitNodeUpdate, 2)
nodeReadyCh := make(chan WaitNode, 2)
allReadyCh := make(chan []WaitNode, 2)
return &Wait{
Prefix: prefix,
MinimumNodes: minimumNodes,
IsReady: isReady,
NodeUpdate: nodeUpdateCh,
NodeReady: nodeReadyCh,
AllReady: allReadyCh,
nodeUpdate: nodeUpdateCh,
nodeReady: nodeReadyCh,
allReady: allReadyCh,
client: client,
kv: client.KV(),
}
}
示例8: NewInstall
func NewInstall(consulClient *consul.Client, marathon *marathon.Marathon, mesos *mesos.Mesos, zkHosts []string) (*Install, error) {
apiConfig = map[string]interface{}{
"mantl": map[string]interface{}{
"zookeeper": map[string]interface{}{
"hosts": strings.Join(zkHosts, ","),
},
},
}
if mesos != nil {
mesosAuthRequired, err := mesos.RequiresAuthentication()
if err != nil {
return nil, err
}
mesosConfig := map[string]interface{}{
"principal": mesos.Principal,
"secret": mesos.Secret,
"secret-path": mesos.SecretPath,
"authentication-enabled": mesosAuthRequired,
}
mantlConfig := apiConfig["mantl"].(map[string]interface{})
mantlConfig["mesos"] = mesosConfig
}
zookeeper := zookeeper.NewZookeeper(zkHosts)
return &Install{consulClient, consulClient.KV(), marathon, mesos, zookeeper}, nil
}
示例9: serviceConfig
// serviceConfig constructs the config for all good instances of a single service.
func serviceConfig(client *api.Client, name string, passing map[string]bool, tagPrefix string) (config []string) {
if name == "" || len(passing) == 0 {
return nil
}
q := &api.QueryOptions{RequireConsistent: true}
svcs, _, err := client.Catalog().Service(name, "", q)
if err != nil {
log.Printf("[WARN] consul: Error getting catalog service %s. %v", name, err)
return nil
}
for _, svc := range svcs {
// check if the instance is in the list of instances
// which passed the health check
if _, ok := passing[svc.ServiceID]; !ok {
continue
}
for _, tag := range svc.ServiceTags {
if host, path, ok := parseURLPrefixTag(tag, tagPrefix); ok {
name, addr, port := svc.ServiceName, svc.ServiceAddress, svc.ServicePort
if runtime.GOOS == "darwin" && !strings.Contains(addr, ".") {
addr += ".local"
}
config = append(config, fmt.Sprintf("route add %s %s%s http://%s:%d/ tags %q", name, host, path, addr, port, strings.Join(svc.ServiceTags, ",")))
}
}
}
return config
}
示例10: removeSession
func removeSession(cl *api.Client, id string) {
session := cl.Session()
_, err := session.Destroy(id, nil)
if err != nil {
log.Printf("Error while destroying session: %v", err)
}
}
示例11: writeFileToConsul
func writeFileToConsul(t *testing.T, prefix, key string, file string, client *consulapi.Client) []byte {
token := os.Getenv("TOKEN")
dc := os.Getenv("DC")
if dc == "" {
dc = "dc1"
}
kv := client.KV()
writeOptions := &consulapi.WriteOptions{Token: token, Datacenter: dc}
// Delete all keys in the prefixed KV space
if _, err := kv.DeleteTree(prefix, writeOptions); err != nil {
t.Fatalf("err: %v", err)
}
fileBytes, err := ioutil.ReadFile(file)
if err != nil {
t.Fatalf("err: %v", err)
}
p := &consulapi.KVPair{Key: key, Flags: 42, Value: fileBytes}
if _, err := kv.Put(p, writeOptions); err != nil {
t.Fatalf("err: %v", err)
}
return fileBytes
}
示例12: getDC
// getDC is used to get the datacenter of the local agent
func getDC(client *consulapi.Client) (string, error) {
info, err := client.Agent().Self()
if err != nil {
return "", fmt.Errorf("Failed to get datacenter from Consul agent: %v", err)
}
dc := info["Config"]["Datacenter"].(string)
return dc, nil
}
示例13: putKV
func putKV(client *api.Client, key, value string, index uint64) (bool, error) {
p := &api.KVPair{Key: key[1:], Value: []byte(value), ModifyIndex: index}
ok, _, err := client.KV().CAS(p, nil)
if err != nil {
return false, err
}
return ok, nil
}
示例14: GetKVTree
/*
Get full tree under a key and optionally unmarshal.
Args:
client : Consul client
key : Key to query for.
output : Unmarshal data to this interface{} if non-nil
*/
func GetKVTree(client *api.Client, key string, output interface{}) (pairs api.KVPairs, err error) {
kv := client.KV()
pairs, _, err = kv.List(key, nil)
if output != nil {
err = Unmarshal(pairs, output)
}
return
}
示例15: Query
func (q *QueryCommand) Query(client *api.Client, tag string) []*api.CatalogService {
services, _, err := client.Catalog().Service(q.service, tag, &api.QueryOptions{AllowStale: true, RequireConsistent: false})
if err != nil {
panic(err)
return nil
}
return services
}