// ZMQ_REQ_CORRELATE: match replies with requests
//
// See: http://api.zeromq.org/4-1:zmq-setsockopt#toc33
339992
func (soc *Socket) SetReqCorrelate(value int) error {
	return soc.setInt(C.ZMQ_REQ_CORRELATE, value)
}
682253
func MatchMock(req *http.Request) (Mock, error) {
	for _, mock := range GetAll() {
		matches, err := mock.Match(req)
		if err != nil {
			return nil, err
		}
		if matches {
			return mock, nil
		}
	}
	return nil, nil
}
229940
func (tprv *TransactionProposalResponseVerifier) Match(transactionProposalResponses []*fab.TransactionProposalResponse) error {
	if tprv.MinResponses <= 0 {
		return errors.New("minimum Responses has to be greater than zero")
	}

	if len(transactionProposalResponses) < tprv.MinResponses {
		return errors.Errorf("required minimum %d endorsments got %d", tprv.MinResponses, len(transactionProposalResponses))
	}

	block, err := createCommonBlock(transactionProposalResponses[0])
	if err != nil {
		return err
	}

	if block.Data == nil || block.Data.Data == nil {
		return errors.New("config block data is nil")
	}

	if len(block.Data.Data) != 1 {
		return errors.New("config block must contain one transaction")
	}

	// Compare block data from  remaining responses
	for _, tpr := range transactionProposalResponses[1:] {
		b, err := createCommonBlock(tpr)
		if err != nil {
			return err
		}

		if !proto.Equal(block.Data, b.Data) {
			return errors.WithStack(status.New(status.EndorserClientStatus, status.EndorsementMismatch.ToInt32(), "payloads for config block do not match", nil))
		}
	}

	return nil
}
231264
func Matcher(p rpc.ReadPeeker) bool {
	b, err := p.Peek(5)
	if err != nil {
		return false
	}
	return bytes.Equal(b, []byte("POST "))
}
800322
func Validate(request Message, replies []Message) error {
	for _, m := range replies {
		// Check for mismatched sequence, unless:
		//   - request had no sequence, meaning we are probably validating
		//     a multicast reply
		if m.Header.Sequence != request.Header.Sequence && request.Header.Sequence != 0 {
			return newOpError("validate", errMismatchedSequence)
		}

		// Check for mismatched PID, unless:
		//   - request had no PID, meaning we are either:
		//     - validating a multicast reply
		//     - netlink has not yet assigned us a PID
		//   - response had no PID, meaning it's from the kernel as a multicast reply
		if m.Header.PID != request.Header.PID && request.Header.PID != 0 && m.Header.PID != 0 {
			return newOpError("validate", errMismatchedPID)
		}
	}

	return nil
}
20003
func ReqRepLatencyServer(addr string, msgSize int, roundTrips int) {
	s, err := rep.NewSocket()
	if err != nil {
		log.Fatalf("Failed to make new pair socket: %v", err)
	}
	defer s.Close()

	all.AddTransports(s)
	l, err := s.NewListener(addr, nil)
	if err != nil {
		log.Fatalf("Failed to make new listener: %v", err)
	}

	// TCP no delay, please!
	l.SetOption(mangos.OptionNoDelay, true)

	err = l.Listen()
	if err != nil {
		log.Fatalf("Failed to listen: %v", err)
	}
	for i := 0; i != roundTrips; i++ {
		msg, err := s.RecvMsg()
		if err != nil {
			log.Fatalf("Failed to recv: %v", err)
		}
		if len(msg.Body) != msgSize {
			log.Fatalf("Received wrong message size: %d != %d", len(msg.Body), msgSize)
		}
		if err = s.SendMsg(msg); err != nil {
			log.Fatalf("Failed to send: %v", err)
		}
	}
}
1035286
func (soc *Socket) SetReqRelaxed(value int) error {
	return soc.setInt(C.ZMQ_REQ_RELAXED, value)
}
463745
func (c *Client) RPC(method string, args interface{}, reply interface{}) error {
	// This is subtle but we start measuring the time on the client side
	// right at the time of the first request, vs. on the first retry as
	// is done on the server side inside forward(). This is because the
	// servers may already be applying the RPCHoldTimeout up there, so by
	// starting the timer here we won't potentially double up the delay.
	// TODO (slackpad) Plumb a deadline here with a context.
	firstCheck := time.Now()

TRY:
	server := c.routers.FindServer()
	if server == nil {
		return structs.ErrNoServers
	}

	// Enforce the RPC limit.
	metrics.IncrCounter([]string{"client", "rpc"}, 1)
	if !c.rpcLimiter.Load().(*rate.Limiter).Allow() {
		metrics.IncrCounter([]string{"client", "rpc", "exceeded"}, 1)
		return structs.ErrRPCRateExceeded
	}

	// Make the request.
	rpcErr := c.connPool.RPC(c.config.Datacenter, server.Addr, server.Version, method, server.UseTLS, args, reply)
	if rpcErr == nil {
		return nil
	}

	// Move off to another server, and see if we can retry.
	c.logger.Printf("[ERR] consul: %q RPC failed to server %s: %v", method, server.Addr, rpcErr)
	metrics.IncrCounterWithLabels([]string{"client", "rpc", "failed"}, 1, []metrics.Label{{Name: "server", Value: server.Name}})
	c.routers.NotifyFailedServer(server)
	if retry := canRetry(args, rpcErr); !retry {
		return rpcErr
	}

	// We can wait a bit and retry!
	if time.Since(firstCheck) < c.config.RPCHoldTimeout {
		jitter := lib.RandomStagger(c.config.RPCHoldTimeout / jitterFraction)
		select {
		case <-time.After(jitter):
			goto TRY
		case <-c.shutdownCh:
		}
	}
	return rpcErr
}
1030990
func (_m *MockRPC) RPC(method string, args interface{}, reply interface{}) error {
	ret := _m.Called(method, args, reply)

	var r0 error
	if rf, ok := ret.Get(0).(func(string, interface{}, interface{}) error); ok {
		r0 = rf(method, args, reply)
	} else {
		r0 = ret.Error(0)
	}

	return r0
}
975285
func (soc *Socket) SetSocksProxy(value string) error {
	if minor < 1 {
		return ErrorNotImplemented41
	}
	if value == "" {
		return soc.setNullString(C.ZMQ_SOCKS_PROXY)
	}
	return soc.setString(C.ZMQ_SOCKS_PROXY, value)
}
881687
func (qzs *queryzRow) MysqlTimePQ() string {
	val := float64(qzs.mysqlTime) / (1e9 * float64(qzs.Count))
	return fmt.Sprintf("%.6f", val)
}
472497
func (c *Called) Match(actual interface{}) (success bool, err error) {
	val := reflect.ValueOf(actual)
	if val.Kind() != reflect.Struct && val.Kind() != reflect.Chan {
		return false, errors.New("BeCalled requires a channel or struct full of channel fields")
	}
	if len(c.calls) == 0 {
		c.calls = append(c.calls, []interface{}{})
	}
	success = true
	for _, call := range c.calls {
		args := args(val)
		actualCall := make([]interface{}, 0, len(args))
		for i, arg := range args {
			recvd, ok := receiveArg(arg)
			if !ok {
				return false, nil
			}
			actualCall = append(actualCall, recvd)
			if i >= len(call) {
				continue
			}
			switch src := call[i].(type) {
			case types.GomegaMatcher:
				matched, err := src.Match(recvd)
				if err != nil {
					return false, err
				}
				if !matched {
					success = false
					c.matchFailures = append(c.matchFailures, fmt.Sprintf("%s: %s", arg.name, src.FailureMessage(recvd)))
				}
			default:
				if !reflect.DeepEqual(call[i], recvd) {
					success = false
					c.matchFailures = append(c.matchFailures, fmt.Sprintf("%s: %v (expected) != %v (actual)", arg.name, call[i], recvd))
				}
			}
		}
		if !success {
			// This was actually an unmatched call, so reset matched
			c.calls = append(c.calls, c.matched...)
			c.matched = nil
			break
		}
		c.matched = append([][]interface{}{call}, c.matched...)
		c.calls = c.calls[1:]
	}
	return success, nil
}
323559
func shExpMatch(str, shexp string) bool {
	shexp = strings.Replace(shexp, ".", "\\.", -1)
	shexp = strings.Replace(shexp, "?", ".?", -1)
	shexp = strings.Replace(shexp, "*", ".*", -1)
	matched, err := regexp.MatchString("^"+shexp+"$", str)

	return err == nil && matched
}
85126
func (c *Context) Socket(socktype SocketType) (sock *Socket, err error) {
	ptr := C.zmq_socket(c.ctx, C.int(socktype))
	if ptr == nil {
		return nil, zmqerr()
	}
	sock = &Socket{
		ctx:  c,
		sock: ptr,
	}
	sock.SetLinger(0)
	return
}
408224
func (soc *Socket) SetInvertMatching(value int) error {
	if minor < 2 {
		return ErrorNotImplemented42
	}
	return soc.setInt(C.ZMQ_INVERT_MATCHING, value)
}
1041136
func (m *Mocker) Match(req *http.Request) (bool, error) {
	if m.disabled {
		return false, nil
	}

	// Filter
	for _, filter := range m.request.Filters {
		if !filter(req) {
			return false, nil
		}
	}

	// Map
	for _, mapper := range m.request.Mappers {
		if treq := mapper(req); treq != nil {
			req = treq
		}
	}

	// Match
	matches, err := m.matcher.Match(req, m.request)
	if matches {
		m.decrement()
	}

	return matches, err
}
717830
func (f *lightFetcher) syncLoop() {
	requesting := false
	defer f.pm.wg.Done()
	for {
		select {
		case <-f.pm.quitSync:
			return
		// when a new announce is received, request loop keeps running until
		// no further requests are necessary or possible
		case newAnnounce := <-f.requestChn:
			f.lock.Lock()
			s := requesting
			requesting = false
			var (
				rq      *distReq
				reqID   uint64
				syncing bool
			)

			if !f.syncing && !(newAnnounce && s) {
				rq, reqID, syncing = f.nextRequest()
			}
			f.lock.Unlock()

			if rq != nil {
				requesting = true
				if _, ok := <-f.pm.reqDist.queue(rq); ok {
					if syncing {
						f.lock.Lock()
						f.syncing = true
						f.lock.Unlock()
					} else {
						go func() {
							time.Sleep(softRequestTimeout)
							f.reqMu.Lock()
							req, ok := f.requested[reqID]
							if ok {
								req.timeout = true
								f.requested[reqID] = req
							}
							f.reqMu.Unlock()
							// keep starting new requests while possible
							f.requestChn <- false
						}()
					}
				} else {
					f.requestChn <- false
				}
			}
		case reqID := <-f.timeoutChn:
			f.reqMu.Lock()
			req, ok := f.requested[reqID]
			if ok {
				delete(f.requested, reqID)
			}
			f.reqMu.Unlock()
			if ok {
				f.pm.serverPool.adjustResponseTime(req.peer.poolEntry, time.Duration(mclock.Now()-req.sent), true)
				req.peer.Log().Debug("Fetching data timed out hard")
				go f.pm.removePeer(req.peer.id)
			}
		case resp := <-f.deliverChn:
			f.reqMu.Lock()
			req, ok := f.requested[resp.reqID]
			if ok && req.peer != resp.peer {
				ok = false
			}
			if ok {
				delete(f.requested, resp.reqID)
			}
			f.reqMu.Unlock()
			if ok {
				f.pm.serverPool.adjustResponseTime(req.peer.poolEntry, time.Duration(mclock.Now()-req.sent), req.timeout)
			}
			f.lock.Lock()
			if !ok || !(f.syncing || f.processResponse(req, resp)) {
				resp.peer.Log().Debug("Failed processing response")
				go f.pm.removePeer(resp.peer.id)
			}
			f.lock.Unlock()
		case p := <-f.syncDone:
			f.lock.Lock()
			p.Log().Debug("Done synchronising with peer")
			f.checkSyncedHeaders(p)
			f.syncing = false
			f.lock.Unlock()
			f.requestChn <- false
		}
	}
}