Best Syzkaller code snippet using ipc.Leave
ipc.go
Source:ipc.go
...40)41const (42 handshakeCommand = "handshake"43 eventCommand = "event"44 forceLeaveCommand = "force-leave"45 joinCommand = "join"46 membersCommand = "members"47 membersFilteredCommand = "members-filtered"48 streamCommand = "stream"49 stopCommand = "stop"50 monitorCommand = "monitor"51 leaveCommand = "leave"52 installKeyCommand = "install-key"53 useKeyCommand = "use-key"54 removeKeyCommand = "remove-key"55 listKeysCommand = "list-keys"56 tagsCommand = "tags"57 queryCommand = "query"58 respondCommand = "respond"59 authCommand = "auth"60 statsCommand = "stats"61 getCoordinateCommand = "get-coordinate"62)63const (64 unsupportedCommand = "Unsupported command"65 unsupportedIPCVersion = "Unsupported IPC version"66 duplicateHandshake = "Handshake already performed"67 handshakeRequired = "Handshake required"68 monitorExists = "Monitor already exists"69 invalidFilter = "Invalid event filter"70 streamExists = "Stream with given sequence exists"71 invalidQueryID = "No pending queries matching ID"72 authRequired = "Authentication required"73 invalidAuthToken = "Invalid authentication token"74)75const (76 queryRecordAck = "ack"77 queryRecordResponse = "response"78 queryRecordDone = "done"79)80// Request header is sent before each request81type requestHeader struct {82 Command string83 Seq uint6484}85// Response header is sent before each response86type responseHeader struct {87 Seq uint6488 Error string89}90type handshakeRequest struct {91 Version int3292}93type authRequest struct {94 AuthKey string95}96type coordinateRequest struct {97 Node string98}99type coordinateResponse struct {100 Coord coordinate.Coordinate101 Ok bool102}103type eventRequest struct {104 Name string105 Payload []byte106 Coalesce bool107}108type forceLeaveRequest struct {109 Node string110 Prune bool111}112type joinRequest struct {113 Existing []string114 Replay bool115}116type joinResponse struct {117 Num int32118}119type membersFilteredRequest struct {120 Tags map[string]string121 Status string122 Name string123}124type membersResponse struct {125 Members []Member126}127type keyRequest struct {128 Key string129}130type keyResponse struct {131 Messages map[string]string132 Keys map[string]int133 NumNodes int134 NumErr int135 NumResp int136}137type monitorRequest struct {138 LogLevel string139}140type streamRequest struct {141 Type string142}143type stopRequest struct {144 Stop uint64145}146type tagsRequest struct {147 Tags map[string]string148 DeleteTags []string149}150type queryRequest struct {151 FilterNodes []string152 FilterTags map[string]string153 RequestAck bool154 RelayFactor uint8155 Timeout time.Duration156 Name string157 Payload []byte158}159type respondRequest struct {160 ID uint64161 Payload []byte162}163type queryRecord struct {164 Type string165 From string166 Payload []byte167}168type logRecord struct {169 Log string170}171type userEventRecord struct {172 Event string173 LTime serf.LamportTime174 Name string175 Payload []byte176 Coalesce bool177}178type queryEventRecord struct {179 Event string180 ID uint64 // ID is opaque to client, used to respond181 LTime serf.LamportTime182 Name string183 Payload []byte184}185type Member struct {186 Name string187 Addr net.IP188 Port uint16189 Tags map[string]string190 Status string191 ProtocolMin uint8192 ProtocolMax uint8193 ProtocolCur uint8194 DelegateMin uint8195 DelegateMax uint8196 DelegateCur uint8197}198type memberEventRecord struct {199 Event string200 Members []Member201}202type AgentIPC struct {203 sync.Mutex204 agent *Agent205 authKey string206 clients map[string]*IPCClient207 listener net.Listener208 logger *log.Logger209 logWriter *logWriter210 stop bool211 stopCh chan struct{}212}213type IPCClient struct {214 queryID uint64 // Used to increment query IDs215 name string216 conn net.Conn217 reader *bufio.Reader218 writer *bufio.Writer219 dec *codec.Decoder220 enc *codec.Encoder221 writeLock sync.Mutex222 version int32 // From the handshake, 0 before223 logStreamer *logStream224 eventStreams map[uint64]*eventStream225 pendingQueries map[uint64]*serf.Query226 queryLock sync.Mutex227 didAuth bool // Did we get an auth token yet?228}229// send is used to send an object using the MsgPack encoding. send230// is serialized to prevent write overlaps, while properly buffering.231func (c *IPCClient) Send(header *responseHeader, obj interface{}) error {232 c.writeLock.Lock()233 defer c.writeLock.Unlock()234 if err := c.enc.Encode(header); err != nil {235 return err236 }237 if obj != nil {238 if err := c.enc.Encode(obj); err != nil {239 return err240 }241 }242 if err := c.writer.Flush(); err != nil {243 return err244 }245 return nil246}247func (c *IPCClient) String() string {248 return fmt.Sprintf("ipc.client: %v", c.conn.RemoteAddr())249}250// nextQueryID safely generates a new query ID251func (c *IPCClient) nextQueryID() uint64 {252 return atomic.AddUint64(&c.queryID, 1)253}254// RegisterQuery is used to register a pending query that may255// get a response. The ID of the query is returned256func (c *IPCClient) RegisterQuery(q *serf.Query) uint64 {257 // Generate a unique-per-client ID258 id := c.nextQueryID()259 // Ensure the query deadline is in the future260 timeout := q.Deadline().Sub(time.Now())261 if timeout < 0 {262 return id263 }264 // Register the query265 c.queryLock.Lock()266 c.pendingQueries[id] = q267 c.queryLock.Unlock()268 // Setup a timer to deregister after the timeout269 time.AfterFunc(timeout, func() {270 c.queryLock.Lock()271 delete(c.pendingQueries, id)272 c.queryLock.Unlock()273 })274 return id275}276// NewAgentIPC is used to create a new Agent IPC handler277func NewAgentIPC(agent *Agent, authKey string, listener net.Listener,278 logOutput io.Writer, logWriter *logWriter) *AgentIPC {279 if logOutput == nil {280 logOutput = os.Stderr281 }282 ipc := &AgentIPC{283 agent: agent,284 authKey: authKey,285 clients: make(map[string]*IPCClient),286 listener: listener,287 logger: log.New(logOutput, "", log.LstdFlags),288 logWriter: logWriter,289 stopCh: make(chan struct{}),290 }291 go ipc.listen()292 return ipc293}294// Shutdown is used to shutdown the IPC layer295func (i *AgentIPC) Shutdown() {296 i.Lock()297 defer i.Unlock()298 if i.stop {299 return300 }301 i.stop = true302 close(i.stopCh)303 i.listener.Close()304 // Close the existing connections305 for _, client := range i.clients {306 client.conn.Close()307 }308}309// listen is a long running routine that listens for new clients310func (i *AgentIPC) listen() {311 for {312 conn, err := i.listener.Accept()313 if err != nil {314 if i.stop {315 return316 }317 i.logger.Printf("[ERR] agent.ipc: Failed to accept client: %v", err)318 continue319 }320 i.logger.Printf("[INFO] agent.ipc: Accepted client: %v", conn.RemoteAddr())321 metrics.IncrCounter([]string{"agent", "ipc", "accept"}, 1)322 // Wrap the connection in a client323 client := &IPCClient{324 name: conn.RemoteAddr().String(),325 conn: conn,326 reader: bufio.NewReader(conn),327 writer: bufio.NewWriter(conn),328 eventStreams: make(map[uint64]*eventStream),329 pendingQueries: make(map[uint64]*serf.Query),330 }331 client.dec = codec.NewDecoder(client.reader,332 &codec.MsgpackHandle{RawToString: true, WriteExt: true})333 client.enc = codec.NewEncoder(client.writer,334 &codec.MsgpackHandle{RawToString: true, WriteExt: true})335 // Register the client336 i.Lock()337 if !i.stop {338 i.clients[client.name] = client339 go i.handleClient(client)340 } else {341 conn.Close()342 }343 i.Unlock()344 }345}346// deregisterClient is called to cleanup after a client disconnects347func (i *AgentIPC) deregisterClient(client *IPCClient) {348 // Close the socket349 client.conn.Close()350 // Remove from the clients list351 i.Lock()352 delete(i.clients, client.name)353 i.Unlock()354 // Remove from the log writer355 if client.logStreamer != nil {356 i.logWriter.DeregisterHandler(client.logStreamer)357 client.logStreamer.Stop()358 }359 // Remove from event handlers360 for _, es := range client.eventStreams {361 i.agent.DeregisterEventHandler(es)362 es.Stop()363 }364}365// handleClient is a long running routine that handles a single client366func (i *AgentIPC) handleClient(client *IPCClient) {367 defer i.deregisterClient(client)368 var reqHeader requestHeader369 for {370 // Decode the header371 if err := client.dec.Decode(&reqHeader); err != nil {372 if !i.stop {373 // The second part of this if is to block socket374 // errors from Windows which appear to happen every375 // time there is an EOF.376 if err != io.EOF && !strings.Contains(strings.ToLower(err.Error()), "wsarecv") {377 i.logger.Printf("[ERR] agent.ipc: failed to decode request header: %v", err)378 }379 }380 return381 }382 // Evaluate the command383 if err := i.handleRequest(client, &reqHeader); err != nil {384 i.logger.Printf("[ERR] agent.ipc: Failed to evaluate request: %v", err)385 return386 }387 }388}389// handleRequest is used to evaluate a single client command390func (i *AgentIPC) handleRequest(client *IPCClient, reqHeader *requestHeader) error {391 // Look for a command field392 command := reqHeader.Command393 seq := reqHeader.Seq394 // Ensure the handshake is performed before other commands395 if command != handshakeCommand && client.version == 0 {396 respHeader := responseHeader{Seq: seq, Error: handshakeRequired}397 client.Send(&respHeader, nil)398 return fmt.Errorf(handshakeRequired)399 }400 metrics.IncrCounter([]string{"agent", "ipc", "command"}, 1)401 // Ensure the client has authenticated after the handshake if necessary402 if i.authKey != "" && !client.didAuth && command != authCommand && command != handshakeCommand {403 i.logger.Printf("[WARN] agent.ipc: Client sending commands before auth")404 respHeader := responseHeader{Seq: seq, Error: authRequired}405 client.Send(&respHeader, nil)406 return nil407 }408 // Dispatch command specific handlers409 switch command {410 case handshakeCommand:411 return i.handleHandshake(client, seq)412 case authCommand:413 return i.handleAuth(client, seq)414 case eventCommand:415 return i.handleEvent(client, seq)416 case membersCommand, membersFilteredCommand:417 return i.handleMembers(client, command, seq)418 case streamCommand:419 return i.handleStream(client, seq)420 case monitorCommand:421 return i.handleMonitor(client, seq)422 case stopCommand:423 return i.handleStop(client, seq)424 case forceLeaveCommand:425 return i.handleForceLeave(client, seq)426 case joinCommand:427 return i.handleJoin(client, seq)428 case leaveCommand:429 return i.handleLeave(client, seq)430 case installKeyCommand:431 return i.handleInstallKey(client, seq)432 case useKeyCommand:433 return i.handleUseKey(client, seq)434 case removeKeyCommand:435 return i.handleRemoveKey(client, seq)436 case listKeysCommand:437 return i.handleListKeys(client, seq)438 case tagsCommand:439 return i.handleTags(client, seq)440 case queryCommand:441 return i.handleQuery(client, seq)442 case respondCommand:443 return i.handleRespond(client, seq)444 case statsCommand:445 return i.handleStats(client, seq)446 case getCoordinateCommand:447 return i.handleGetCoordinate(client, seq)448 default:449 respHeader := responseHeader{Seq: seq, Error: unsupportedCommand}450 client.Send(&respHeader, nil)451 return fmt.Errorf("command '%s' not recognized", command)452 }453}454func (i *AgentIPC) handleHandshake(client *IPCClient, seq uint64) error {455 var req handshakeRequest456 if err := client.dec.Decode(&req); err != nil {457 return fmt.Errorf("decode failed: %v", err)458 }459 resp := responseHeader{460 Seq: seq,461 Error: "",462 }463 // Check the version464 if req.Version < MinIPCVersion || req.Version > MaxIPCVersion {465 resp.Error = unsupportedIPCVersion466 } else if client.version != 0 {467 resp.Error = duplicateHandshake468 } else {469 client.version = req.Version470 }471 return client.Send(&resp, nil)472}473func (i *AgentIPC) handleAuth(client *IPCClient, seq uint64) error {474 var req authRequest475 if err := client.dec.Decode(&req); err != nil {476 return fmt.Errorf("decode failed: %v", err)477 }478 resp := responseHeader{479 Seq: seq,480 Error: "",481 }482 // Check the token matches483 if req.AuthKey == i.authKey {484 client.didAuth = true485 } else {486 resp.Error = invalidAuthToken487 }488 return client.Send(&resp, nil)489}490func (i *AgentIPC) handleEvent(client *IPCClient, seq uint64) error {491 var req eventRequest492 if err := client.dec.Decode(&req); err != nil {493 return fmt.Errorf("decode failed: %v", err)494 }495 // Attempt the send496 err := i.agent.UserEvent(req.Name, req.Payload, req.Coalesce)497 // Respond498 resp := responseHeader{499 Seq: seq,500 Error: errToString(err),501 }502 return client.Send(&resp, nil)503}504func (i *AgentIPC) handleForceLeave(client *IPCClient, seq uint64) error {505 var req forceLeaveRequest506 if err := client.dec.Decode(&req); err != nil {507 return fmt.Errorf("decode failed: %v", err)508 }509 // Attempt leave510 var err error511 if req.Prune {512 err = i.agent.ForceLeavePrune(req.Node)513 } else {514 err = i.agent.ForceLeave(req.Node)515 }516 // Respond517 resp := responseHeader{518 Seq: seq,519 Error: errToString(err),520 }521 return client.Send(&resp, nil)522}523func (i *AgentIPC) handleJoin(client *IPCClient, seq uint64) error {524 var req joinRequest525 if err := client.dec.Decode(&req); err != nil {526 return fmt.Errorf("decode failed: %v", err)527 }528 // Attempt the join529 num, err := i.agent.Join(req.Existing, req.Replay)530 // Respond531 header := responseHeader{532 Seq: seq,533 Error: errToString(err),534 }535 resp := joinResponse{536 Num: int32(num),537 }538 return client.Send(&header, &resp)539}540func (i *AgentIPC) handleMembers(client *IPCClient, command string, seq uint64) error {541 serf := i.agent.Serf()542 raw := serf.Members()543 members := make([]Member, 0, len(raw))544 if command == membersFilteredCommand {545 var req membersFilteredRequest546 err := client.dec.Decode(&req)547 if err != nil {548 return fmt.Errorf("decode failed: %v", err)549 }550 raw, err = i.filterMembers(raw, req.Tags, req.Status, req.Name)551 if err != nil {552 return err553 }554 }555 for _, m := range raw {556 sm := Member{557 Name: m.Name,558 Addr: m.Addr,559 Port: m.Port,560 Tags: m.Tags,561 Status: m.Status.String(),562 ProtocolMin: m.ProtocolMin,563 ProtocolMax: m.ProtocolMax,564 ProtocolCur: m.ProtocolCur,565 DelegateMin: m.DelegateMin,566 DelegateMax: m.DelegateMax,567 DelegateCur: m.DelegateCur,568 }569 members = append(members, sm)570 }571 header := responseHeader{572 Seq: seq,573 Error: "",574 }575 resp := membersResponse{576 Members: members,577 }578 return client.Send(&header, &resp)579}580func (i *AgentIPC) filterMembers(members []serf.Member, tags map[string]string,581 status string, name string) ([]serf.Member, error) {582 result := make([]serf.Member, 0, len(members))583 // Pre-compile all the regular expressions584 tagsRe := make(map[string]*regexp.Regexp)585 for tag, expr := range tags {586 re, err := regexp.Compile(fmt.Sprintf("^%s$", expr))587 if err != nil {588 return nil, fmt.Errorf("Failed to compile regex: %v", err)589 }590 tagsRe[tag] = re591 }592 statusRe, err := regexp.Compile(fmt.Sprintf("^%s$", status))593 if err != nil {594 return nil, fmt.Errorf("Failed to compile regex: %v", err)595 }596 nameRe, err := regexp.Compile(fmt.Sprintf("^%s$", name))597 if err != nil {598 return nil, fmt.Errorf("Failed to compile regex: %v", err)599 }600OUTER:601 for _, m := range members {602 // Check if tags were passed, and if they match603 for tag := range tags {604 if !tagsRe[tag].MatchString(m.Tags[tag]) {605 continue OUTER606 }607 }608 // Check if status matches609 if status != "" && !statusRe.MatchString(m.Status.String()) {610 continue611 }612 // Check if node name matches613 if name != "" && !nameRe.MatchString(m.Name) {614 continue615 }616 // Made it past the filters!617 result = append(result, m)618 }619 return result, nil620}621func (i *AgentIPC) handleInstallKey(client *IPCClient, seq uint64) error {622 var req keyRequest623 if err := client.dec.Decode(&req); err != nil {624 return fmt.Errorf("decode failed: %v", err)625 }626 queryResp, err := i.agent.InstallKey(req.Key)627 header := responseHeader{628 Seq: seq,629 Error: errToString(err),630 }631 resp := keyResponse{632 Messages: queryResp.Messages,633 NumNodes: queryResp.NumNodes,634 NumErr: queryResp.NumErr,635 NumResp: queryResp.NumResp,636 }637 return client.Send(&header, &resp)638}639func (i *AgentIPC) handleUseKey(client *IPCClient, seq uint64) error {640 var req keyRequest641 if err := client.dec.Decode(&req); err != nil {642 return fmt.Errorf("decode failed: %v", err)643 }644 queryResp, err := i.agent.UseKey(req.Key)645 header := responseHeader{646 Seq: seq,647 Error: errToString(err),648 }649 resp := keyResponse{650 Messages: queryResp.Messages,651 NumNodes: queryResp.NumNodes,652 NumErr: queryResp.NumErr,653 NumResp: queryResp.NumResp,654 }655 return client.Send(&header, &resp)656}657func (i *AgentIPC) handleRemoveKey(client *IPCClient, seq uint64) error {658 var req keyRequest659 if err := client.dec.Decode(&req); err != nil {660 return fmt.Errorf("decode failed: %v", err)661 }662 queryResp, err := i.agent.RemoveKey(req.Key)663 header := responseHeader{664 Seq: seq,665 Error: errToString(err),666 }667 resp := keyResponse{668 Messages: queryResp.Messages,669 NumNodes: queryResp.NumNodes,670 NumErr: queryResp.NumErr,671 NumResp: queryResp.NumResp,672 }673 return client.Send(&header, &resp)674}675func (i *AgentIPC) handleListKeys(client *IPCClient, seq uint64) error {676 queryResp, err := i.agent.ListKeys()677 header := responseHeader{678 Seq: seq,679 Error: errToString(err),680 }681 resp := keyResponse{682 Messages: queryResp.Messages,683 Keys: queryResp.Keys,684 NumNodes: queryResp.NumNodes,685 NumErr: queryResp.NumErr,686 NumResp: queryResp.NumResp,687 }688 return client.Send(&header, &resp)689}690func (i *AgentIPC) handleStream(client *IPCClient, seq uint64) error {691 var es *eventStream692 var req streamRequest693 if err := client.dec.Decode(&req); err != nil {694 return fmt.Errorf("decode failed: %v", err)695 }696 resp := responseHeader{697 Seq: seq,698 Error: "",699 }700 // Create the event filters701 filters := ParseEventFilter(req.Type)702 for _, f := range filters {703 if !f.Valid() {704 resp.Error = invalidFilter705 goto SEND706 }707 }708 // Check if there is an existing stream709 if _, ok := client.eventStreams[seq]; ok {710 resp.Error = streamExists711 goto SEND712 }713 // Create an event streamer714 es = newEventStream(client, filters, seq, i.logger)715 client.eventStreams[seq] = es716 // Register with the agent. Defer so that we can respond before717 // registration, avoids any possible race condition718 defer i.agent.RegisterEventHandler(es)719SEND:720 return client.Send(&resp, nil)721}722func (i *AgentIPC) handleMonitor(client *IPCClient, seq uint64) error {723 var req monitorRequest724 if err := client.dec.Decode(&req); err != nil {725 return fmt.Errorf("decode failed: %v", err)726 }727 resp := responseHeader{728 Seq: seq,729 Error: "",730 }731 // Upper case the log level732 req.LogLevel = strings.ToUpper(req.LogLevel)733 // Create a level filter734 filter := LevelFilter()735 filter.MinLevel = logutils.LogLevel(req.LogLevel)736 if !ValidateLevelFilter(filter.MinLevel, filter) {737 resp.Error = fmt.Sprintf("Unknown log level: %s", filter.MinLevel)738 goto SEND739 }740 // Check if there is an existing monitor741 if client.logStreamer != nil {742 resp.Error = monitorExists743 goto SEND744 }745 // Create a log streamer746 client.logStreamer = newLogStream(client, filter, seq, i.logger)747 // Register with the log writer. Defer so that we can respond before748 // registration, avoids any possible race condition749 defer i.logWriter.RegisterHandler(client.logStreamer)750SEND:751 return client.Send(&resp, nil)752}753func (i *AgentIPC) handleStop(client *IPCClient, seq uint64) error {754 var req stopRequest755 if err := client.dec.Decode(&req); err != nil {756 return fmt.Errorf("decode failed: %v", err)757 }758 // Remove a log monitor if any759 if client.logStreamer != nil && client.logStreamer.seq == req.Stop {760 i.logWriter.DeregisterHandler(client.logStreamer)761 client.logStreamer.Stop()762 client.logStreamer = nil763 }764 // Remove an event stream if any765 if es, ok := client.eventStreams[req.Stop]; ok {766 i.agent.DeregisterEventHandler(es)767 es.Stop()768 delete(client.eventStreams, req.Stop)769 }770 // Always succeed771 resp := responseHeader{Seq: seq, Error: ""}772 return client.Send(&resp, nil)773}774func (i *AgentIPC) handleLeave(client *IPCClient, seq uint64) error {775 i.logger.Printf("[INFO] agent.ipc: Graceful leave triggered")776 // Do the leave777 err := i.agent.Leave()778 if err != nil {779 i.logger.Printf("[ERR] agent.ipc: leave failed: %v", err)780 }781 resp := responseHeader{Seq: seq, Error: errToString(err)}782 // Send and wait783 err = client.Send(&resp, nil)784 // Trigger a shutdown!785 if err := i.agent.Shutdown(); err != nil {786 i.logger.Printf("[ERR] agent.ipc: shutdown failed: %v", err)787 }788 return err789}790func (i *AgentIPC) handleTags(client *IPCClient, seq uint64) error {791 var req tagsRequest...
force_leave_test.go
Source:force_leave_test.go
...6 "github.com/hashicorp/serf/serf"7 "github.com/hashicorp/serf/testutil"8 "github.com/mitchellh/cli"9)10func TestForceLeaveCommandRun(t *testing.T) {11 ip1, returnFn1 := testutil.TakeIP()12 defer returnFn1()13 ip2, returnFn2 := testutil.TakeIP()14 defer returnFn2()15 ip3, returnFn3 := testutil.TakeIP()16 defer returnFn3()17 a1 := testAgent(t, ip1)18 defer a1.Shutdown()19 a2 := testAgent(t, ip2)20 defer a2.Shutdown()21 rpcAddr, ipc := testIPC(t, ip3, a1)22 defer ipc.Shutdown()23 _, err := a1.Join([]string{a2.SerfConfig().NodeName + "/" + a2.SerfConfig().MemberlistConfig.BindAddr}, false)24 if err != nil {25 t.Fatalf("err: %v", err)26 }27 testutil.Yield()28 // Forcibly shutdown a2 so that it appears "failed" in a129 if err := a2.Serf().Shutdown(); err != nil {30 t.Fatalf("err: %v", err)31 }32 start := time.Now()33WAIT:34 time.Sleep(a2.SerfConfig().MemberlistConfig.ProbeInterval * 3)35 m := a1.Serf().Members()36 if len(m) != 2 {37 t.Fatalf("should have 2 members: %#v", a1.Serf().Members())38 }39 if m[1].Status != serf.StatusFailed && time.Now().Sub(start) < 3*time.Second {40 goto WAIT41 }42 ui := new(cli.MockUi)43 c := &ForceLeaveCommand{Ui: ui}44 args := []string{45 "-rpc-addr=" + rpcAddr,46 a2.SerfConfig().NodeName,47 }48 code := c.Run(args)49 if code != 0 {50 t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String())51 }52 m = a1.Serf().Members()53 if len(m) != 2 {54 t.Fatalf("should have 2 members: %#v", a1.Serf().Members())55 }56 left := m[0]57 if m[1].Name == a2.SerfConfig().NodeName {58 left = m[1]59 }60 if left.Status != serf.StatusLeft {61 t.Fatalf("should be left: %#v", left)62 }63}64func TestForceLeaveCommandRun_noAddrs(t *testing.T) {65 ui := new(cli.MockUi)66 c := &ForceLeaveCommand{Ui: ui}67 args := []string{"-rpc-addr=foo"}68 code := c.Run(args)69 if code != 1 {70 t.Fatalf("bad: %d", code)71 }72 if !strings.Contains(ui.ErrorWriter.String(), "node name") {73 t.Fatalf("bad: %#v", ui.ErrorWriter.String())74 }75}76func TestForceLeaveCommandRun_prune(t *testing.T) {77 ip1, returnFn1 := testutil.TakeIP()78 defer returnFn1()79 ip2, returnFn2 := testutil.TakeIP()80 defer returnFn2()81 ip3, returnFn3 := testutil.TakeIP()82 defer returnFn3()83 a1 := testAgent(t, ip1)84 defer a1.Shutdown()85 a2 := testAgent(t, ip2)86 defer a2.Shutdown()87 rpcAddr, ipc := testIPC(t, ip3, a1)88 defer ipc.Shutdown()89 _, err := a1.Join([]string{a2.SerfConfig().NodeName + "/" + a2.SerfConfig().MemberlistConfig.BindAddr}, false)90 if err != nil {91 t.Fatalf("err: %v", err)92 }93 testutil.Yield()94 // Forcibly shutdown a2 so that it appears "failed" in a195 if err := a2.Serf().Shutdown(); err != nil {96 t.Fatalf("err: %v", err)97 }98 start := time.Now()99WAIT:100 time.Sleep(a2.SerfConfig().MemberlistConfig.ProbeInterval * 3)101 m := a1.Serf().Members()102 if len(m) != 2 {103 t.Fatalf("should have 2 members: %#v", a1.Serf().Members())104 }105 if m[1].Status != serf.StatusFailed && time.Now().Sub(start) < 3*time.Second {106 goto WAIT107 }108 ui := new(cli.MockUi)109 c := &ForceLeaveCommand{Ui: ui}110 args := []string{111 "-rpc-addr=" + rpcAddr,112 "-prune",113 a2.SerfConfig().NodeName,114 }115 code := c.Run(args)116 if code != 0 {117 t.Fatalf("bad: %d. %#v", code, ui.ErrorWriter.String())118 }119 m = a1.Serf().Members()120 if len(m) != 1 {121 t.Fatalf("should have 1 members: %#v", a1.Serf().Members())122 }123}...
Leave
Using AI Code Generation
1import "fmt"2func main() {3 fmt.Println("Hello, World!")4}5import "fmt"6func main() {7 fmt.Println("Hello, World!")8}9import "fmt"10func main() {11 fmt.Println("Hello, World!")12}13import "fmt"14func main() {15 fmt.Println("Hello, World!")16}17import "fmt"18func main() {19 fmt.Println("Hello, World!")20}21import "fmt"22func main() {23 fmt.Println("Hello, World!")24}25import "fmt"26func main() {27 fmt.Println("Hello, World!")28}29import "fmt"30func main() {31 fmt.Println("Hello, World!")32}33import "fmt"34func main() {35 fmt.Println("Hello, World!")36}37import "fmt"38func main() {39 fmt.Println("Hello, World!")40}41import "fmt"42func main() {43 fmt.Println("Hello, World!")44}45import "fmt"46func main() {47 fmt.Println("Hello, World!")48}49import "fmt"50func main() {51 fmt.Println("Hello, World!")52}53import "fmt"54func main() {
Leave
Using AI Code Generation
1import "fmt"2import "ipc"3func main() {4 ipc.Leave("group1", "user1")5}6import "fmt"7import "ipc"8func main() {9 ipc.Leave("group1", "user2")10}11import "fmt"12import "ipc"13func main() {14 ipc.Leave("group1", "user3")15}16import "fmt"17import "ipc"18func main() {19 ipc.Leave("group1", "user4")20}21import "fmt"22import "ipc"23func main() {24 ipc.Leave("group1", "user5")25}26import "fmt"27import "ipc"28func main() {29 ipc.Leave("group1", "user6")30}31import "fmt"32import "ipc"33func main() {34 ipc.Leave("group1", "user7")35}36import "fmt"37import "ipc"38func main() {39 ipc.Leave("group1", "user8")40}41import "fmt"42import "ipc"43func main() {44 ipc.Leave("group1", "user9")45}46import "fmt"47import "ipc"48func main() {49 ipc.Leave("group1", "user10")50}51import "fmt"52import "ipc"53func main() {54 ipc.Leave("group1", "user11")55}
Leave
Using AI Code Generation
1import (2type IPC struct {3}4func (ipc *IPC) Leave(args *int, reply *int) error {5 log.Println("Leave method called")6}7func main() {8 ipc := new(IPC)9 rpc.Register(ipc)10 l, err := net.Listen("tcp", ":1234")11 if err != nil {12 log.Fatal("listen error:", err)13 }14 for {15 conn, err := l.Accept()16 if err != nil {17 log.Fatal("accept error:", err)18 }19 go jsonrpc.ServeConn(conn)20 }21}22import (23type IPC struct {24}25func (ipc *IPC) Join(args *int, reply *int) error {26 log.Println("Join method called")27}28func main() {29 client, err := rpc.Dial("tcp", "
Leave
Using AI Code Generation
1import (2type LeaveArgs struct {3}4type LeaveReply struct {5}6func main() {7 if len(os.Args) != 2 {8 fmt.Println("Usage: go run 2.go <username>")9 }10 client, err := rpc.DialHTTP("tcp", "localhost:1234")11 if err != nil {12 log.Fatal("dialing:", err)13 }14 args := LeaveArgs{Username: username}15 err = client.Call("Ipc.Leave", args, &reply)16 if err != nil {17 log.Fatal("Ipc error:", err)18 }19 fmt.Println("Leave reply:", reply.Success)20}21import (22type CreateArgs struct {23}24type CreateReply struct {25}26func main() {27 if len(os.Args) != 3 {28 fmt.Println("Usage: go run 3.go <username> <password>")29 }30 client, err := rpc.DialHTTP("tcp", "localhost:1234")31 if err != nil {32 log.Fatal("dialing:", err)33 }34 args := CreateArgs{Username: username, Password: password}35 err = client.Call("Ipc.Create", args, &reply)36 if err != nil {37 log.Fatal("Ipc error:", err)38 }39 fmt.Println("Create reply:", reply.Success)40}41import (42type LoginArgs struct {43}44type LoginReply struct {45}46func main() {47 if len(os.Args) != 3 {48 fmt.Println("Usage: go run 4.go <username> <
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!