// getPluginInfoFromRepositoryForPlatform returns the plugin info, if found, from
// the specified repository for the specified platform.
356388
func (actor Actor) getPluginInfoFromRepositoryForPlatform(pluginName string, pluginRepo configv3.PluginRepository, platform string) (PluginInfo, error) {
	pluginRepository, err := actor.client.GetPluginRepository(pluginRepo.URL)
	if err != nil {
		return PluginInfo{}, err
	}

	var pluginFoundWithIncompatibleBinary bool

	for _, plugin := range pluginRepository.Plugins {
		if plugin.Name == pluginName {
			for _, pluginBinary := range plugin.Binaries {
				if pluginBinary.Platform == platform {
					return PluginInfo{
						Name:     plugin.Name,
						Version:  plugin.Version,
						URL:      pluginBinary.URL,
						Checksum: pluginBinary.Checksum,
					}, nil
				}
			}
			pluginFoundWithIncompatibleBinary = true
		}
	}

	if pluginFoundWithIncompatibleBinary {
		return PluginInfo{}, actionerror.NoCompatibleBinaryError{}
	}

	return PluginInfo{}, actionerror.PluginNotFoundInRepositoryError{
		PluginName:     pluginName,
		RepositoryName: pluginRepo.Name,
	}
}
261225
func (c *Client) GetPluginPrivileges(name string, ctx context.Context) ([]PluginPrivilege, error) {
	resp, err := c.do("GET", "/plugins/privileges?remote="+name, doOptions{
		context: ctx,
	})
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()
	var pluginPrivileges []PluginPrivilege
	if err := json.NewDecoder(resp.Body).Decode(&pluginPrivileges); err != nil {
		return nil, err
	}
	return pluginPrivileges, nil
}
925520
func GetPluginProperties(jsonPropertiesFile string) (map[string]interface{}, error) {
	pluginPropertiesJSON, err := ioutil.ReadFile(jsonPropertiesFile)
	if err != nil {
		return nil, fmt.Errorf("Could not read %s: %s\n", filepath.Base(jsonPropertiesFile), err)
	}
	var pluginJSON interface{}
	if err = json.Unmarshal([]byte(pluginPropertiesJSON), &pluginJSON); err != nil {
		return nil, fmt.Errorf("Could not read %s: %s\n", filepath.Base(jsonPropertiesFile), err)
	}
	return pluginJSON.(map[string]interface{}), nil
}
806923
func (c *Sys) GetPlugin(i *GetPluginInput) (*GetPluginResponse, error) {
	path := catalogPathByType(i.Type, i.Name)
	req := c.c.NewRequest(http.MethodGet, path)

	ctx, cancelFunc := context.WithCancel(context.Background())
	defer cancelFunc()
	resp, err := c.c.RawRequestWithContext(ctx, req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	var result struct {
		Data *GetPluginResponse
	}
	err = resp.DecodeJSON(&result)
	if err != nil {
		return nil, err
	}
	return result.Data, err
}
1131114
func (InstallPluginCommand) handleFetchingPluginInfoFromRepositoriesError(fetchErr actionerror.FetchingPluginInfoFromRepositoryError) error {
	switch clientErr := fetchErr.Err.(type) {
	case pluginerror.RawHTTPStatusError:
		return translatableerror.FetchingPluginInfoFromRepositoriesError{
			Message:        clientErr.Status,
			RepositoryName: fetchErr.RepositoryName,
		}

	case pluginerror.SSLValidationHostnameError:
		return translatableerror.FetchingPluginInfoFromRepositoriesError{
			Message:        clientErr.Error(),
			RepositoryName: fetchErr.RepositoryName,
		}

	case pluginerror.UnverifiedServerError:
		return translatableerror.FetchingPluginInfoFromRepositoriesError{
			Message:        clientErr.Error(),
			RepositoryName: fetchErr.RepositoryName,
		}

	default:
		return clientErr
	}
}
1325337
func CheckForNewVersion(plugin Plugin) (string, error) {
	route, found, err := ReadPluginRoute(plugin.Name)
	if err != nil {
		return "", err
	}
	if !found {
		return "", fmt.Errorf("no route found for already loaded plugin (%s)", plugin.Name)
	}
	if route.Version == "" {
		// local plugin, can not update
		return "", nil
	}

	pluginSrcDir := GetPluginSrcDir(plugin.Name)

	gitDirPath := filepath.Join(pluginSrcDir, ".git")
	if exist, err := pathutil.IsPathExists(gitDirPath); err != nil {
		return "", fmt.Errorf("failed to check if .git folder exist at (%s), error: %s", gitDirPath, err)
	} else if !exist {
		return "", fmt.Errorf(".git folder not exist at (%s), error: %s", gitDirPath, err)
	}

	versions, err := GitVersionTags(pluginSrcDir)
	if err != nil {
		return "", err
	}

	if len(versions) == 0 {
		return "", nil
	}

	latestVersion := versions[len(versions)-1]

	currentVersion, err := GetPluginVersion(plugin.Name)
	if err != nil {
		return "", fmt.Errorf("failed to check installed plugin (%s) version, error: %s", plugin.Name, err)
	}

	if currentVersion == nil {
		return "", nil
	}

	if latestVersion.GreaterThan(currentVersion) {
		return latestVersion.String(), nil
	}

	return "", nil
}
1077150
func (hs *HTTPServer) getFrontendSettingsMap(c *m.ReqContext) (map[string]interface{}, error) {
	orgDataSources := make([]*m.DataSource, 0)

	if c.OrgId != 0 {
		query := m.GetDataSourcesQuery{OrgId: c.OrgId}
		err := bus.Dispatch(&query)

		if err != nil {
			return nil, err
		}

		dsFilterQuery := m.DatasourcesPermissionFilterQuery{
			User:        c.SignedInUser,
			Datasources: query.Result,
		}

		if err := bus.Dispatch(&dsFilterQuery); err != nil {
			if err != bus.ErrHandlerNotFound {
				return nil, err
			}

			orgDataSources = query.Result
		} else {
			orgDataSources = dsFilterQuery.Result
		}
	}

	datasources := make(map[string]interface{})
	var defaultDatasource string

	enabledPlugins, err := plugins.GetEnabledPlugins(c.OrgId)
	if err != nil {
		return nil, err
	}

	pluginsToPreload := []string{}

	for _, app := range enabledPlugins.Apps {
		if app.Preload {
			pluginsToPreload = append(pluginsToPreload, app.Module)
		}
	}

	for _, ds := range orgDataSources {
		url := ds.Url

		if ds.Access == m.DS_ACCESS_PROXY {
			url = "/api/datasources/proxy/" + strconv.FormatInt(ds.Id, 10)
		}

		var dsMap = map[string]interface{}{
			"id":   ds.Id,
			"type": ds.Type,
			"name": ds.Name,
			"url":  url,
		}

		meta, exists := enabledPlugins.DataSources[ds.Type]
		if !exists {
			log.Error(3, "Could not find plugin definition for data source: %v", ds.Type)
			continue
		}

		if meta.Preload {
			pluginsToPreload = append(pluginsToPreload, meta.Module)
		}

		dsMap["meta"] = meta

		if ds.IsDefault {
			defaultDatasource = ds.Name
		}

		if ds.JsonData != nil {
			dsMap["jsonData"] = ds.JsonData
		} else {
			dsMap["jsonData"] = make(map[string]string)
		}

		if ds.Access == m.DS_ACCESS_DIRECT {
			if ds.BasicAuth {
				dsMap["basicAuth"] = util.GetBasicAuthHeader(ds.BasicAuthUser, ds.DecryptedBasicAuthPassword())
			}
			if ds.WithCredentials {
				dsMap["withCredentials"] = ds.WithCredentials
			}

			if ds.Type == m.DS_INFLUXDB_08 {
				dsMap["username"] = ds.User
				dsMap["password"] = ds.DecryptedPassword()
				dsMap["url"] = url + "/db/" + ds.Database
			}

			if ds.Type == m.DS_INFLUXDB {
				dsMap["username"] = ds.User
				dsMap["password"] = ds.DecryptedPassword()
				dsMap["url"] = url
			}
		}

		if ds.Type == m.DS_ES {
			dsMap["index"] = ds.Database
		}

		if ds.Type == m.DS_INFLUXDB {
			dsMap["database"] = ds.Database
		}

		if ds.Type == m.DS_PROMETHEUS {
			// add unproxied server URL for link to Prometheus web UI
			dsMap["directUrl"] = ds.Url
		}

		datasources[ds.Name] = dsMap
	}

	// add datasources that are built in (meaning they are not added via data sources page, nor have any entry in datasource table)
	for _, ds := range plugins.DataSources {
		if ds.BuiltIn {
			datasources[ds.Name] = map[string]interface{}{
				"type": ds.Type,
				"name": ds.Name,
				"meta": plugins.DataSources[ds.Id],
			}
		}
	}

	if defaultDatasource == "" {
		defaultDatasource = "-- Grafana --"
	}

	panels := map[string]interface{}{}
	for _, panel := range enabledPlugins.Panels {
		if panel.State == plugins.PluginStateAlpha && !hs.Cfg.PluginsEnableAlpha {
			continue
		}

		if panel.Preload {
			pluginsToPreload = append(pluginsToPreload, panel.Module)
		}

		panels[panel.Id] = map[string]interface{}{
			"module":       panel.Module,
			"baseUrl":      panel.BaseUrl,
			"name":         panel.Name,
			"id":           panel.Id,
			"info":         panel.Info,
			"hideFromList": panel.HideFromList,
			"sort":         getPanelSort(panel.Id),
			"dataFormats":  panel.DataFormats,
			"state":        panel.State,
		}
	}

	jsonObj := map[string]interface{}{
		"defaultDatasource":          defaultDatasource,
		"datasources":                datasources,
		"panels":                     panels,
		"appSubUrl":                  setting.AppSubUrl,
		"allowOrgCreate":             (setting.AllowUserOrgCreate && c.IsSignedIn) || c.IsGrafanaAdmin,
		"authProxyEnabled":           setting.AuthProxyEnabled,
		"ldapEnabled":                setting.LdapEnabled,
		"alertingEnabled":            setting.AlertingEnabled,
		"alertingErrorOrTimeout":     setting.AlertingErrorOrTimeout,
		"alertingNoDataOrNullValues": setting.AlertingNoDataOrNullValues,
		"exploreEnabled":             setting.ExploreEnabled,
		"googleAnalyticsId":          setting.GoogleAnalyticsId,
		"disableLoginForm":           setting.DisableLoginForm,
		"externalUserMngInfo":        setting.ExternalUserMngInfo,
		"externalUserMngLinkUrl":     setting.ExternalUserMngLinkUrl,
		"externalUserMngLinkName":    setting.ExternalUserMngLinkName,
		"viewersCanEdit":             setting.ViewersCanEdit,
		"editorsCanAdmin":            hs.Cfg.EditorsCanAdmin,
		"disableSanitizeHtml":        hs.Cfg.DisableSanitizeHtml,
		"pluginsToPreload":           pluginsToPreload,
		"buildInfo": map[string]interface{}{
			"version":       setting.BuildVersion,
			"commit":        setting.BuildCommit,
			"buildstamp":    setting.BuildStamp,
			"latestVersion": plugins.GrafanaLatestVersion,
			"hasUpdate":     plugins.GrafanaHasUpdate,
			"env":           setting.Env,
			"isEnterprise":  setting.IsEnterprise,
		},
	}

	return jsonObj, nil
}
1045651
func getIsImportRepositoryInfo(isi *imagev1.ImageStreamImport) *metrics.ImportErrorInfo {
	if isi.Status.Repository == nil || isi.Spec.Repository == nil {
		return nil
	}
	ref := isi.Spec.Repository.From
	if ref.Kind != "DockerImage" {
		return nil
	}
	imgRef, err := imageapi.ParseDockerImageReference(ref.Name)
	if err != nil {
		utilruntime.HandleError(fmt.Errorf(
			"failed to parse isi.spec.repository.from.name %q: %v",
			ref.Name, err))
		return nil
	}

	info := mkImportInfo(imgRef.DockerClientDefaults().Registry, &isi.Status.Repository.Status)
	return &info
}
1242193
func (c *Client) GetPlugins(details bool) *GetPluginsResult {
	r := &GetPluginsResult{}

	var path string
	if details {
		path = "/plugins?details"
	} else {
		path = "/plugins"
	}

	resp, err := c.do("GET", path, ContentTypeJSON)
	if err != nil {
		r.Err = err
		return r
	}

	switch resp.Meta.Type {
	// TODO change this to concrete const type when Joel adds it
	case rbody.PluginListType:
		// Success
		b := resp.Body.(*rbody.PluginList)
		r.LoadedPlugins = convertLoadedPlugins(b.LoadedPlugins)
		r.AvailablePlugins = convertAvailablePlugins(b.AvailablePlugins)
		return r
	case rbody.ErrorType:
		r.Err = resp.Body.(*rbody.Error)
	default:
		r.Err = ErrAPIResponseMetaType
	}
	return r
}
1125664
func interfacesFor(version unversioned.GroupVersion) (*meta.VersionInterfaces, error) {
	switch version {
	case v1.SchemeGroupVersion:
		return &meta.VersionInterfaces{
			ObjectConvertor:  api.Scheme,
			MetadataAccessor: accessor,
		}, nil
	default:
		g, _ := registered.Group(autoscaling.GroupName)
		return nil, fmt.Errorf("unsupported storage version: %s (valid: %v)", version, g.GroupVersions)
	}
}
13400
func MustNewPluginInfo(group, product, version string, params ...PluginInfoParam) PluginInfo {
	cmd, err := NewPluginInfo(group, product, version, params...)
	if err != nil {
		panic(errors.Wrapf(err, "failed to create plugin info"))
	}
	return cmd
}
504091
func (config *Config) GetPluginCaseInsensitive(pluginName string) (Plugin, bool) {
	for name, plugin := range config.pluginsConfig.Plugins {
		if strings.EqualFold(name, pluginName) {
			return plugin, true
		}
	}

	return Plugin{}, false
}
303627
func interfacesFor(version string) (*meta.VersionInterfaces, error) {
	switch version {
	case "metrics/v1alpha1":
		return &meta.VersionInterfaces{
			Codec:            v1alpha1.Codec,
			ObjectConvertor:  api.Scheme,
			MetadataAccessor: accessor,
		}, nil
	default:
		g, _ := latest.Group("metrics")
		return nil, fmt.Errorf("unsupported storage version: %s (valid: %s)", version, strings.Join(g.Versions, ", "))
	}
}
890575
func (d *domainClient) GetPlatformFontsForNode(ctx context.Context, args *GetPlatformFontsForNodeArgs) (reply *GetPlatformFontsForNodeReply, err error) {
	reply = new(GetPlatformFontsForNodeReply)
	if args != nil {
		err = rpcc.Invoke(ctx, "CSS.getPlatformFontsForNode", args, reply, d.conn)
	} else {
		err = rpcc.Invoke(ctx, "CSS.getPlatformFontsForNode", nil, reply, d.conn)
	}
	if err != nil {
		err = &internal.OpError{Domain: "CSS", Op: "GetPlatformFontsForNode", Err: err}
	}
	return
}
74108
func (m *API) GetMachineProviderInterfaceInfo(machines params.Entities) params.ProviderInterfaceInfoResults {
	results := make([]params.ProviderInterfaceInfoResult, len(machines.Entities))
	for i, entity := range machines.Entities {
		results[i].MachineTag = entity.Tag

		interfaces, err := m.getInterfaceInfoForOneMachine(entity.Tag)
		if err != nil {
			results[i].Error = common.ServerError(err)
			continue
		}

		infos := make([]params.ProviderInterfaceInfo, len(interfaces))
		for i, info := range interfaces {
			infos[i].InterfaceName = info.InterfaceName
			infos[i].MACAddress = info.MACAddress
			infos[i].ProviderId = string(info.ProviderId)
		}

		results[i].Interfaces = infos
	}
	return params.ProviderInterfaceInfoResults{results}
}
200574
func (kl *Kubelet) getPodPluginDir(podUID types.UID, pluginName string) string {
	return filepath.Join(kl.getPodPluginsDir(podUID), pluginName)
}
570037
func (ds *dockerService) getIPFromPlugin(sandbox *dockertypes.ContainerJSON) (string, error) {
	metadata, err := parseSandboxName(sandbox.Name)
	if err != nil {
		return "", err
	}
	msg := fmt.Sprintf("Couldn't find network status for %s/%s through plugin", metadata.Namespace, metadata.Name)
	cID := kubecontainer.BuildContainerID(runtimeName, sandbox.ID)
	networkStatus, err := ds.network.GetPodNetworkStatus(metadata.Namespace, metadata.Name, cID)
	if err != nil {
		return "", err
	}
	if networkStatus == nil {
		return "", fmt.Errorf("%v: invalid network status for", msg)
	}
	return networkStatus.IP.String(), nil
}