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

Use resource handler to get version #452

Merged
merged 2 commits into from
Sep 23, 2024
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
66 changes: 66 additions & 0 deletions pkg/opensearch/opensearch.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,14 @@
package opensearch

import (
"bytes"
"context"
"fmt"
"io"
"net/http"
"net/url"
"path"
"strings"

"github.com/bitly/go-simplejson"
"github.com/grafana/grafana-plugin-sdk-go/backend"
Expand Down Expand Up @@ -166,3 +171,64 @@ func extractParametersFromServiceMapFrames(resp *backend.QueryDataResponse) ([]s
}
return services, operations
}

func (ds *OpenSearchDatasource) CallResource(ctx context.Context, req *backend.CallResourceRequest, sender backend.CallResourceResponseSender) error {
// allowed paths for resource calls:
// - empty string for fetching db version
// - /_mapping for fetching index mapping, e.g. requests going to `index/_mapping`
// - _msearch for executing getTerms queries
// - _mapping for fetching "root" index mappings
if req.Path != "" && !strings.HasSuffix(req.Path, "/_mapping") && req.Path != "_msearch" && req.Path != "_mapping" {
return fmt.Errorf("invalid resource URL: %s", req.Path)
}

osUrl, err := createOpensearchURL(req, req.PluginContext.DataSourceInstanceSettings.URL)
if err != nil {
return err
}

request, err := http.NewRequestWithContext(ctx, req.Method, osUrl, bytes.NewBuffer(req.Body))
if err != nil {
return err
}

response, err := ds.HttpClient.Do(request)
if err != nil {
return err
}

body, err := io.ReadAll(response.Body)
if err != nil {
return err
}

responseHeaders := map[string][]string{
"content-type": {"application/json"},
}

if encoding := response.Header.Get("Content-Encoding"); encoding != "" {
responseHeaders["content-encoding"] = []string{response.Header.Get("Content-Encoding")}
}

return sender.Send(&backend.CallResourceResponse{
Status: response.StatusCode,
Headers: responseHeaders,
Body: body,
})
}

func createOpensearchURL(req *backend.CallResourceRequest, urlStr string) (string, error) {
osUrl, err := url.Parse(urlStr)
if err != nil {
return "", fmt.Errorf("failed to parse data source URL: %s, error: %w", urlStr, err)
}
osUrl.Path = path.Join(osUrl.Path, req.Path)
osUrlString := osUrl.String()
// If the request path is empty and the URL does not end with a slash, add a slash to the URL.
// This ensures that for version checks executed to the root URL, the URL ends with a slash.
// This is helpful, for example, for load balancers that expect URLs to match the pattern /.*.
if req.Path == "" && osUrlString[len(osUrlString)-1:] != "/" {
return osUrl.String() + "/", nil
}
return osUrlString, nil
}
66 changes: 66 additions & 0 deletions src/opensearchDatasource.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1369,6 +1369,72 @@ describe('OpenSearchDatasource', function (this: any) {
});
});

describe('getOpenSearchVersion backend flow', () => {
beforeEach(() => {
// @ts-ignore-next-line
config.featureToggles.openSearchBackendFlowEnabled = true;
});

afterEach(() => {
// @ts-ignore-next-line
config.featureToggles.openSearchBackendFlowEnabled = false;
});
it('should return OpenSearch version', async () => {
const mockResource = jest.fn().mockResolvedValue({
version: { distribution: 'opensearch', number: '2.6.0' },
});
ctx.ds.getResource = mockResource;

const version = await ctx.ds.getOpenSearchVersion();
expect(version.flavor).toBe(Flavor.OpenSearch);
expect(version.version).toBe('2.6.0');
expect(version.label).toBe('OpenSearch 2.6.0');

expect(mockResource.mock.lastCall[0]).toBe('');
});

it('should return ElasticSearch version', async () => {
ctx.ds.getResource = jest.fn().mockResolvedValue({
version: { number: '7.6.0' },
});

const version = await ctx.ds.getOpenSearchVersion();
expect(version.flavor).toBe(Flavor.Elasticsearch);
expect(version.version).toBe('7.6.0');
expect(version.label).toBe('ElasticSearch 7.6.0');
});

it('should error for invalid version', async () => {
ctx.ds.getResource = jest.fn().mockResolvedValue({
version: { number: '7.11.1' },
});
await expect(() => ctx.ds.getOpenSearchVersion()).rejects.toThrow(
'ElasticSearch version 7.11.1 is not supported by the OpenSearch plugin. Use the ElasticSearch plugin.'
);
});

it('should return ElasticSearch for ElasticSearch 7.10.2 without tagline', async () => {
ctx.ds.getResource = jest.fn().mockResolvedValue({
version: { number: '7.10.2' },
});
const version = await ctx.ds.getOpenSearchVersion();
expect(version.flavor).toBe(Flavor.Elasticsearch);
expect(version.version).toBe('7.10.2');
expect(version.label).toBe('ElasticSearch 7.10.2');
});

it('should return OpenSearch for ElasticSearch 7.10.2 with tagline', async () => {
ctx.ds.getResource = jest.fn().mockResolvedValue({
version: { number: '7.10.2' },
tagline: 'The OpenSearch Project: https://opensearch.org/',
});
const version = await ctx.ds.getOpenSearchVersion();
expect(version.flavor).toBe(Flavor.OpenSearch);
expect(version.version).toBe('1.0.0');
expect(version.label).toBe('OpenSearch (compatibility mode)');
});
});

describe('#executeLuceneQueries', () => {
beforeEach(() => {
createDatasource({
Expand Down
71 changes: 41 additions & 30 deletions src/opensearchDatasource.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import _ from 'lodash';
import { from, merge, of, Observable } from 'rxjs';
import { from, merge, of, Observable, lastValueFrom } from 'rxjs';
import { map, tap } from 'rxjs/operators';
import {
DataSourceInstanceSettings,
Expand Down Expand Up @@ -134,7 +134,7 @@
options.headers = headers ?? {};

if (this.basicAuth || this.withCredentials) {
options.withCredentials = true;

Check warning on line 137 in src/opensearchDatasource.ts

View workflow job for this annotation

GitHub Actions / compatibilitycheck

'withCredentials' is deprecated. withCredentials is deprecated in favor of credentials

Check warning on line 137 in src/opensearchDatasource.ts

View workflow job for this annotation

GitHub Actions / compatibilitycheck

'withCredentials' is deprecated. withCredentials is deprecated in favor of credentials
}

if (this.basicAuth) {
Expand All @@ -146,7 +146,7 @@
}

return getBackendSrv()
.datasourceRequest(options)

Check warning on line 149 in src/opensearchDatasource.ts

View workflow job for this annotation

GitHub Actions / compatibilitycheck

'datasourceRequest' is deprecated. Use the fetch function instead

Check warning on line 149 in src/opensearchDatasource.ts

View workflow job for this annotation

GitHub Actions / compatibilitycheck

'datasourceRequest' is deprecated. Use the fetch function instead
.catch((err: any) => {
if (err.data) {
const message = err.data.error?.reason ?? err.data.message ?? 'Unknown error';
Expand Down Expand Up @@ -782,37 +782,48 @@
}

async getOpenSearchVersion(): Promise<Version> {
return await this.request('GET', '/').then((results: any) => {
const newVersion: Version = {
flavor: results.data.version.distribution === 'opensearch' ? Flavor.OpenSearch : Flavor.Elasticsearch,
version: results.data.version.number,
};
newVersion.label = `${AVAILABLE_FLAVORS.find((f) => f.value === newVersion.flavor)?.label || newVersion.flavor} ${
newVersion.version
}`;

// Elasticsearch versions after 7.10 are unsupported
if (newVersion.flavor === Flavor.Elasticsearch && gte(newVersion.version, '7.11.0')) {
throw new Error(
'ElasticSearch version ' +
newVersion.version +
` is not supported by the OpenSearch plugin. Use the ElasticSearch plugin.`
);
}
// @ts-ignore-next-line
const { openSearchBackendFlowEnabled } = config.featureToggles;
const getDbVersionObservable = openSearchBackendFlowEnabled
? lastValueFrom(from(this.getResource('')))
: this.request('GET', '/');
return getDbVersionObservable.then(
(results: any) => {
const data = openSearchBackendFlowEnabled ? results : results.data;
const newVersion: Version = {
flavor: data.version.distribution === 'opensearch' ? Flavor.OpenSearch : Flavor.Elasticsearch,
version: data.version.number,
};
newVersion.label = `${
AVAILABLE_FLAVORS.find((f) => f.value === newVersion.flavor)?.label || newVersion.flavor
} ${newVersion.version}`;

// Elasticsearch versions after 7.10 are unsupported
if (newVersion.flavor === Flavor.Elasticsearch && gte(newVersion.version, '7.11.0')) {
throw new Error(
'ElasticSearch version ' +
newVersion.version +
` is not supported by the OpenSearch plugin. Use the ElasticSearch plugin.`
);
}

// Handle an Opensearch instance in compatibility mode. They report ElasticSearch version 7.10.2 but they still use the OpenSearch tagline
if (
newVersion.flavor === Flavor.Elasticsearch &&
newVersion.version === '7.10.2' &&
results.data.tagline === 'The OpenSearch Project: https://opensearch.org/'
) {
newVersion.flavor = Flavor.OpenSearch;
newVersion.version = '1.0.0';
newVersion.label = 'OpenSearch (compatibility mode)';
}
// Handle an Opensearch instance in compatibility mode. They report ElasticSearch version 7.10.2 but they still use the OpenSearch tagline
if (
newVersion.flavor === Flavor.Elasticsearch &&
newVersion.version === '7.10.2' &&
data.tagline === 'The OpenSearch Project: https://opensearch.org/'
) {
newVersion.flavor = Flavor.OpenSearch;
newVersion.version = '1.0.0';
newVersion.label = 'OpenSearch (compatibility mode)';
}

return newVersion;
});
return newVersion;
},
() => {
throw new Error('Failed to connect to server');
}
);
}

isMetadataField(fieldName: string) {
Expand Down
Loading