本文整理汇总了Golang中github.com/square/p2/pkg/labels.NewConsulApplicator函数的典型用法代码示例。如果您正苦于以下问题:Golang NewConsulApplicator函数的具体用法?Golang NewConsulApplicator怎么用?Golang NewConsulApplicator使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewConsulApplicator函数的11个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Golang代码示例。
示例1: NewConsul
func NewConsul(client consulutil.ConsulClient, retries int) *consulStore {
return &consulStore{
retries: retries,
applicator: labels.NewConsulApplicator(client, retries),
kv: client.KV(),
}
}
开发者ID:drcapulet,项目名称:p2,代码行数:7,代码来源:consul_store.go
示例2: TestInitializeReplicationWithManaged
func TestInitializeReplicationWithManaged(t *testing.T) {
replicator, _, f := testReplicatorAndServer(t)
defer f.Stop()
setupPreparers(f)
// Make one node appear to be managed by a replication controller
err := labels.NewConsulApplicator(f.Client, 1).SetLabel(
labels.POD,
path.Join(testNodes[0].String(), testPodId),
rc.RCIDLabel,
"controller GUID ignored",
)
if err != nil {
t.Fatal(err)
}
// Replication should fail because one node is managed
replication, _, err := replicator.InitializeReplication(false, false, 0, 0)
if err == nil {
t.Errorf("replication did not reject managed node")
replication.Cancel()
}
// Replication should succeed when explicitly ignoring the controllers
time.Sleep(50 * time.Millisecond)
replication, _, err = replicator.InitializeReplication(false, true, 0, 0)
if err != nil {
t.Fatal("replication could not ignore managed node:", err)
}
replication.Cancel()
}
开发者ID:rudle,项目名称:p2,代码行数:31,代码来源:replicator_test.go
示例3: main
func main() {
quitCh := make(chan struct{})
_, consulOpts, labeler := flags.ParseWithConsulOptions()
client := kp.NewConsulClient(consulOpts)
logger := logging.NewLogger(logrus.Fields{})
dsStore := dsstore.NewConsul(client, 3, &logger)
kpStore := kp.NewConsulStore(client)
healthChecker := checker.NewConsulHealthChecker(client)
sessions := make(chan string)
go consulutil.SessionManager(api.SessionEntry{
Name: SessionName(),
LockDelay: 5 * time.Second,
Behavior: api.SessionBehaviorDelete,
TTL: "15s",
}, client, sessions, quitCh, logger)
dsf := ds_farm.NewFarm(kpStore, dsStore, labeler, labels.NewConsulApplicator(client, 0), sessions, logger, nil, &healthChecker, 1*time.Second, *useCachePodMatches)
go func() {
// clear lock immediately on ctrl-C
signals := make(chan os.Signal, 1)
signal.Notify(signals, os.Interrupt)
<-signals
close(quitCh)
}()
dsf.Start(quitCh)
}
开发者ID:petertseng,项目名称:p2,代码行数:30,代码来源:main.go
示例4: NewP2RM
// NewP2RM is a constructor for the P2RM type. It will generate the necessary
// storage types based on its api.Client argument
func NewP2RM(client consulutil.ConsulClient, podName string, nodeName types.NodeName) *P2RM {
rm := &P2RM{}
rm.Client = client
rm.Store = kp.NewConsulStore(client)
rm.RCStore = rcstore.NewConsul(client, 5)
rm.Labeler = labels.NewConsulApplicator(client, 3)
rm.LabelID = path.Join(nodeName.String(), podName)
rm.PodName = podName
rm.NodeName = nodeName
return rm
}
开发者ID:rudle,项目名称:p2,代码行数:14,代码来源:main.go
示例5: watchPodClusters
func watchPodClusters(client consulutil.ConsulClient, applicator labels.ApplicatorWithoutWatches) {
logger := &logging.DefaultLogger
logger.Infoln("Beginning pod cluster watch")
pcStore := pcstore.NewConsul(client, applicator, labels.NewConsulApplicator(client, 0), logger)
quitCh := make(chan struct{})
go func() {
signalCh := make(chan os.Signal, 2)
signal.Notify(signalCh, syscall.SIGTERM, os.Interrupt)
received := <-signalCh
logger.Warnf("Received %v, shutting down", received)
close(quitCh)
}()
if err := pcStore.WatchAndSync(&printSyncer{logger}, quitCh); err != nil {
log.Fatalf("error watching pod cluster: %v", err)
}
}
开发者ID:petertseng,项目名称:p2,代码行数:18,代码来源:main.go
示例6: waitForPodLabeledWithRC
func waitForPodLabeledWithRC(selector klabels.Selector, rcID fields.ID) error {
client := kp.NewConsulClient(kp.Options{})
applicator := labels.NewConsulApplicator(client, 1)
// we have to label this hostname as being allowed to run tests
host, err := os.Hostname()
if err != nil {
return fmt.Errorf("Could not get hostname: %s", err)
}
err = applicator.SetLabel(labels.NODE, host, "test", "yes")
if err != nil {
return fmt.Errorf("Could not set node selector label on %s: %v", host, err)
}
quitCh := make(chan struct{})
defer close(quitCh)
watchCh := applicator.WatchMatches(selector, labels.POD, quitCh)
waitTime := time.After(30 * time.Second)
for {
select {
case <-waitTime:
return fmt.Errorf("Label selector %v wasn't matched before timeout: %s", selector, targetLogs())
case res, ok := <-watchCh:
if !ok {
return fmt.Errorf("Label selector watch unexpectedly terminated")
}
if len(res) > 1 {
return fmt.Errorf("Too many results found, should only have 1: %v", res)
}
if len(res) == 1 {
_, podID, err := labels.NodeAndPodIDFromPodLabel(res[0])
if err != nil {
return err
}
if podID.String() != "hello" {
return fmt.Errorf("Should have found the hello pod, instead found %s", podID)
}
return nil
}
}
}
}
开发者ID:petertseng,项目名称:p2,代码行数:42,代码来源:check.go
示例7: testReplicatorAndServer
func testReplicatorAndServer(t *testing.T) (Replicator, Store, consulutil.Fixture) {
active := 1
store, f := makeStore(t)
healthChecker := fake_checker.HappyHealthChecker(testNodes)
threshold := health.Passing
replicator, err := NewReplicator(
basicManifest(),
basicLogger(),
testNodes,
active,
store,
labels.NewConsulApplicator(f.Client, 1),
healthChecker,
threshold,
testLockMessage,
NoTimeout,
)
if err != nil {
t.Fatalf("Unable to initialize replicator: %s", err)
}
return replicator, store, f
}
开发者ID:petertseng,项目名称:p2,代码行数:24,代码来源:common_setup_test.go
示例8: ParseWithConsulOptions
func ParseWithConsulOptions() (string, kp.Options, labels.ApplicatorWithoutWatches) {
consulURL := kingpin.Flag("consul", "The hostname and port of a consul agent in the p2 cluster. Defaults to 0.0.0.0:8500.").String()
httpApplicatorURL := kingpin.Flag("http-applicator-url", "The URL of an labels.httpApplicator target, including the protocol and port. For example, https://consul-server.io:9999").URL()
token := kingpin.Flag("token", "The consul ACL token to use. Empty by default.").String()
tokenFile := kingpin.Flag("token-file", "The file containing the Consul ACL token").ExistingFile()
headers := kingpin.Flag("header", "An HTTP header to add to requests, in KEY=VALUE form. Can be specified multiple times.").StringMap()
https := kingpin.Flag("https", "Use HTTPS").Bool()
wait := kingpin.Flag("wait", "Maximum duration for Consul watches, before resetting and starting again.").Default("30s").Duration()
caFile := kingpin.Flag("tls-ca-file", "File containing the x509 PEM-encoded CA ").ExistingFile()
keyFile := kingpin.Flag("tls-key-file", "File containing the x509 PEM-encoded private key").ExistingFile()
certFile := kingpin.Flag("tls-cert-file", "File containing the x509 PEM-encoded public key certificate").ExistingFile()
cmd := kingpin.Parse()
if *tokenFile != "" {
tokenBytes, err := ioutil.ReadFile(*tokenFile)
if err != nil {
log.Fatalln(err)
}
*token = string(tokenBytes)
}
var transport http.RoundTripper
if *caFile != "" || *keyFile != "" || *certFile != "" {
tlsConfig, err := netutil.GetTLSConfig(*certFile, *keyFile, *caFile)
if err != nil {
log.Fatalln(err)
}
transport = &http.Transport{
TLSClientConfig: tlsConfig,
// same dialer as http.DefaultTransport
Dial: (&net.Dialer{
Timeout: http.DefaultClient.Timeout,
KeepAlive: http.DefaultClient.Timeout,
}).Dial,
}
} else {
transport = http.DefaultTransport
}
httpClient := netutil.NewHeaderClient(*headers, transport)
kpOpts := kp.Options{
Address: *consulURL,
Token: *token,
Client: httpClient,
HTTPS: *https,
WaitTime: *wait,
}
var applicator labels.ApplicatorWithoutWatches
var err error
if *httpApplicatorURL != nil {
applicator, err = labels.NewHTTPApplicator(httpClient, *httpApplicatorURL)
if err != nil {
log.Fatalln(err)
}
} else {
applicator = labels.NewConsulApplicator(kp.NewConsulClient(kpOpts), 0)
}
return cmd, kpOpts, applicator
}
开发者ID:petertseng,项目名称:p2,代码行数:61,代码来源:kingpin.go
示例9: main
func main() {
cmd, consulOpts := flags.ParseWithConsulOptions()
client := kp.NewConsulClient(consulOpts)
logger := logging.NewLogger(logrus.Fields{})
dsstore := dsstore.NewConsul(client, 3, &logger)
applicator := labels.NewConsulApplicator(client, 3)
switch cmd {
case CmdCreate:
minHealth, err := strconv.Atoi(*createMinHealth)
if err != nil {
log.Fatalf("Invalid value for minimum health, expected integer: %v", err)
}
name := ds_fields.ClusterName(*createName)
manifest, err := manifest.FromPath(*createManifest)
if err != nil {
log.Fatalf("%s", err)
}
podID := manifest.ID()
if *createTimeout <= time.Duration(0) {
log.Fatalf("Timeout must be a positive non-zero value, got '%v'", *createTimeout)
}
selectorString := *createSelector
if *createEverywhere {
selectorString = klabels.Everything().String()
} else if selectorString == "" {
selectorString = klabels.Nothing().String()
log.Fatal("Explicit everything selector not allowed, please use the --everwhere flag")
}
selector, err := parseNodeSelectorWithPrompt(klabels.Nothing(), selectorString, applicator)
if err != nil {
log.Fatalf("Error occurred: %v", err)
}
if err = confirmMinheathForSelector(minHealth, selector, applicator); err != nil {
log.Fatalf("Error occurred: %v", err)
}
ds, err := dsstore.Create(manifest, minHealth, name, selector, podID, *createTimeout)
if err != nil {
log.Fatalf("err: %v", err)
}
fmt.Printf("%v has been created in consul", ds.ID)
fmt.Println()
case CmdGet:
id := ds_fields.ID(*getID)
ds, _, err := dsstore.Get(id)
if err != nil {
log.Fatalf("err: %v", err)
}
bytes, err := json.Marshal(ds)
if err != nil {
logger.WithError(err).Fatalln("Unable to marshal daemon set as JSON")
}
fmt.Printf("%s", bytes)
case CmdList:
dsList, err := dsstore.List()
if err != nil {
log.Fatalf("err: %v", err)
}
podID := types.PodID(*listPod)
for _, ds := range dsList {
if *listPod == "" || podID == ds.PodID {
fmt.Printf("%s/%s:%s\n", ds.PodID, ds.Name, ds.ID)
}
}
case CmdEnable:
id := ds_fields.ID(*enableID)
mutator := func(ds ds_fields.DaemonSet) (ds_fields.DaemonSet, error) {
if !ds.Disabled {
return ds, util.Errorf("Daemon set has already been enabled")
}
ds.Disabled = false
return ds, nil
}
_, err := dsstore.MutateDS(id, mutator)
if err != nil {
log.Fatalf("err: %v", err)
}
fmt.Printf("The daemon set '%s' has been successfully enabled in consul", id.String())
fmt.Println()
case CmdDisable:
id := ds_fields.ID(*disableID)
mutator := func(ds ds_fields.DaemonSet) (ds_fields.DaemonSet, error) {
if ds.Disabled {
return ds, util.Errorf("Daemon set has already been disabled")
}
ds.Disabled = true
return ds, nil
//.........这里部分代码省略.........
开发者ID:rudle,项目名称:p2,代码行数:101,代码来源:main.go
示例10: main
func main() {
// Parse custom flags + standard Consul routing options
kingpin.Version(version.VERSION)
_, opts := flags.ParseWithConsulOptions()
// Set up the logger
logger := logging.NewLogger(logrus.Fields{})
logger.Logger.Formatter = new(logrus.TextFormatter)
if *logLevel != "" {
lv, err := logrus.ParseLevel(*logLevel)
if err != nil {
logger.WithErrorAndFields(err, logrus.Fields{"level": *logLevel}).
Fatalln("Could not parse log level")
}
logger.Logger.Level = lv
}
// Initialize the myriad of different storage components
httpClient := cleanhttp.DefaultClient()
client := kp.NewConsulClient(opts)
kpStore := kp.NewConsulStore(client)
rcStore := rcstore.NewConsul(client, RetryCount)
rollStore := rollstore.NewConsul(client, nil)
healthChecker := checker.NewConsulHealthChecker(client)
labeler := labels.NewConsulApplicator(client, RetryCount)
var sched scheduler.Scheduler
if *labelEndpoint != "" {
endpoint, err := url.Parse(*labelEndpoint)
if err != nil {
logger.WithErrorAndFields(err, logrus.Fields{
"url": *labelEndpoint,
}).Fatalln("Could not parse URL from label endpoint")
}
httpLabeler, err := labels.NewHttpApplicator(opts.Client, endpoint)
if err != nil {
logger.WithError(err).Fatalln("Could not create label applicator from endpoint")
}
sched = scheduler.NewApplicatorScheduler(httpLabeler)
} else {
sched = scheduler.NewApplicatorScheduler(labeler)
}
// Start acquiring sessions
sessions := make(chan string)
go consulutil.SessionManager(api.SessionEntry{
Name: SessionName(),
LockDelay: 5 * time.Second,
Behavior: api.SessionBehaviorDelete,
TTL: "15s",
}, client, sessions, nil, logger)
pub := stream.NewStringValuePublisher(sessions, "")
alerter := alerting.NewNop()
if *pagerdutyServiceKey != "" {
var err error
alerter, err = alerting.NewPagerduty(*pagerdutyServiceKey, httpClient)
if err != nil {
logger.WithError(err).Fatalln(
"Unable to initialize pagerduty alerter",
)
}
}
// Run the farms!
go rc.NewFarm(
kpStore,
rcStore,
sched,
labeler,
pub.Subscribe().Chan(),
logger,
klabels.Everything(),
alerter,
).Start(nil)
roll.NewFarm(
roll.UpdateFactory{
KPStore: kpStore,
RCStore: rcStore,
HealthChecker: healthChecker,
Labeler: labeler,
Scheduler: sched,
},
kpStore,
rollStore,
rcStore,
pub.Subscribe().Chan(),
logger,
labeler,
klabels.Everything(),
alerter,
).Start(nil)
}
开发者ID:drcapulet,项目名称:p2,代码行数:92,代码来源:main.go
示例11: main
func main() {
kingpin.Version(version.VERSION)
cmd, opts := flags.ParseWithConsulOptions()
logger := logging.NewLogger(logrus.Fields{})
logger.Logger.Formatter = &logrus.TextFormatter{}
if *logLevel != "" {
lv, err := logrus.ParseLevel(*logLevel)
if err != nil {
logger.WithErrorAndFields(err, logrus.Fields{"level": *logLevel}).Fatalln("Could not parse log level")
}
logger.Logger.Level = lv
}
client := kp.NewConsulClient(opts)
labeler := labels.NewConsulApplicator(client, 3)
sched := rc.NewApplicatorScheduler(labeler)
if *labelEndpoint != "" {
endpoint, err := url.Parse(*labelEndpoint)
if err != nil {
logging.DefaultLogger.WithErrorAndFields(err, logrus.Fields{
"url": *labelEndpoint,
}).Fatalln("Could not parse URL from label endpoint")
}
httpLabeler, err := labels.NewHttpApplicator(opts.Client, endpoint)
if err != nil {
logging.DefaultLogger.WithError(err).Fatalln("Could not create label applicator from endpoint")
}
sched = rc.NewApplicatorScheduler(httpLabeler)
}
rctl := RCtl{
baseClient: client,
rcs: rcstore.NewConsul(client, 3),
rls: rollstore.NewConsul(client),
kps: kp.NewConsulStore(client),
labeler: labeler,
sched: sched,
hcheck: checker.NewConsulHealthChecker(client),
logger: logger,
}
switch cmd {
case CMD_CREATE:
rctl.Create(*createManifest, *createNodeSel, *createPodLabels)
case CMD_DELETE:
rctl.Delete(*deleteID, *deleteForce)
case CMD_REPLICAS:
rctl.SetReplicas(*replicasID, *replicasNum)
case CMD_LIST:
rctl.List(*listJSON)
case CMD_GET:
rctl.Get(*getID, *getManifest)
case CMD_ENABLE:
rctl.Enable(*enableID)
case CMD_DISABLE:
rctl.Disable(*disableID)
case CMD_ROLL:
rctl.RollingUpdate(*rollOldID, *rollNewID, *rollWant, *rollNeed, *rollDelete)
case CMD_FARM:
rctl.Farm()
case CMD_SCHEDUP:
rctl.ScheduleUpdate(*schedupOldID, *schedupNewID, *schedupWant, *schedupNeed, *schedupDelete)
}
}
开发者ID:tomzhang,项目名称:p2,代码行数:64,代码来源:main.go
注:本文中的github.com/square/p2/pkg/labels.NewConsulApplicator函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论