// ensureNoWatch ensures there is no watch for CRs of a CRD.
// Returns true if a watch was found and terminated and false if there was no watch already.
545040
func (h *crdEventHandler) ensureNoWatch(logger *zap.Logger, crd *apiext_v1b1.CustomResourceDefinition) bool {
	crdWatch, ok := h.watchers[crd.Name]
	if !ok {
		// Nothing to do. This can happen if there was an error adding a watch
		return false
	}
	logger.Info("Removing watch for CRD")
	crdWatch.cancel()
	delete(h.watchers, crd.Name)
	gvk := schema.GroupVersionKind{
		Group:   crd.Spec.Group,
		Version: crd.Spec.Versions[0].Name,
		Kind:    crd.Spec.Names.Kind,
	}
	h.controller.Store.RemoveInformer(gvk)
	return true
}
1106972
func (r *Reflector) resyncChan() (<-chan time.Time, func() bool) {
	if r.resyncPeriod == 0 {
		r.nextResync = time.Time{}
		return neverExitWatch, func() bool { return false }
	}
	// The cleanup function is required: imagine the scenario where watches
	// always fail so we end up listing frequently. Then, if we don't
	// manually stop the timer, we could end up with many timers active
	// concurrently.
	r.nextResync = r.now().Add(r.resyncPeriod)
	t := time.NewTimer(r.resyncPeriod)
	return t.C, t.Stop
}
138622
func AssertGetNonexistentFails(s3CLIPath string, cfg *config.S3Cli) {
	configPath := MakeConfigFile(cfg)
	defer func() { _ = os.Remove(configPath) }()

	s3CLISession, err := RunS3CLI(s3CLIPath, configPath, "get", "non-existent-file", "/dev/null")
	Expect(err).ToNot(HaveOccurred())
	Expect(s3CLISession.ExitCode()).ToNot(BeZero())
	Expect(s3CLISession.Err.Contents()).To(ContainSubstring("NoSuchKey"))
}
1362567
func ensureNotKnownEndpoint(store jujuclient.ClientStore, endpoint string) error {
	existingDetails, existingName, err := store.ControllerByAPIEndpoints(endpoint)
	if err != nil && !errors.IsNotFound(err) {
		return errors.Trace(err)
	}

	if existingDetails == nil {
		return nil
	}

	// Check if we know the username for this controller
	accountDetails, err := store.AccountDetails(existingName)
	if err != nil && !errors.IsNotFound(err) {
		return errors.Trace(err)
	}

	if accountDetails != nil {
		return errors.Errorf(`This controller has already been registered on this client as %q
To login as user %q run 'juju login -u %s -c %s'.`, existingName, accountDetails.User, accountDetails.User, existingName)
	}

	return errors.Errorf(`This controller has already been registered on this client as %q
To login run 'juju login -c %s'.`, existingName, existingName)
}
1017919
func agentServiceWatch(params map[string]interface{}) (WatcherFunc, error) {
	// We don't support consistency modes since it's agent local data

	var serviceID string
	if err := assignValue(params, "service_id", &serviceID); err != nil {
		return nil, err
	}

	fn := func(p *Plan) (BlockingParamVal, interface{}, error) {
		agent := p.client.Agent()
		opts := makeQueryOptionsWithContext(p, false)
		defer p.cancelFunc()

		svc, _, err := agent.Service(serviceID, &opts)
		if err != nil {
			return nil, nil, err
		}

		// Return string ContentHash since we don't have Raft indexes to block on.
		return WaitHashVal(svc.ContentHash), svc, err
	}
	return fn, nil
}
28852
func (m *Monitor) fetchCheckForService(svc *service.Service, disco discovery.Discoverer) *Check {

	check := &Check{}
	check.Type, check.Args = disco.HealthCheck(svc)
	if check.Type == "" {
		log.Warnf("Got empty check type for service %s (id: %s) with args: %s!", svc.Name, svc.ID, check.Args)
		return nil
	}

	// Setup some other parts of the check that don't come from discovery
	check.ID = svc.ID
	check.Command = m.GetCommandNamed(check.Type)
	check.Status = FAILED

	return check
}
1175927
func (d *frameDec) checkCRC() error {
	if !d.HasCheckSum {
		return nil
	}
	var tmp [8]byte
	gotB := d.crc.Sum(tmp[:0])
	// Flip to match file order.
	gotB[0] = gotB[7]
	gotB[1] = gotB[6]
	gotB[2] = gotB[5]
	gotB[3] = gotB[4]

	// We can overwrite upper tmp now
	want := d.rawInput.readSmall(4)
	if want == nil {
		println("CRC missing?")
		return io.ErrUnexpectedEOF
	}

	if !bytes.Equal(gotB[:4], want) {
		println("CRC Check Failed:", gotB[:4], "!=", want)
		return ErrCRCMismatch
	}
	println("CRC ok")
	return nil
}
109381
func (c *collection) EnsureHashIndex(ctx context.Context, fields []string, options *EnsureHashIndexOptions) (Index, bool, error) {
	input := indexData{
		Type:   string(HashIndex),
		Fields: fields,
	}
	off := false
	if options != nil {
		input.Unique = &options.Unique
		input.Sparse = &options.Sparse
		if options.NoDeduplicate {
			input.Deduplicate = &off
		}
	}
	idx, created, err := c.ensureIndex(ctx, input)
	if err != nil {
		return nil, false, WithStack(err)
	}
	return idx, created, nil
}
155521
func InitKubServiceWatch(np *plugin.NetPlugin) {

	watchClient := setUpAPIClient()
	if watchClient == nil {
		log.Fatalf("Could not init kubernetes API client")
	}

	svcCh := make(chan SvcWatchResp, 1)
	epCh := make(chan EpWatchResp, 1)
	go func() {
		for {
			select {
			case svcEvent := <-svcCh:
				switch svcEvent.opcode {
				case "WARN":
					log.Debugf("svcWatch : %s", svcEvent.errStr)
					break
				case "FATAL":
					log.Errorf("svcWatch : %s", svcEvent.errStr)
					break
				case "ERROR":
					log.Warnf("svcWatch : %s", svcEvent.errStr)
					watchClient.WatchServices(svcCh)
					break

				case "DELETED":
					np.DelSvcSpec(svcEvent.svcName, &svcEvent.svcSpec)
					break
				default:
					np.AddSvcSpec(svcEvent.svcName, &svcEvent.svcSpec)
				}
			case epEvent := <-epCh:
				switch epEvent.opcode {
				case "WARN":
					log.Debugf("epWatch : %s", epEvent.errStr)
					break
				case "FATAL":
					log.Errorf("epWatch : %s", epEvent.errStr)
					break
				case "ERROR":
					log.Warnf("epWatch : %s", epEvent.errStr)
					watchClient.WatchSvcEps(epCh)
					break

				default:
					np.SvcProviderUpdate(epEvent.svcName, epEvent.providers)
				}
			}
		}
	}()

	watchClient.WatchServices(svcCh)
	watchClient.WatchSvcEps(epCh)
}
751329
func (s *Store) ensureCheckTxn(tx *memdb.Txn, idx uint64, hc *structs.HealthCheck) error {
	// Check if we have an existing health check
	existing, err := tx.First("checks", "id", hc.Node, string(hc.CheckID))
	if err != nil {
		return fmt.Errorf("failed health check lookup: %s", err)
	}

	// Set the indexes
	if existing != nil {
		existingCheck := existing.(*structs.HealthCheck)
		hc.CreateIndex = existingCheck.CreateIndex
		hc.ModifyIndex = existingCheck.ModifyIndex
	} else {
		hc.CreateIndex = idx
		hc.ModifyIndex = idx
	}

	// Use the default check status if none was provided
	if hc.Status == "" {
		hc.Status = api.HealthCritical
	}

	// Get the node
	node, err := tx.First("nodes", "id", hc.Node)
	if err != nil {
		return fmt.Errorf("failed node lookup: %s", err)
	}
	if node == nil {
		return ErrMissingNode
	}

	modified := true
	// If the check is associated with a service, check that we have
	// a registration for the service.
	if hc.ServiceID != "" {
		service, err := tx.First("services", "id", hc.Node, hc.ServiceID)
		if err != nil {
			return fmt.Errorf("failed service lookup: %s", err)
		}
		if service == nil {
			return ErrMissingService
		}

		// Copy in the service name and tags
		svc := service.(*structs.ServiceNode)
		hc.ServiceName = svc.ServiceName
		hc.ServiceTags = svc.ServiceTags
		if existing != nil && existing.(*structs.HealthCheck).IsSame(hc) {
			modified = false
		} else {
			// Check has been modified, we trigger a index service change
			if err = tx.Insert("index", &IndexEntry{serviceIndexName(svc.ServiceName), idx}); err != nil {
				return fmt.Errorf("failed updating index: %s", err)
			}
		}
	} else {
		if existing != nil && existing.(*structs.HealthCheck).IsSame(hc) {
			modified = false
		} else {
			// Since the check has been modified, it impacts all services of node
			// Update the status for all the services associated with this node
			err = s.updateAllServiceIndexesOfNode(tx, idx, hc.Node)
			if err != nil {
				return err
			}
		}
	}

	// Delete any sessions for this check if the health is critical.
	if hc.Status == api.HealthCritical {
		mappings, err := tx.Get("session_checks", "node_check", hc.Node, string(hc.CheckID))
		if err != nil {
			return fmt.Errorf("failed session checks lookup: %s", err)
		}

		var ids []string
		for mapping := mappings.Next(); mapping != nil; mapping = mappings.Next() {
			ids = append(ids, mapping.(*sessionCheck).Session)
		}

		// Delete the session in a separate loop so we don't trash the
		// iterator.
		for _, id := range ids {
			if err := s.deleteSessionTxn(tx, idx, id); err != nil {
				return fmt.Errorf("failed deleting session: %s", err)
			}
		}
	}
	if modified {
		// We update the modify index, ONLY if something has changed, thus
		// With constant output, no change is seen when watching a service
		// With huge number of nodes where anti-entropy updates continuously
		// the checks, but not the values within the check
		hc.ModifyIndex = idx
	}

	// Persist the check registration in the db.
	if err := tx.Insert("checks", hc); err != nil {
		return fmt.Errorf("failed inserting check: %s", err)
	}
	if err := tx.Insert("index", &IndexEntry{"checks", idx}); err != nil {
		return fmt.Errorf("failed updating index: %s", err)
	}

	return nil
}
370254
func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) {
	ch := make(chan discovery.Entries)
	errCh := make(chan error)
	ticker := time.NewTicker(s.heartbeat)

	go func() {
		defer close(errCh)
		defer close(ch)

		// Send the initial entries if available.
		var currentEntries discovery.Entries
		var err error

		s.mu.Lock()
		if len(s.values) > 0 {
			currentEntries, err = discovery.CreateEntries(s.values)
		}
		s.mu.Unlock()

		if err != nil {
			errCh <- err
		} else if currentEntries != nil {
			ch <- currentEntries
		}

		// Periodically send updates.
		for {
			select {
			case <-ticker.C:
				s.mu.Lock()
				newEntries, err := discovery.CreateEntries(s.values)
				s.mu.Unlock()
				if err != nil {
					errCh <- err
					continue
				}

				// Check if the file has really changed.
				if !newEntries.Equals(currentEntries) {
					ch <- newEntries
				}
				currentEntries = newEntries
			case <-stopCh:
				ticker.Stop()
				return
			}
		}
	}()

	return ch, errCh
}
5573
func (s *Discovery) Watch(stopCh <-chan struct{}) (<-chan discovery.Entries, <-chan error) {
	ch := make(chan discovery.Entries)
	errCh := make(chan error)
	ticker := time.NewTicker(s.heartbeat)

	go func() {
		defer close(errCh)
		defer close(ch)

		// Send the initial entries if available.
		currentEntries, err := s.fetch()
		if err != nil {
			errCh <- err
		} else {
			ch <- currentEntries
		}

		// Periodically send updates.
		for {
			select {
			case <-ticker.C:
				newEntries, err := s.fetch()
				if err != nil {
					errCh <- err
					continue
				}

				// Check if the file has really changed.
				if !newEntries.Equals(currentEntries) {
					ch <- newEntries
				}
				currentEntries = newEntries
			case <-stopCh:
				ticker.Stop()
				return
			}
		}
	}()

	return ch, errCh
}
904169
func shouldWatchFileWithExtension(name string) bool {
	for _, s := range watchExts {
		if strings.HasSuffix(name, s) {
			return true
		}
	}
	return false
}
1074815
func (v *Validator) SetNotBefore(nbf time.Time) {
	v.expect()
	v.Expected.Set("nbf", nbf)
}
625900
func (m *MonitorConfig) CheckAndSetDefaults() error {
	if m.Context == nil {
		return trace.BadParameter("missing parameter Context")
	}
	if m.DisconnectExpiredCert.IsZero() && m.ClientIdleTimeout == 0 {
		return trace.BadParameter("either DisconnectExpiredCert or ClientIdleTimeout should be set")
	}
	if m.Conn == nil {
		return trace.BadParameter("missing parameter Conn")
	}
	if m.Entry == nil {
		return trace.BadParameter("missing parameter Entry")
	}
	if m.Tracker == nil {
		return trace.BadParameter("missing parameter Tracker")
	}
	if m.Audit == nil {
		return trace.BadParameter("missing parameter Audit")
	}
	if m.Clock == nil {
		m.Clock = clockwork.NewRealClock()
	}
	return nil
}
579693
func (s *Store) ensureCheckCASTxn(tx *memdb.Txn, idx uint64, hc *structs.HealthCheck) (bool, error) {
	// Retrieve the existing entry.
	_, existing, err := s.getNodeCheckTxn(tx, hc.Node, hc.CheckID)
	if err != nil {
		return false, fmt.Errorf("failed health check lookup: %s", err)
	}

	// Check if the we should do the set. A ModifyIndex of 0 means that
	// we are doing a set-if-not-exists.
	if hc.ModifyIndex == 0 && existing != nil {
		return false, nil
	}
	if hc.ModifyIndex != 0 && existing == nil {
		return false, nil
	}
	if existing != nil && hc.ModifyIndex != 0 && hc.ModifyIndex != existing.ModifyIndex {
		return false, nil
	}

	// Perform the update.
	if err := s.ensureCheckTxn(tx, idx, hc); err != nil {
		return false, err
	}

	return true, nil
}
697243
func ErrChainMismatch(knownChain,
	unknownChain *chainhash.Hash) ReservationError {
	return ReservationError{
		fmt.Errorf("Unknown chain=%v. Supported chain=%v",
			unknownChain, knownChain),
	}
}