// reconcileReleaseDef looks up the helm release associated with a
// HelmRelease resource, and either installs, upgrades, or does
// nothing, depending on the state (or absence) of the release.
424635
func (chs *ChartChangeSync) reconcileReleaseDef(fhr fluxv1beta1.HelmRelease) {
	releaseName := release.GetReleaseName(fhr)

	// Attempt to retrieve an upgradable release, in case no release
	// or error is returned, install it.
	rel, err := chs.release.GetUpgradableRelease(releaseName)
	if err != nil {
		chs.logger.Log("warning", "unable to proceed with release", "resource", fhr.ResourceID().String(), "release", releaseName, "err", err)
		return
	}

	opts := release.InstallOptions{DryRun: false}

	chartPath := ""
	chartRevision := ""
	if fhr.Spec.ChartSource.GitChartSource != nil {
		chartSource := fhr.Spec.ChartSource.GitChartSource
		// We need to hold the lock until after we're done releasing
		// the chart, so that the clone doesn't get swapped out from
		// under us. TODO(michael) consider having a lock per clone.
		chs.clonesMu.Lock()
		defer chs.clonesMu.Unlock()
		chartClone, ok := chs.clones[releaseName]
		// Validate the clone we have for the release is the same as
		// is being referenced in the chart source.
		if ok {
			ok = chartClone.remote == chartSource.GitURL && chartClone.ref == chartSource.RefOrDefault()
			if !ok {
				if chartClone.export != nil {
					chartClone.export.Clean()
				}
				delete(chs.clones, releaseName)
			}
		}
		// FIXME(michael): if it's not cloned, and it's not going to
		// be, we might not want to wait around until the next tick
		// before reporting what's wrong with it. But if we just use
		// repo.Ready(), we'll force all charts through that blocking
		// code, rather than waiting for things to sync in good time.
		if !ok {
			repo, ok := chs.mirrors.Get(mirrorName(chartSource))
			if !ok {
				chs.maybeMirror(fhr)
				chs.setCondition(fhr, fluxv1beta1.HelmReleaseChartFetched, v1.ConditionUnknown, ReasonGitNotReady, "git repo "+chartSource.GitURL+" not mirrored yet")
				chs.logger.Log("info", "chart repo not cloned yet", "resource", fhr.ResourceID().String())
			} else {
				status, err := repo.Status()
				if status != git.RepoReady {
					chs.setCondition(fhr, fluxv1beta1.HelmReleaseChartFetched, v1.ConditionUnknown, ReasonGitNotReady, "git repo not mirrored yet: "+err.Error())
					chs.logger.Log("info", "chart repo not ready yet", "resource", fhr.ResourceID().String(), "status", string(status), "err", err)
				}
			}
			return
		}
		chs.setCondition(fhr, fluxv1beta1.HelmReleaseChartFetched, v1.ConditionTrue, ReasonCloned, "successfully cloned git repo")
		chartPath = filepath.Join(chartClone.export.Dir(), chartSource.Path)
		chartRevision = chartClone.head

		if chs.config.UpdateDeps && !fhr.Spec.ChartSource.GitChartSource.SkipDepUpdate {
			if err := updateDependencies(chartPath, ""); err != nil {
				chs.setCondition(fhr, fluxv1beta1.HelmReleaseReleased, v1.ConditionFalse, ReasonDependencyFailed, err.Error())
				chs.logger.Log("warning", "failed to update chart dependencies", "resource", fhr.ResourceID().String(), "err", err)
				return
			}
		}
	} else if fhr.Spec.ChartSource.RepoChartSource != nil { // TODO(michael): make this dispatch more natural, or factor it out
		chartSource := fhr.Spec.ChartSource.RepoChartSource
		path, err := ensureChartFetched(chs.config.ChartCache, chartSource)
		if err != nil {
			chs.setCondition(fhr, fluxv1beta1.HelmReleaseChartFetched, v1.ConditionFalse, ReasonDownloadFailed, "chart download failed: "+err.Error())
			chs.logger.Log("info", "chart download failed", "resource", fhr.ResourceID().String(), "err", err)
			return
		}
		chs.setCondition(fhr, fluxv1beta1.HelmReleaseChartFetched, v1.ConditionTrue, ReasonDownloaded, "chart fetched: "+filepath.Base(path))
		chartPath = path
		chartRevision = chartSource.Version
	}

	if rel == nil {
		_, err := chs.release.Install(chartPath, releaseName, fhr, release.InstallAction, opts, &chs.kubeClient)
		if err != nil {
			chs.setCondition(fhr, fluxv1beta1.HelmReleaseReleased, v1.ConditionFalse, ReasonInstallFailed, err.Error())
			chs.logger.Log("warning", "failed to install chart", "resource", fhr.ResourceID().String(), "err", err)
			return
		}
		chs.setCondition(fhr, fluxv1beta1.HelmReleaseReleased, v1.ConditionTrue, ReasonSuccess, "helm install succeeded")
		if err = status.UpdateReleaseRevision(chs.ifClient.FluxV1beta1().HelmReleases(fhr.Namespace), fhr, chartRevision); err != nil {
			chs.logger.Log("warning", "could not update the release revision", "namespace", fhr.Namespace, "resource", fhr.Name, "err", err)
		}
		return
	}

	changed, err := chs.shouldUpgrade(chartPath, rel, fhr)
	if err != nil {
		chs.logger.Log("warning", "unable to determine if release has changed", "resource", fhr.ResourceID().String(), "err", err)
		return
	}
	if changed {
		cFhr, err := chs.ifClient.FluxV1beta1().HelmReleases(fhr.Namespace).Get(fhr.Name, metav1.GetOptions{})
		if err != nil {
			chs.logger.Log("warning", "failed to retrieve HelmRelease scheduled for upgrade", "resource", fhr.ResourceID().String(), "err", err)
			return
		}
		if diff := cmp.Diff(fhr.Spec, cFhr.Spec); diff != "" {
			chs.logger.Log("warning", "HelmRelease spec has diverged since we calculated if we should upgrade, skipping upgrade", "resource", fhr.ResourceID().String())
			return
		}
		_, err = chs.release.Install(chartPath, releaseName, fhr, release.UpgradeAction, opts, &chs.kubeClient)
		if err != nil {
			chs.setCondition(fhr, fluxv1beta1.HelmReleaseReleased, v1.ConditionFalse, ReasonUpgradeFailed, err.Error())
			chs.logger.Log("warning", "failed to upgrade chart", "resource", fhr.ResourceID().String(), "err", err)
			return
		}
		chs.setCondition(fhr, fluxv1beta1.HelmReleaseReleased, v1.ConditionTrue, ReasonSuccess, "helm upgrade succeeded")
		if err = status.UpdateReleaseRevision(chs.ifClient.FluxV1beta1().HelmReleases(fhr.Namespace), fhr, chartRevision); err != nil {
			chs.logger.Log("warning", "could not update the release revision", "resource", fhr.ResourceID().String(), "err", err)
		}
		return
	}
}
615773
func (impl *repoImpl) ResolveVersion(c context.Context, r *api.ResolveVersionRequest) (resp *api.Instance, err error) {
	defer func() { err = grpcutil.GRPCifyAndLogErr(c, err) }()

	// Validate the request.
	if err := common.ValidatePackageName(r.Package); err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "bad 'package' - %s", err)
	}
	if err := common.ValidateInstanceVersion(r.Version); err != nil {
		return nil, status.Errorf(codes.InvalidArgument, "bad 'version' - %s", err)
	}

	// Check ACLs.
	if _, err := impl.checkRole(c, r.Package, api.Role_READER); err != nil {
		return nil, err
	}

	// Actually resolve the version. This will return an appropriately grpc-tagged
	// error.
	inst, err := model.ResolveVersion(c, r.Package, r.Version)
	if err != nil {
		return nil, err
	}
	return inst.Proto(), nil
}
945878
func (c *helmReleases) Create(helmRelease *v1beta1.HelmRelease) (result *v1beta1.HelmRelease, err error) {
	result = &v1beta1.HelmRelease{}
	err = c.client.Post().
		Namespace(c.ns).
		Resource("helmreleases").
		Body(helmRelease).
		Do().
		Into(result)
	return
}
1058737
func (d *apiVersionsFromDiscovery) Invalidate() {
	d.mu.Lock()
	defer d.mu.Unlock()

	d.prefVersion = nil
}
702559
func NewReconcileOptions(ioStreams genericclioptions.IOStreams) *ReconcileOptions {
	return &ReconcileOptions{
		FilenameOptions: &resource.FilenameOptions{},
		PrintFlags:      genericclioptions.NewPrintFlags("reconciled").WithTypeSetter(scheme.Scheme),
		IOStreams:       ioStreams,
	}
}
108468
func (c *ClassList) Reconcile(m *ClassList) bool {
	var added bool
	maxlen := len(c.list)
	for ind, val := range m.list {
		if ind >= maxlen {
			added = true
			c.list = append(c.list, val)
			continue
		}

		if c.list[ind] == val {
			continue
		}

		added = true
		c.list[ind] = val
	}

	return added
}
985317
func (ar *AgentReconciler) Reconcile(a *Agent) {
	dAgentState, err := desiredAgentState(a, ar.reg)
	if err != nil {
		log.Errorf("Unable to determine agent's desired state: %v", err)
		return
	}

	cAgentState, err := a.units()
	if err != nil {
		log.Errorf("Unable to determine agent's current state: %v", err)
		return
	}

	tasks := ar.calculateTasksForUnits(dAgentState, cAgentState)
	ar.launchTasks(tasks, a)
}
197050
func Reconcile(opts ...scheduler.ReconcileOpt) *scheduler.Call {
	return &scheduler.Call{
		Type:      scheduler.Call_RECONCILE,
		Reconcile: (&scheduler.Call_Reconcile{}).With(opts...),
	}
}
40514
func (client DefaultClient) UpdateReleasedFlag(mappingID int, released bool) error {
	req, err := http.NewRequest("PUT", fmt.Sprintf("%s/rest/com.deniz.jira.mapping/latest/releaseFlag/%d?isReleased=%v", client.baseURL, mappingID, released), nil)
	if err != nil {
		return err
	}
	req.Header.Set("Accept", "application/json")
	req.SetBasicAuth(client.username, client.password)
	responseCode, data, err := client.consumeResponse(req)
	if err != nil {
		return err
	}
	if responseCode != http.StatusOK {
		logger.Printf("JIRA response: %s\n", string(data))
		return fmt.Errorf("error updating mapping is-released flag.  Status code: %d.\n", responseCode)
	}
	return nil
}
1104915
func (s *SerfEventHandler) reconcile(me serf.MemberEvent) {

	// Do nothing if we are not the leader.
	if !s.IsLeader() {
		return
	}

	// Check if this is a reap event
	isReap := me.EventType() == serf.EventMemberReap

	// Queue the members for reconciliation
	for _, m := range me.Members {
		// Change the status if this is a reap event
		if isReap {
			m.Status = StatusReap
		}

		// Call reconcile
		if s.Reconciler != nil {
			s.Reconciler.Reconcile(m)
		}
	}
}
797531
func (s *ReleaseServer) GetReleaseContent(c ctx.Context, req *services.GetReleaseContentRequest) (*services.GetReleaseContentResponse, error) {
	if err := validateReleaseName(req.Name); err != nil {
		s.Log("releaseContent: Release name is invalid: %s", req.Name)
		return nil, err
	}

	if req.Version <= 0 {
		rel, err := s.env.Releases.Last(req.Name)
		return &services.GetReleaseContentResponse{Release: rel}, err
	}

	rel, err := s.env.Releases.Get(req.Name, req.Version)
	return &services.GetReleaseContentResponse{Release: rel}, err
}
375313
func (client *Client) SetRelease(release string) {
	client.mu.Lock()
	defer client.mu.Unlock()
	client.release = release
}
838097
func (fhr HelmRelease) ResourceID() flux.ResourceID {
	return flux.MakeResourceID(fhr.Namespace, "HelmRelease", fhr.Name)
}
1130805
func GetReleaseVersions() ([]*Version, error) {
	versions, err := GetVersions()
	if err != nil {
		return nil, err
	}
	var output []*Version
	for _, version := range versions {
		if version.Version.String() != version.FullVersion {
			continue
		}
		output = append(output, version)
	}
	return output, nil
}
589667
func (s ReleaseContainersSpec) CalculateRelease(rc ReleaseContext, logger log.Logger) ([]*WorkloadUpdate, Result, error) {
	results := Result{}
	prefilter, postfilter := s.filters()
	all, err := rc.SelectWorkloads(results, prefilter, postfilter)
	if err != nil {
		return nil, results, err
	}
	updates := s.workloadUpdates(results, all)
	return updates, results, s.resultsError(results)
}
790472
func (r *ReleaseModuleServiceServer) InstallRelease(ctx context.Context, in *rudderAPI.InstallReleaseRequest) (*rudderAPI.InstallReleaseResponse, error) {
	grpclog.Print("install")
	b := bytes.NewBufferString(in.Release.Manifest)
	err := kubeClient.Create(in.Release.Namespace, b, 500, false)
	if err != nil {
		grpclog.Printf("error when creating release: %v", err)
	}
	return &rudderAPI.InstallReleaseResponse{}, err
}
592355
func upgradeTo(binary string, rel Release) error {
	expectedReleases := releaseNames(rel.Tag)
	for _, asset := range rel.Assets {
		assetName := path.Base(asset.Name)
		l.Debugln("considering release", assetName)

		for _, expRel := range expectedReleases {
			if strings.HasPrefix(assetName, expRel) {
				return upgradeToURL(assetName, binary, asset.URL)
			}
		}
	}

	return ErrNoReleaseDownload
}