-
Notifications
You must be signed in to change notification settings - Fork 2.4k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[processor/geoip] Add maxmind geoprovider (#33451)
**Description:** <Describe what has changed.> This PR adds an initial implementation for the MaxMind GeoIP provider for later usage in the `geoipprocessor`. The processor is still a nop, as no provider can be configured yet. Providers configuration will be added in #33268. - Internal package for temporal attributes conventions reference (should be removed in favor of open-telemetry/semantic-conventions#1116): `processor/geoipprocessor/internal/convention/attributes.go` - [geoip2-golang](https://github.com/oschwald/geoip2-golang) package used as a client for data retrieval. See recommended MaxMind clients: https://dev.maxmind.com/geoip/docs/databases#api-clients **Link to tracking Issue:** <Issue number if applicable> #32663 **Testing:** <Describe what testing was performed and which tests were added.> Database files are generated before running the unit tests [using MaxMind writer.](https://github.com/maxmind/MaxMind-DB/tree/0a9c1aa26cd7b91bee2efe27e7d174797d8211a6/test-data#how-to-generate-test-data). The generation time of those files seems not to be an issue (0.189s): ``` $ go test -v === RUN TestInvalidNewProvider --- PASS: TestInvalidNewProvider (0.00s) === RUN TestProviderLocation === PAUSE TestProviderLocation === CONT TestProviderLocation === RUN TestProviderLocation/nil_IP_address === RUN TestProviderLocation/unsupported_database_type === RUN TestProviderLocation/no_IP_metadata_in_database === RUN TestProviderLocation/all_attributes_should_be_present_for_IPv4_using_GeoLite2-City_database === RUN TestProviderLocation/subset_attributes_for_IPv6_IP_using_GeoIP2-City_database --- PASS: TestProviderLocation (0.00s) --- PASS: TestProviderLocation/nil_IP_address (0.00s) --- PASS: TestProviderLocation/unsupported_database_type (0.00s) --- PASS: TestProviderLocation/no_IP_metadata_in_database (0.00s) --- PASS: TestProviderLocation/all_attributes_should_be_present_for_IPv4_using_GeoLite2-City_database (0.00s) --- PASS: TestProviderLocation/subset_attributes_for_IPv6_IP_using_GeoIP2-City_database (0.00s) PASS ok github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/provider/maxmindprovider 0.189s ``` Testing database files are removed on sucessful test execution. **Documentation:** <Describe the documentation added.> README.md file
- Loading branch information
Showing
25 changed files
with
546 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
# Use this changelog template to create an entry for release notes. | ||
|
||
# One of 'breaking', 'deprecation', 'new_component', 'enhancement', 'bug_fix' | ||
change_type: enhancement | ||
|
||
# The name of the component, or a single word describing the area of concern, (e.g. filelogreceiver) | ||
component: geoipprocessor | ||
|
||
# A brief description of the change. Surround your text with quotes ("") if it needs to start with a backtick (`). | ||
note: Add MaxMind geoip provider for GeoIP2-City and GeoLite2-City databases. | ||
|
||
# Mandatory: One or more tracking issues related to the change. You can use the PR number here if no issue exists. | ||
issues: [32663] | ||
|
||
# (Optional) One or more lines of additional information to render under the primary note. | ||
# These lines will be padded with 2 spaces and then inserted directly into the document. | ||
# Use pipe (|) for multiline entries. | ||
subtext: | ||
|
||
# If your change doesn't affect end users or the exported elements of any package, | ||
# you should instead start your pull request title with [chore] or use the "Skip Changelog" label. | ||
# Optional: The change log or logs in which this entry should be included. | ||
# e.g. '[user]' or '[user, api]' | ||
# Include 'user' if the change is relevant to end users. | ||
# Include 'api' if there is a change to a library API. | ||
# Default: '[user]' | ||
change_logs: [] |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
40 changes: 40 additions & 0 deletions
40
processor/geoipprocessor/internal/convention/attributes.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,40 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package conventions // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/convention" | ||
|
||
// TODO: replace for semconv once https://github.com/open-telemetry/semantic-conventions/issues/1033 is closed. | ||
const ( | ||
// AttributeGeoCityName represents the attribute name for the city name in geographical data. | ||
AttributeGeoCityName = "geo.city_name" | ||
|
||
// AttributeGeoPostalCode represents the attribute name for the city postal code. | ||
AttributeGeoPostalCode = "geo.postal_code" | ||
|
||
// AttributeGeoCountryName represents the attribute name for the country name in geographical data. | ||
AttributeGeoCountryName = "geo.country_name" | ||
|
||
// AttributeGeoCountryIsoCode represents the attribute name for the Two-letter ISO Country Code. | ||
AttributeGeoCountryIsoCode = "geo.country_iso_code" | ||
|
||
// AttributeGeoContinentName represents the attribute name for the continent name in geographical data. | ||
AttributeGeoContinentName = "geo.continent_name" | ||
|
||
// AttributeGeoContinentIsoCode represents the attribute name for the Two-letter Continent Code. | ||
AttributeGeoContinentCode = "geo.continent_code" | ||
|
||
// AttributeGeoRegionName represents the attribute name for the region name in geographical data. | ||
AttributeGeoRegionName = "geo.region_name" | ||
|
||
// AttributeGeoRegionIsoCode represents the attribute name for the Two-letter ISO Region Code. | ||
AttributeGeoRegionIsoCode = "geo.region_iso_code" | ||
|
||
// AttributeGeoTimezone represents the attribute name for the timezone. | ||
AttributeGeoTimezone = "geo.timezone" | ||
|
||
// AttributeGeoLocationLat represents the attribute name for the latitude. | ||
AttributeGeoLocationLat = "geo.location.lat" | ||
|
||
// AttributeGeoLocationLon represents the attribute name for the longitude. | ||
AttributeGeoLocationLon = "geo.location.lon" | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
14 changes: 14 additions & 0 deletions
14
processor/geoipprocessor/internal/provider/maxmindprovider/README.md
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,14 @@ | ||
# MaxMind GeoIP Provider | ||
|
||
This package provides a MaxMind GeoIP provider for use with the OpenTelemetry GeoIP processor. It leverages the [geoip2-golang package](https://github.com/oschwald/geoip2-golang) to query geographical information associated with IP addresses from MaxMind databases. See recommended clients: https://dev.maxmind.com/geoip/docs/databases#api-clients | ||
|
||
# Features | ||
|
||
- Supports GeoIP2-City and GeoLite2-City database types. | ||
- Retrieves and returns geographical metadata for a given IP address. The generated attributes follow the internal [Geo conventions](../../convention/attributes.go). | ||
|
||
## Configuration | ||
|
||
The following configuration must be provided: | ||
|
||
- `database_path`: local file path to a GeoIP2-City or GeoLite2-City database. |
27 changes: 27 additions & 0 deletions
27
processor/geoipprocessor/internal/provider/maxmindprovider/config.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,27 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package maxmind // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/provider/maxmindprovider" | ||
|
||
import ( | ||
"errors" | ||
|
||
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/provider" | ||
) | ||
|
||
// Config defines configuration for MaxMind provider. | ||
type Config struct { | ||
// DatabasePath section allows specifying a local GeoIP database | ||
// file to retrieve the geographical metadata from. | ||
DatabasePath string `mapstructure:"database_path"` | ||
} | ||
|
||
var _ provider.Config = (*Config)(nil) | ||
|
||
// Validate implements provider.Config. | ||
func (c *Config) Validate() error { | ||
if c.DatabasePath == "" { | ||
return errors.New("a local geoIP database path must be provided") | ||
} | ||
return nil | ||
} |
103 changes: 103 additions & 0 deletions
103
processor/geoipprocessor/internal/provider/maxmindprovider/provider.go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,103 @@ | ||
// Copyright The OpenTelemetry Authors | ||
// SPDX-License-Identifier: Apache-2.0 | ||
|
||
package maxmind // import "github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/provider/maxmindprovider" | ||
|
||
import ( | ||
"context" | ||
"errors" | ||
"fmt" | ||
"net" | ||
|
||
"github.com/oschwald/geoip2-golang" | ||
"go.opentelemetry.io/otel/attribute" | ||
|
||
conventions "github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/convention" | ||
"github.com/open-telemetry/opentelemetry-collector-contrib/processor/geoipprocessor/internal/provider" | ||
) | ||
|
||
var ( | ||
// defaultLanguageCode specifies English as the default Geolocation language code, see https://dev.maxmind.com/geoip/docs/web-services/responses#languages | ||
defaultLanguageCode = "en" | ||
geoIP2CityDBType = "GeoIP2-City" | ||
geoLite2CityDBType = "GeoLite2-City" | ||
|
||
errUnsupportedDB = errors.New("unsupported geo IP database type") | ||
errNoMetadataFound = errors.New("no geo IP metadata found") | ||
) | ||
|
||
type maxMindProvider struct { | ||
geoReader *geoip2.Reader | ||
// language code to be used in name retrieval, e.g. "en" or "pt-BR" | ||
langCode string | ||
} | ||
|
||
var _ provider.GeoIPProvider = (*maxMindProvider)(nil) | ||
|
||
func newMaxMindProvider(cfg *Config) (*maxMindProvider, error) { | ||
geoReader, err := geoip2.Open(cfg.DatabasePath) | ||
if err != nil { | ||
return nil, fmt.Errorf("could not open geoip database: %w", err) | ||
} | ||
|
||
return &maxMindProvider{geoReader: geoReader, langCode: defaultLanguageCode}, nil | ||
} | ||
|
||
// Location implements provider.GeoIPProvider for MaxMind. If a non City database type is used or no metadata is found in the database, an error will be returned. | ||
func (g *maxMindProvider) Location(_ context.Context, ipAddress net.IP) (attribute.Set, error) { | ||
switch g.geoReader.Metadata().DatabaseType { | ||
case geoIP2CityDBType, geoLite2CityDBType: | ||
attrs, err := g.cityAttributes(ipAddress) | ||
if err != nil { | ||
return attribute.Set{}, err | ||
} else if len(*attrs) == 0 { | ||
return attribute.Set{}, errNoMetadataFound | ||
} | ||
return attribute.NewSet(*attrs...), nil | ||
default: | ||
return attribute.Set{}, fmt.Errorf("%w type: %s", errUnsupportedDB, g.geoReader.Metadata().DatabaseType) | ||
} | ||
} | ||
|
||
// cityAttributes returns a list of key-values containing geographical metadata associated to the provided IP. The key names are populated using the internal geo IP conventions package. If the an invalid or nil IP is provided, an error is returned. | ||
func (g *maxMindProvider) cityAttributes(ipAddress net.IP) (*[]attribute.KeyValue, error) { | ||
attributes := make([]attribute.KeyValue, 0, 11) | ||
|
||
city, err := g.geoReader.City(ipAddress) | ||
if err != nil { | ||
return nil, err | ||
} | ||
|
||
// The exact set of top-level keys varies based on the particular GeoIP2 web service you are using. If a key maps to an undefined or empty value, it is not included in the JSON object. The following anonymous function appends the given key-value only if the value is not empty. | ||
appendIfNotEmpty := func(keyName, value string) { | ||
if value != "" { | ||
attributes = append(attributes, attribute.String(keyName, value)) | ||
} | ||
} | ||
|
||
// city | ||
appendIfNotEmpty(conventions.AttributeGeoCityName, city.City.Names[g.langCode]) | ||
// country | ||
appendIfNotEmpty(conventions.AttributeGeoCountryName, city.Country.Names[g.langCode]) | ||
appendIfNotEmpty(conventions.AttributeGeoCountryIsoCode, city.Country.IsoCode) | ||
// continent | ||
appendIfNotEmpty(conventions.AttributeGeoContinentName, city.Continent.Names[g.langCode]) | ||
appendIfNotEmpty(conventions.AttributeGeoContinentCode, city.Continent.Code) | ||
// postal code | ||
appendIfNotEmpty(conventions.AttributeGeoPostalCode, city.Postal.Code) | ||
// region | ||
if len(city.Subdivisions) > 0 { | ||
// The most specific subdivision is located at the last array position, see https://github.com/maxmind/GeoIP2-java/blob/2fe4c65424fed2c3c2449e5530381b6452b0560f/src/main/java/com/maxmind/geoip2/model/AbstractCityResponse.java#L112 | ||
mostSpecificSubdivision := city.Subdivisions[len(city.Subdivisions)-1] | ||
appendIfNotEmpty(conventions.AttributeGeoRegionName, mostSpecificSubdivision.Names[g.langCode]) | ||
appendIfNotEmpty(conventions.AttributeGeoRegionIsoCode, mostSpecificSubdivision.IsoCode) | ||
} | ||
|
||
// location | ||
appendIfNotEmpty(conventions.AttributeGeoTimezone, city.Location.TimeZone) | ||
if city.Location.Latitude != 0 && city.Location.Longitude != 0 { | ||
attributes = append(attributes, attribute.Float64(conventions.AttributeGeoLocationLat, city.Location.Latitude), attribute.Float64(conventions.AttributeGeoLocationLon, city.Location.Longitude)) | ||
} | ||
|
||
return &attributes, err | ||
} |
Oops, something went wrong.