本文整理汇总了Golang中github.com/youtube/vitess/go/vt/logutil.NewConsoleLogger函数的典型用法代码示例。如果您正苦于以下问题:Golang NewConsoleLogger函数的具体用法?Golang NewConsoleLogger怎么用?Golang NewConsoleLogger使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了NewConsoleLogger函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: ExecuteVtworkerCommand
// ExecuteVtworkerCommand is part of the vtworkerdatapb.VtworkerServer interface
func (s *VtworkerServer) ExecuteVtworkerCommand(args *vtworkerdatapb.ExecuteVtworkerCommandRequest, stream vtworkerservicepb.Vtworker_ExecuteVtworkerCommandServer) (err error) {
// Please note that this panic handler catches only panics occuring in the code below.
// The actual execution of the vtworker command takes place in a new go routine
// (started in Instance.setAndStartWorker()) which has its own panic handler.
defer servenv.HandlePanic("vtworker", &err)
// Stream everything back what the Wrangler is logging.
logstream := logutil.NewCallbackLogger(func(e *logutilpb.Event) {
// If the client disconnects, we will just fail
// to send the log events, but won't interrupt
// the command.
stream.Send(&vtworkerdatapb.ExecuteVtworkerCommandResponse{
Event: e,
})
})
// Let the Wrangler also log everything to the console (and thereby
// effectively to a logfile) to make sure that any information or errors
// is preserved in the logs in case the RPC or vtworker crashes.
logger := logutil.NewTeeLogger(logstream, logutil.NewConsoleLogger())
// create the wrangler
wr := s.wi.CreateWrangler(logger)
// execute the command
worker, done, err := s.wi.RunCommand(args.Args, wr, false /*runFromCli*/)
if err == nil && worker != nil && done != nil {
err = s.wi.WaitForCommand(worker, done)
}
return err
}
示例2: runCommand
func runCommand(args []string) {
wrk := commandWorker(wr, args)
done, err := setAndStartWorker(wrk, logutil.NewConsoleLogger())
if err != nil {
log.Fatalf("Cannot set worker: %v", err)
}
// a go routine displays the status every second
go func() {
timer := time.Tick(*commandDisplayInterval)
for {
select {
case <-done:
log.Infof("Command is done:")
log.Info(wrk.StatusAsText())
if wrk.Error() != nil {
os.Exit(1)
}
os.Exit(0)
case <-timer:
log.Info(wrk.StatusAsText())
}
}
}()
}
示例3: ApplyTabletAction
func (ar *ActionRepository) ApplyTabletAction(actionName string, tabletAlias topo.TabletAlias, r *http.Request) *ActionResult {
result := &ActionResult{Name: actionName, Parameters: tabletAlias.String()}
action, ok := ar.tabletActions[actionName]
if !ok {
result.error("Unknown tablet action")
return result
}
// check the role
if action.role != "" {
if err := acl.CheckAccessHTTP(r, action.role); err != nil {
result.error("Access denied")
return result
}
}
// run the action
wr := wrangler.New(logutil.NewConsoleLogger(), ar.ts, wrangler.DefaultActionTimeout, actionnode.DefaultLockTimeout)
output, err := action.method(wr, tabletAlias, r)
if err != nil {
result.error(err.Error())
return result
}
result.Output = output
return result
}
示例4: TestSchemaManagerExecutorFail
func TestSchemaManagerExecutorFail(t *testing.T) {
sql := "create table test_table (pk int)"
controller := newFakeController([]string{sql}, false, false, false)
fakeTmc := newFakeTabletManagerClient()
fakeTmc.AddSchemaChange(sql, &tabletmanagerdatapb.SchemaChangeResult{
BeforeSchema: &tabletmanagerdatapb.SchemaDefinition{},
AfterSchema: &tabletmanagerdatapb.SchemaDefinition{
DatabaseSchema: "CREATE DATABASE `{{.DatabaseName}}` /*!40100 DEFAULT CHARACTER SET utf8 */",
TableDefinitions: []*tabletmanagerdatapb.TableDefinition{
{
Name: "test_table",
Schema: sql,
Type: tmutils.TableBaseTable,
},
},
},
})
fakeTmc.AddSchemaDefinition("vt_test_keyspace", &tabletmanagerdatapb.SchemaDefinition{})
fakeTmc.EnableExecuteFetchAsDbaError = true
wr := wrangler.New(logutil.NewConsoleLogger(), newFakeTopo(), fakeTmc)
executor := NewTabletExecutor(wr, testWaitSlaveTimeout)
ctx := context.Background()
err := Run(ctx, controller, executor)
if err == nil {
t.Fatalf("schema change should fail")
}
}
示例5: TestEmergencyReparentShardMasterElectNotBest
// TestEmergencyReparentShardMasterElectNotBest tries to emergency reparent
// to a host that is not the latest in replication position.
func TestEmergencyReparentShardMasterElectNotBest(t *testing.T) {
ctx := context.Background()
ts := zktopo.NewTestServer(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient(), time.Second)
// Create a master, a couple good slaves
oldMaster := NewFakeTablet(t, wr, "cell1", 0, topo.TYPE_MASTER)
newMaster := NewFakeTablet(t, wr, "cell1", 1, topo.TYPE_REPLICA)
moreAdvancedSlave := NewFakeTablet(t, wr, "cell1", 2, topo.TYPE_REPLICA)
// new master
newMaster.FakeMysqlDaemon.Replicating = true
newMaster.FakeMysqlDaemon.CurrentMasterPosition = myproto.ReplicationPosition{
GTIDSet: myproto.MariadbGTID{
Domain: 2,
Server: 123,
Sequence: 456,
},
}
newMaster.FakeMysqlDaemon.ExpectedExecuteSuperQueryList = []string{
"STOP SLAVE",
}
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// old master, will be scrapped
oldMaster.StartActionLoop(t, wr)
defer oldMaster.StopActionLoop(t)
// more advanced slave
moreAdvancedSlave.FakeMysqlDaemon.Replicating = true
moreAdvancedSlave.FakeMysqlDaemon.CurrentMasterPosition = myproto.ReplicationPosition{
GTIDSet: myproto.MariadbGTID{
Domain: 2,
Server: 123,
Sequence: 457,
},
}
moreAdvancedSlave.FakeMysqlDaemon.ExpectedExecuteSuperQueryList = []string{
"STOP SLAVE",
}
moreAdvancedSlave.StartActionLoop(t, wr)
defer moreAdvancedSlave.StopActionLoop(t)
// run EmergencyReparentShard
if err := wr.EmergencyReparentShard(ctx, newMaster.Tablet.Keyspace, newMaster.Tablet.Shard, newMaster.Tablet.Alias, 10*time.Second); err == nil || !strings.Contains(err.Error(), "is more advanced than master elect tablet") {
t.Fatalf("EmergencyReparentShard returned the wrong error: %v", err)
}
// check what was run
if err := newMaster.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("newMaster.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
if err := oldMaster.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("oldMaster.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
if err := moreAdvancedSlave.FakeMysqlDaemon.CheckSuperQueryList(); err != nil {
t.Fatalf("moreAdvancedSlave.FakeMysqlDaemon.CheckSuperQueryList failed: %v", err)
}
}
示例6: ApplyShardAction
// ApplyShardAction applies the provided action to the shard.
func (ar *ActionRepository) ApplyShardAction(ctx context.Context, actionName, keyspace, shard string, r *http.Request) *ActionResult {
// if the shard name contains a '-', we assume it's the
// name for a ranged based shard, so we lower case it.
if strings.Contains(shard, "-") {
shard = strings.ToLower(shard)
}
result := &ActionResult{Name: actionName, Parameters: keyspace + "/" + shard}
action, ok := ar.shardActions[actionName]
if !ok {
result.error("Unknown shard action")
return result
}
ctx, cancel := context.WithTimeout(ctx, *actionTimeout)
wr := wrangler.New(logutil.NewConsoleLogger(), ar.ts, tmclient.NewTabletManagerClient())
output, err := action(ctx, wr, keyspace, shard, r)
cancel()
if err != nil {
result.error(err.Error())
return result
}
result.Output = output
return result
}
示例7: RestoreFromBackup
// RestoreFromBackup deletes all local data and restores anew from the latest backup.
func (agent *ActionAgent) RestoreFromBackup(ctx context.Context, logger logutil.Logger) error {
if err := agent.lock(ctx); err != nil {
return err
}
defer agent.unlock()
tablet, err := agent.TopoServer.GetTablet(ctx, agent.TabletAlias)
if err != nil {
return err
}
if tablet.Type == topodatapb.TabletType_MASTER {
return fmt.Errorf("type MASTER cannot restore from backup, if you really need to do this, restart vttablet in replica mode")
}
// create the loggers: tee to console and source
l := logutil.NewTeeLogger(logutil.NewConsoleLogger(), logger)
// now we can run restore
err = agent.restoreDataLocked(ctx, l, true /* deleteBeforeRestore */)
// re-run health check to be sure to capture any replication delay
agent.runHealthCheckLocked()
return err
}
示例8: ApplyTabletAction
// ApplyTabletAction applies the provided action to the tablet.
func (ar *ActionRepository) ApplyTabletAction(ctx context.Context, actionName string, tabletAlias *topodatapb.TabletAlias, r *http.Request) *ActionResult {
result := &ActionResult{
Name: actionName,
Parameters: topoproto.TabletAliasString(tabletAlias),
}
action, ok := ar.tabletActions[actionName]
if !ok {
result.error("Unknown tablet action")
return result
}
// check the role
if action.role != "" {
if err := acl.CheckAccessHTTP(r, action.role); err != nil {
result.error("Access denied")
return result
}
}
// run the action
ctx, cancel := context.WithTimeout(ctx, *actionTimeout)
wr := wrangler.New(logutil.NewConsoleLogger(), ar.ts, tmclient.NewTabletManagerClient())
output, err := action.method(ctx, wr, tabletAlias, r)
cancel()
if err != nil {
result.error(err.Error())
return result
}
result.Output = output
return result
}
示例9: TestTabletExternallyReparentedFailedOldMaster
func TestTabletExternallyReparentedFailedOldMaster(t *testing.T) {
tabletmanager.SetReparentFlags(time.Minute /* finalizeTimeout */)
ctx := context.Background()
ts := zktopo.NewTestServer(t, []string{"cell1", "cell2"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient(), time.Second)
// Create an old master, a new master, and a good slave.
oldMaster := NewFakeTablet(t, wr, "cell1", 0, topo.TYPE_MASTER)
newMaster := NewFakeTablet(t, wr, "cell1", 1, topo.TYPE_REPLICA)
goodSlave := NewFakeTablet(t, wr, "cell1", 2, topo.TYPE_REPLICA)
// Reparent to a replica, and pretend the old master is not responding.
// On the elected master, we will respond to
// TabletActionSlaveWasPromoted
newMaster.StartActionLoop(t, wr)
defer newMaster.StopActionLoop(t)
// On the old master, we will only get a
// TabletActionSlaveWasRestarted call, let's just not
// respond to it at all
// On the good slave, we will respond to
// TabletActionSlaveWasRestarted.
goodSlave.StartActionLoop(t, wr)
defer goodSlave.StopActionLoop(t)
// The reparent should work as expected here
t.Logf("TabletExternallyReparented(new master) expecting success")
tmc := tmclient.NewTabletManagerClient()
ti, err := ts.GetTablet(ctx, newMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet failed: %v", err)
}
waitID := makeWaitID()
if err := tmc.TabletExternallyReparented(context.Background(), ti, waitID); err != nil {
t.Fatalf("TabletExternallyReparented(replica) failed: %v", err)
}
waitForExternalReparent(t, waitID)
// Now double-check the serving graph is good.
// Should only have one good replica left.
addrs, _, err := ts.GetEndPoints(ctx, "cell1", "test_keyspace", "0", topo.TYPE_REPLICA)
if err != nil {
t.Fatalf("GetEndPoints failed at the end: %v", err)
}
if len(addrs.Entries) != 1 {
t.Fatalf("GetEndPoints has too many entries: %v", addrs)
}
// check the old master was converted to spare
tablet, err := ts.GetTablet(ctx, oldMaster.Tablet.Alias)
if err != nil {
t.Fatalf("GetTablet(%v) failed: %v", oldMaster.Tablet.Alias, err)
}
if tablet.Type != topo.TYPE_SPARE {
t.Fatalf("old master should be spare but is: %v", tablet.Type)
}
}
示例10: main
func main() {
flag.Parse()
args := flag.Args()
installSignalHandlers()
servenv.Init()
defer servenv.Close()
ts := topo.GetServer()
defer topo.CloseServers()
// the logger will be replaced when we start a job
wr = wrangler.New(logutil.NewConsoleLogger(), ts, 30*time.Second, 30*time.Second)
if len(args) == 0 {
// interactive mode, initialize the web UI to chose a command
initInteractiveMode()
} else {
// single command mode, just runs it
runCommand(args)
}
initStatusHandling()
servenv.RunDefault()
}
示例11: main
func main() {
flag.Parse()
ctx, cancel := context.WithTimeout(context.Background(), *actionTimeout)
defer cancel()
sigChan := make(chan os.Signal, 1)
signal.Notify(sigChan, syscall.SIGTERM, syscall.SIGINT)
go func() {
s := <-sigChan
log.Errorf("Trying to cancel current command after receiving signal: %v", s)
cancel()
}()
logger := logutil.NewConsoleLogger()
err := vtworkerclient.RunCommandAndWait(
ctx, *server, flag.Args(),
func(e *logutilpb.Event) {
logutil.LogEvent(logger, e)
})
if err != nil {
log.Error(err)
os.Exit(1)
}
}
示例12: TestNewRestartableResultReader
// TestNewRestartableResultReader tests the correct error handling e.g.
// if the connection to a tablet fails due to a canceled context.
func TestNewRestartableResultReader(t *testing.T) {
wantErr := errors.New("restartable_result_reader_test.go: context canceled")
tabletconn.RegisterDialer("fake_dialer", func(tablet *topodatapb.Tablet, timeout time.Duration) (tabletconn.TabletConn, error) {
return nil, wantErr
})
protocol := flag.CommandLine.Lookup("tablet_protocol").Value.String()
flag.Set("tablet_protocol", "fake_dialer")
// Restore the previous flag value after the test.
defer flag.Set("tablet_protocol", protocol)
// Create dependencies e.g. a "singleTabletProvider" instance.
ts := zktestserver.New(t, []string{"cell1"})
wr := wrangler.New(logutil.NewConsoleLogger(), ts, tmclient.NewTabletManagerClient())
alias := &topodatapb.TabletAlias{
Cell: "cell1",
Uid: 1,
}
tablet := &topodatapb.Tablet{
Keyspace: "ks1",
Shard: "-80",
Alias: alias,
}
ctx := context.Background()
if err := ts.CreateTablet(ctx, tablet); err != nil {
t.Fatalf("CreateTablet failed: %v", err)
}
tp := newSingleTabletProvider(ctx, ts, alias)
_, err := NewRestartableResultReader(ctx, wr.Logger(), tp, nil /* td */, chunk{}, false)
if err == nil || !strings.Contains(err.Error(), wantErr.Error()) {
t.Fatalf("NewRestartableResultReader() should have failed because the context is canceled: %v", err)
}
}
示例13: ExecuteVtctlCommand
// ExecuteVtctlCommand is part of the pb.VtctlServer interface
func (s *VtctlServer) ExecuteVtctlCommand(args *pb.ExecuteVtctlCommandRequest, stream pbs.Vtctl_ExecuteVtctlCommandServer) (err error) {
defer servenv.HandlePanic("vtctl", &err)
// create a logger, send the result back to the caller
logstream := logutil.NewChannelLogger(10)
logger := logutil.NewTeeLogger(logstream, logutil.NewConsoleLogger())
// send logs to the caller
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for e := range logstream {
// Note we don't interrupt the loop here, as
// we still need to flush and finish the
// command, even if the channel to the client
// has been broken. We'll just keep trying.
stream.Send(&pb.ExecuteVtctlCommandResponse{
Event: logutil.LoggerEventToProto(&e),
})
}
wg.Done()
}()
// create the wrangler
wr := wrangler.New(logger, s.ts, tmclient.NewTabletManagerClient(), time.Duration(args.LockTimeout))
// execute the command
err = vtctl.RunCommand(stream.Context(), wr, args.Args)
// close the log channel, and wait for them all to be sent
close(logstream)
wg.Wait()
return err
}
示例14: MultiSnapshot
// MultiSnapshot takes a multi-part snapshot
// Should be called under RpcWrapLockAction.
func (agent *ActionAgent) MultiSnapshot(args *actionnode.MultiSnapshotArgs, logger logutil.Logger) (*actionnode.MultiSnapshotReply, error) {
tablet, err := agent.TopoServer.GetTablet(agent.TabletAlias)
if err != nil {
return nil, err
}
ki, err := agent.TopoServer.GetKeyspace(tablet.Keyspace)
if err != nil {
return nil, err
}
if tablet.Type != topo.TYPE_BACKUP {
return nil, fmt.Errorf("expected backup type, not %v", tablet.Type)
}
// create the loggers: tee to console and source
l := logutil.NewTeeLogger(logutil.NewConsoleLogger(), logger)
filenames, err := agent.Mysqld.CreateMultiSnapshot(l, args.KeyRanges, tablet.DbName(), ki.ShardingColumnName, ki.ShardingColumnType, tablet.Addr(), false, args.Concurrency, args.Tables, args.ExcludeTables, args.SkipSlaveRestart, args.MaximumFilesize, agent.hookExtraEnv())
if err != nil {
return nil, err
}
sr := &actionnode.MultiSnapshotReply{ManifestPaths: filenames}
if tablet.Parent.Uid == topo.NO_TABLET {
// If this is a master, this will be the new parent.
// FIXME(msolomon) this doens't work in hierarchical replication.
sr.ParentAlias = tablet.Alias
} else {
sr.ParentAlias = tablet.Parent
}
return sr, nil
}
示例15: ExecuteVtctlCommand
// ExecuteVtctlCommand is the server side method that will execute the query,
// and stream the results.
func (s *VtctlServer) ExecuteVtctlCommand(context context.Context, query *gorpcproto.ExecuteVtctlCommandArgs, sendReply func(interface{}) error) error {
// create a logger, send the result back to the caller
logstream := logutil.NewChannelLogger(10)
logger := logutil.NewTeeLogger(logstream, logutil.NewConsoleLogger())
// send logs to the caller
wg := sync.WaitGroup{}
wg.Add(1)
go func() {
for e := range logstream {
// Note we don't interrupt the loop here, as
// we still need to flush and finish the
// command, even if the channel to the client
// has been broken. We'll just keep trying.
sendReply(&e)
}
wg.Done()
}()
// create the wrangler
wr := wrangler.New(logger, s.ts, query.ActionTimeout, query.LockTimeout)
// execute the command
err := vtctl.RunCommand(wr, query.Args)
// close the log channel, and wait for them all to be sent
close(logstream)
wg.Wait()
return err
}