// Dashboards returns a noop.DashboardsStore if the context has no organization specified
// and an organization.DashboardsStore otherwise.
971965
func (s *Store) Dashboards(ctx context.Context) chronograf.DashboardsStore {
	if isServer := hasServerContext(ctx); isServer {
		return s.DashboardsStore
	}
	if org, ok := hasOrganizationContext(ctx); ok {
		return organizations.NewDashboardsStore(s.DashboardsStore, org)
	}

	return &noop.DashboardsStore{}
}
1092338
func (d *Dashboards) Add(ctx context.Context, dashboard chronograf.Dashboard) (chronograf.Dashboard, error) {
	genID, err := d.IDs.Generate()
	if err != nil {
		d.Logger.
			WithField("component", "dashboard").
			Error("Unable to generate ID")
		return chronograf.Dashboard{}, err
	}

	id, err := strconv.Atoi(genID)
	if err != nil {
		d.Logger.
			WithField("component", "dashboard").
			Error("Unable to convert ID")
		return chronograf.Dashboard{}, err
	}

	dashboard.ID = chronograf.DashboardID(id)

	file := dashboardFile(d.Dir, dashboard)
	if err = d.Create(file, dashboard); err != nil {
		if err == chronograf.ErrDashboardInvalid {
			d.Logger.
				WithField("component", "dashboard").
				WithField("name", file).
				Error("Invalid Dashboard: ", err)
		} else {
			d.Logger.
				WithField("component", "dashboard").
				WithField("name", file).
				Error("Unable to write dashboard:", err)
		}
		return chronograf.Dashboard{}, err
	}
	return dashboard, nil
}
915558
func (h *DashboardHandler) handleGetDashboards(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()
	req, err := decodeGetDashboardsRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if req.ownerID != nil {
		filter := platform.UserResourceMappingFilter{
			UserID:       *req.ownerID,
			UserType:     platform.Owner,
			ResourceType: platform.DashboardsResourceType,
		}

		mappings, _, err := h.UserResourceMappingService.FindUserResourceMappings(ctx, filter)
		if err != nil {
			EncodeError(ctx, &platform.Error{
				Code: platform.EInternal,
				Msg:  "Error loading dashboard owners",
				Err:  err,
			}, w)
			return
		}

		for _, mapping := range mappings {
			req.filter.IDs = append(req.filter.IDs, &mapping.ResourceID)
		}
	}

	dashboards, _, err := h.DashboardService.FindDashboards(ctx, req.filter, req.opts)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusOK, newGetDashboardsResponse(ctx, dashboards, req.filter, req.opts, h.LabelService)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
439269
func (c *Client) Datastores(ctx context.Context) ([]*mo.Datastore, error) {
	_, datacenter, err := c.finder(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}
	folders, err := datacenter.Folders(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}

	es, err := c.lister(folders.DatastoreFolder.Reference()).List(ctx)
	if err != nil {
		return nil, errors.Trace(err)
	}

	var datastores []*mo.Datastore
	for _, e := range es {
		switch o := e.Object.(type) {
		case mo.Datastore:
			datastores = append(datastores, &o)
		}
	}
	return datastores, nil
}
887255
func NewUsersStore(s chronograf.UsersStore, org string) *UsersStore {
	return &UsersStore{
		store:        s,
		organization: org,
	}
}
1105084
func NewDashboardsStore(s chronograf.DashboardsStore, org string) *DashboardsStore {
	return &DashboardsStore{
		store:        s,
		organization: org,
	}
}
918383
func NewOrganizationsStore(s chronograf.OrganizationsStore, org string) *OrganizationsStore {
	return &OrganizationsStore{
		store:        s,
		organization: org,
	}
}
1046073
func (d *DashboardsStore) Delete(ctx context.Context, dash chronograf.Dashboard) error {
	if err := d.client.db.Update(func(tx *bolt.Tx) error {
		strID := strconv.Itoa(int(dash.ID))
		if err := tx.Bucket(DashboardsBucket).Delete([]byte(strID)); err != nil {
			return err
		}
		return nil
	}); err != nil {
		return err
	}

	return nil
}
973545
func (s *Service) FindDashboards(ctx context.Context, filter platform.DashboardFilter, opts platform.FindOptions) ([]*platform.Dashboard, int, error) {
	var ds []*platform.Dashboard
	op := OpPrefix + platform.OpFindDashboards
	if len(filter.IDs) == 1 {
		d, err := s.FindDashboardByID(ctx, *filter.IDs[0])
		if err != nil && platform.ErrorCode(err) != platform.ENotFound {
			return ds, 0, &platform.Error{
				Err: err,
				Op:  op,
			}
		}
		if d == nil {
			return ds, 0, nil
		}
		return []*platform.Dashboard{d}, 1, nil
	}

	var count int
	filterFn := filterDashboardFn(filter)
	err := s.forEachDashboard(ctx, opts, func(d *platform.Dashboard) bool {
		if filterFn(d) {
			if count >= opts.Offset {
				ds = append(ds, d)
			}
			count++
		}
		if opts.Limit > 0 && len(ds) >= opts.Limit {
			return false
		}
		return true
	})

	if err != nil {
		return nil, 0, err
	}

	return ds, len(ds), err
}
1313881
func SortDashboards(opts FindOptions, ds []*Dashboard) {
	var sorter func(i, j int) bool
	switch opts.SortBy {
	case "CreatedAt":
		sorter = func(i, j int) bool {
			return ds[j].Meta.CreatedAt.After(ds[i].Meta.CreatedAt)
		}
	case "UpdatedAt":
		sorter = func(i, j int) bool {
			return ds[j].Meta.UpdatedAt.After(ds[i].Meta.UpdatedAt)
		}
	case "Name":
		sorter = func(i, j int) bool {
			return ds[i].Name < ds[j].Name
		}
	default:
		sorter = func(i, j int) bool {
			if opts.Descending {
				return ds[i].ID > ds[j].ID
			}
			return ds[i].ID < ds[j].ID
		}
	}

	sort.Slice(ds, sorter)
}
1174794
func GetDashboardVersion(c *m.ReqContext) Response {
	dashID := c.ParamsInt64(":dashboardId")

	guardian := guardian.New(dashID, c.OrgId, c.SignedInUser)
	if canSave, err := guardian.CanSave(); err != nil || !canSave {
		return dashboardGuardianResponse(err)
	}

	query := m.GetDashboardVersionQuery{
		OrgId:       c.OrgId,
		DashboardId: dashID,
		Version:     c.ParamsInt(":id"),
	}

	if err := bus.Dispatch(&query); err != nil {
		return Error(500, fmt.Sprintf("Dashboard version %d not found for dashboardId %d", query.Version, dashID), err)
	}

	creator := anonString
	if query.Result.CreatedBy > 0 {
		creator = getUserLogin(query.Result.CreatedBy)
	}

	dashVersionMeta := &m.DashboardVersionMeta{
		Id:            query.Result.Id,
		DashboardId:   query.Result.DashboardId,
		Data:          query.Result.Data,
		ParentVersion: query.Result.ParentVersion,
		RestoredFrom:  query.Result.RestoredFrom,
		Version:       query.Result.Version,
		Created:       query.Result.Created,
		Message:       query.Result.Message,
		CreatedBy:     creator,
	}

	return JSON(200, dashVersionMeta)
}
1295715
func (s *DashboardService) CreateDashboard(ctx context.Context, d *platform.Dashboard) error {
	url, err := newURL(s.Addr, dashboardsPath)
	if err != nil {
		return err
	}

	b, err := json.Marshal(d)
	if err != nil {
		return err
	}

	req, err := http.NewRequest("POST", url.String(), bytes.NewReader(b))
	if err != nil {
		return err
	}

	req.Header.Set("Content-Type", "application/json")
	SetToken(s.Token, req)

	hc := newClient(url.Scheme, s.InsecureSkipVerify)

	resp, err := hc.Do(req)
	if err != nil {
		return err
	}

	if err := CheckError(resp, true); err != nil {
		return err
	}

	if err := json.NewDecoder(resp.Body).Decode(d); err != nil {
		return err
	}

	return nil
}
263031
func (h *DashboardHandler) handlePutDashboardCells(w http.ResponseWriter, r *http.Request) {
	ctx := r.Context()

	req, err := decodePutDashboardCellRequest(ctx, r)
	if err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := h.DashboardService.ReplaceDashboardCells(ctx, req.dashboardID, req.cells); err != nil {
		EncodeError(ctx, err, w)
		return
	}

	if err := encodeResponse(ctx, w, http.StatusCreated, newDashboardCellsResponse(req.dashboardID, req.cells)); err != nil {
		logEncodingError(h.Logger, r, err)
		return
	}
}
1113888
func (s *DashboardsStore) Delete(ctx context.Context, d chronograf.Dashboard) error {
	err := validOrganization(ctx)
	if err != nil {
		return err
	}

	d, err = s.store.Get(ctx, d.ID)
	if err != nil {
		return err
	}

	return s.store.Delete(ctx, d)
}
93898
func (s *DirectStore) Mappings(ctx context.Context) chronograf.MappingsStore {
	return s.MappingsStore
}
328470
func (s *OrganizationsStore) Delete(ctx context.Context, o *chronograf.Organization) error {
	if o.ID == string(DefaultOrganizationID) {
		return chronograf.ErrCannotDeleteDefaultOrganization
	}
	_, err := s.get(ctx, o.ID)
	if err != nil {
		return err
	}
	if err := s.client.db.Update(func(tx *bolt.Tx) error {
		return tx.Bucket(OrganizationsBucket).Delete([]byte(o.ID))
	}); err != nil {
		return err
	}

	// Dependent Delete of all resources

	// Each of the associated organization stores expects organization to be
	// set on the context.
	ctx = context.WithValue(ctx, organizations.ContextKey, o.ID)

	sourcesStore := organizations.NewSourcesStore(s.client.SourcesStore, o.ID)
	sources, err := sourcesStore.All(ctx)
	if err != nil {
		return err
	}
	for _, source := range sources {
		if err := sourcesStore.Delete(ctx, source); err != nil {
			return err
		}
	}

	serversStore := organizations.NewServersStore(s.client.ServersStore, o.ID)
	servers, err := serversStore.All(ctx)
	if err != nil {
		return err
	}
	for _, server := range servers {
		if err := serversStore.Delete(ctx, server); err != nil {
			return err
		}
	}

	dashboardsStore := organizations.NewDashboardsStore(s.client.DashboardsStore, o.ID)
	dashboards, err := dashboardsStore.All(ctx)
	if err != nil {
		return err
	}
	for _, dashboard := range dashboards {
		if err := dashboardsStore.Delete(ctx, dashboard); err != nil {
			return err
		}
	}

	usersStore := organizations.NewUsersStore(s.client.UsersStore, o.ID)
	users, err := usersStore.All(ctx)
	if err != nil {
		return err
	}
	for _, user := range users {
		if err := usersStore.Delete(ctx, &user); err != nil {
			return err
		}
	}

	mappings, err := s.client.MappingsStore.All(ctx)
	if err != nil {
		return err
	}
	for _, mapping := range mappings {
		if mapping.Organization == o.ID {
			if err := s.client.MappingsStore.Delete(ctx, &mapping); err != nil {
				return err
			}
		}
	}

	return nil
}
137845
func dashboardURL(proxy string, ns string, svc string) string {
	// Reference: https://github.com/kubernetes/dashboard/wiki/Accessing-Dashboard---1.7.X-and-above
	return fmt.Sprintf("http://%s/api/v1/namespaces/%s/services/http:%s:/proxy/", proxy, ns, svc)
}