Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow for extra columns to be added to ExplorerTable #3248

Merged
merged 4 commits into from
Aug 31, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions api/query/query.proto
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,8 @@ message Object {
string message = 8;
string category = 9;
string unstructured = 10;
string id = 11;
string tenant = 12;
}

message DebugGetAccessRulesRequest {
Expand Down
6 changes: 6 additions & 0 deletions api/query/query.swagger.json
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,12 @@
},
"unstructured": {
"type": "string"
},
"id": {
"type": "string"
},
"tenant": {
"type": "string"
}
}
},
Expand Down
162 changes: 90 additions & 72 deletions pkg/api/query/query.pb.go

Large diffs are not rendered by default.

1 change: 1 addition & 0 deletions pkg/query/internal/models/object.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ type Object struct {
Category configuration.ObjectCategory `json:"category" gorm:"type:text"`
KubernetesDeletedAt time.Time `json:"kubernetesDeletedAt"`
Unstructured json.RawMessage `json:"unstructured" gorm:"type:blob"`
Tenant string `json:"tenant" gorm:"type:text"`
}

func (o Object) Validate() error {
Expand Down
5 changes: 5 additions & 0 deletions pkg/query/objectscollector/objectscollector.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,10 @@ import (
"github.com/weaveworks/weave-gitops/core/logger"
)

// Flux label for tenant
// https://github.com/fluxcd/flux2/blob/1730f3c46bddf0a29787d8d4fa5ace283f298e49/cmd/flux/create_tenant.go#L56
var tenantLabel = "toolkit.fluxcd.io/tenant"

func NewObjectsCollector(w store.Store, idx store.IndexWriter, mgr clusters.Subscriber, sa collector.ImpersonateServiceAccount, kinds []configuration.ObjectKind, log logr.Logger) (collector.Collector, error) {
incoming := make(chan []models.ObjectTransaction)
go func() {
Expand Down Expand Up @@ -119,6 +123,7 @@ func processRecords(objectTransactions []models.ObjectTransaction, store store.S
Category: cat,
KubernetesDeletedAt: modelTs,
Unstructured: raw,
Tenant: o.GetLabels()[tenantLabel],
}

if objTx.TransactionType() == models.TransactionTypeDelete {
Expand Down
45 changes: 43 additions & 2 deletions pkg/query/objectscollector/objectscollector_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,8 @@ import (
"github.com/fluxcd/helm-controller/api/v2beta1"
"github.com/go-logr/logr"
"github.com/go-logr/logr/testr"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
. "github.com/onsi/gomega"
"github.com/weaveworks/weave-gitops-enterprise/pkg/query/configuration"
"github.com/weaveworks/weave-gitops-enterprise/pkg/query/internal/models"
Expand All @@ -18,8 +20,6 @@ import (
func TestObjectsCollector_defaultProcessRecords(t *testing.T) {
g := NewWithT(t)
log := testr.New(t)
fakeStore := &storefakes.FakeStore{}
fakeIndex := &storefakes.FakeIndexWriter{}

//setup data
clusterName := "anyCluster"
Expand All @@ -28,6 +28,7 @@ func TestObjectsCollector_defaultProcessRecords(t *testing.T) {
name string
objectRecords []models.ObjectTransaction
expectedStoreNumCalls map[models.TransactionType]int
expectedObject []models.Object
errPattern string
}{
{
Expand Down Expand Up @@ -61,9 +62,37 @@ func TestObjectsCollector_defaultProcessRecords(t *testing.T) {
},
errPattern: "",
},
{
name: "gets an object tenant",
objectRecords: []models.ObjectTransaction{
testutils.NewObjectTransaction("anyCluster", testutils.NewHelmRelease("createdOrUpdatedHelmRelease", "default", func(hr *v2beta1.HelmRelease) {
hr.Labels = map[string]string{
tenantLabel: "my-tenant",
}
}), models.TransactionTypeUpsert),
},
expectedStoreNumCalls: map[models.TransactionType]int{
models.TransactionTypeDelete: 0,
models.TransactionTypeUpsert: 1,
models.TransactionTypeDeleteAll: 0,
},
expectedObject: []models.Object{{
Cluster: "anyCluster",
Name: "createdOrUpdatedHelmRelease",
Namespace: "default",
APIGroup: "",
APIVersion: "v2beta1",
Kind: "HelmRelease",
Tenant: "my-tenant",
Status: "Failed",
}},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fakeStore := &storefakes.FakeStore{}
fakeIndex := &storefakes.FakeIndexWriter{}

err := processRecords(tt.objectRecords, fakeStore, fakeIndex, log)
if tt.errPattern != "" {
g.Expect(err).To(MatchError(MatchRegexp(tt.errPattern)))
Expand All @@ -73,6 +102,18 @@ func TestObjectsCollector_defaultProcessRecords(t *testing.T) {
g.Expect(fakeStore.StoreObjectsCallCount()).To(Equal(tt.expectedStoreNumCalls[models.TransactionTypeUpsert]))
g.Expect(fakeStore.DeleteObjectsCallCount()).To(Equal(tt.expectedStoreNumCalls[models.TransactionTypeDelete]))
g.Expect(fakeStore.DeleteAllObjectsCallCount()).To(Equal(tt.expectedStoreNumCalls[models.TransactionTypeDeleteAll]))

if tt.expectedObject != nil {
opt := cmpopts.IgnoreFields(models.Object{}, "ID", "CreatedAt", "UpdatedAt", "DeletedAt", "Category", "Unstructured")
_, storeResult := fakeStore.StoreObjectsArgsForCall(0)

diff := cmp.Diff(tt.expectedObject[0], storeResult[0], opt)

if diff != "" {
t.Errorf("unexpected result (-want +got):\n%s", diff)
}

}
})
}
}
Expand Down
2 changes: 2 additions & 0 deletions pkg/query/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -280,6 +280,8 @@ func convertToPbObject(obj []models.Object) []*pb.Object {
Message: o.Message,
Category: string(o.Category),
Unstructured: string(o.Unstructured),
Id: o.GetID(),
Tenant: o.Tenant,
})
}

Expand Down
2 changes: 2 additions & 0 deletions ui-cra/src/api/query/query.pb.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,8 @@ export type Object = {
message?: string
category?: string
unstructured?: string
id?: string
tenant?: string
}

export type DebugGetAccessRulesRequest = {
Expand Down
44 changes: 41 additions & 3 deletions ui-cra/src/components/Applications/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,23 @@ import {
Button,
Icon,
IconType,
Link,
V2Routes,
formatURL,
useFeatureFlags,
useListAutomations,
} from '@weaveworks/weave-gitops';
import _ from 'lodash';
import { FC } from 'react';
import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
import { Object } from '../../api/query/query.pb';
import { Routes } from '../../utils/nav';
import { ActionsWrapper } from '../Clusters';
import OpenedPullRequest from '../Clusters/OpenedPullRequest';
import Explorer from '../Explorer/Explorer';
import { ActionsWrapper } from '../Clusters';
import { NotificationsWrapper } from '../Layout/NotificationsWrapper';
import { Page } from '../Layout/App';
import { NotificationsWrapper } from '../Layout/NotificationsWrapper';

const WGApplicationsDashboard: FC = ({ className }: any) => {
const { isFlagEnabled } = useFeatureFlags();
Expand Down Expand Up @@ -55,7 +60,40 @@ const WGApplicationsDashboard: FC = ({ className }: any) => {
</ActionsWrapper>
<div className={className}>
{useQueryServiceBackend ? (
<Explorer category="automation" enableBatchSync />
<Explorer
category="automation"
enableBatchSync
extraColumns={[
{
label: 'Source',
index: 4,
value: (o: Object & { parsed: any }) => {
const sourceAddr =
o.kind === 'HelmRelease'
? 'spec.chart.spec.sourceRef.name'
: 'spec.sourceRef.name';

const url = formatURL(V2Routes.Sources, {
name: o.name,
namespace: o.namespace,
clusterName: o.cluster,
});

const sourceName = _.get(o.parsed, sourceAddr);

if (!sourceName) {
return '-';
}

return (
<Link to={url}>
{o.namespace}/{sourceName}
</Link>
);
},
},
]}
/>
) : (
<AutomationsTable automations={automations?.result} />
)}
Expand Down
26 changes: 22 additions & 4 deletions ui-cra/src/components/Explorer/Explorer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -8,23 +8,34 @@ import { useHistory } from 'react-router-dom';
import styled from 'styled-components';
import { Facet } from '../../api/query/query.pb';
import { useListFacets, useQueryService } from '../../hooks/query';
import ExplorerTable from './ExplorerTable';
import ExplorerTable, { FieldWithIndex } from './ExplorerTable';
import FilterDrawer from './FilterDrawer';
import Filters from './Filters';
import PaginationControls from './PaginationControls';
import QueryInput from './QueryInput';
import QueryStateChips from './QueryStateChips';
import { QueryStateManager, URLQueryStateManager } from './QueryStateManager';
import { QueryStateProvider, columnHeaderHandler } from './hooks';
import {
QueryStateProvider,
columnHeaderHandler,
useGetUnstructuredObjects,
} from './hooks';

type Props = {
className?: string;
category?: 'automation' | 'source';
enableBatchSync?: boolean;
manager?: QueryStateManager;
extraColumns?: FieldWithIndex[];
};

function Explorer({ className, category, enableBatchSync, manager }: Props) {
function Explorer({
className,
category,
enableBatchSync,
manager,
extraColumns,
}: Props) {
const history = useHistory();
if (!manager) {
manager = new URLQueryStateManager(history);
Expand All @@ -45,6 +56,12 @@ function Explorer({ className, category, enableBatchSync, manager }: Props) {
category,
});

const unst = useGetUnstructuredObjects(data?.objects || []);
const rows = _.map(data?.objects, (o: any) => ({
...o,
parsed: unst[o.id],
}));

const filteredFacets = filterFacetsForCategory(facetsRes?.facets, category);

return (
Expand All @@ -60,10 +77,11 @@ function Explorer({ className, category, enableBatchSync, manager }: Props) {
<Flex wide>
<ExplorerTable
queryState={queryState}
rows={data?.objects || []}
rows={rows}
onColumnHeaderClick={columnHeaderHandler(queryState, setQueryState)}
enableBatchSync={enableBatchSync}
sortField={queryState.orderBy}
extraColumns={extraColumns}
/>

<FilterDrawer
Expand Down
Loading