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

Refactor database naming strategy #42

Merged
merged 1 commit into from
Jul 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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,12 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## Unreleased

### Added

- `PostgresDatabase` Resource - Add database naming strategy [#38](https://github.com/mruoss/kompost/pull/38), [#42](https://github.com/mruoss/kompost/pull/42)

## [0.3.0] - 2023-07-13

### Changed
Expand Down
61 changes: 40 additions & 21 deletions docs/postgres/postgres_database.md
Original file line number Diff line number Diff line change
Expand Up @@ -10,22 +10,6 @@ Once your [`PostgresInstance`](postgres_instance.md) or
[`PostgresClusterInstance`](postgres_cluster_instance.md) is set up and
connected, you can declare your database resources.

```yaml
apiVersion: kompost.chuge.li/v1alpha1
kind: PostgresDatabase
metadata:
name: some-database
namespace: default
spec:
instanceRef:
name: staging-server
```

Based on the CRD definition above, it will create a database called `default_some_database`,
where the appended prefix `default_` is the previously informed namespaced.
To avoid the use of the namespace you can set the `usingPrefixNamingStrategy`
attribute to false. See example bellow:

```yaml
apiVersion: kompost.chuge.li/v1alpha1
kind: PostgresDatabase
Expand All @@ -35,11 +19,8 @@ metadata:
spec:
instanceRef:
name: staging-server
usingPrefixNamingStrategy: false
```

In this case the final name of the database will be `some_database`.

## Connection Details

Once applied to the cluster, Kompost creates a database and **two users**. One
Expand Down Expand Up @@ -85,6 +66,44 @@ data:
DB_USER: ZGVmYXVsdF9zb21lX2RhdGFiYXNlX2FwcA==
```

## Database Naming Strategy

The field `databaseNamingStrategy` controls how the database name is derived
from the resource name. Possible values are `resource_name` and
`prefix_namespace`. The default strategy is `prefix_namespace`.

### Strategies

- `resource_name`: Use the resource name as database name
- `prefix_namespace`: Prefix the resource name with the namespace to get a
cluster-wide unique name.

### Example

Taking the [basic usage example](#basic-usage) from above, the resulting
database on the server is named `default_some_database`.

```yaml
apiVersion: kompost.chuge.li/v1alpha1
kind: PostgresDatabase
metadata:
name: some-database
namespace: default
spec:
instanceRef:
name: staging-server
databaseNamingStrategy: resource_name
```

The resulting database on the server is named `some_database`.

!!! warning Strategy resource_name can lead to conflicts

Using the `resource_name` strategy can lead to conflicts. If you define
`PostgresDatabase` resources with the same name in different namespaces,
both resources would control the same database on the server. Therefore the
default strategy is `prefix_namespace`

## Deletion Policy - Abandoning Underlying Resources

When using Kompost on a live environment, you might want to protect the
Expand All @@ -103,7 +122,7 @@ metadata:
kompost.chuge.li/deletion-policy: abandon # <-- underlying resources are abandoned (not deleted) when this resource gets deleted
spec:
instanceRef:
name: staging-server
name: staging-server
```

## Database Creation Parameters
Expand All @@ -113,7 +132,7 @@ parameters](https://www.postgresql.org/docs/current/sql-createdatabase.html)
when creating a database. Some of these parameters are supported by Kompost and
can be passed in `spec.params`.

!!! note Creation params cannot be changed
!!! note Creation params cannot be changed

These parameters are only used when the database is created. Kompost therefore denies requests to change them on an existing resource.

Expand Down
15 changes: 10 additions & 5 deletions lib/kompost/kompo/postgres/controller/database_controller.ex
Original file line number Diff line number Diff line change
Expand Up @@ -37,10 +37,11 @@ defmodule Kompost.Kompo.Postgres.Controller.DatabaseController do
resource = axn.resource
namespace = resource["metadata"]["namespace"]

using_prefix_strategy? =
resource["spec"]["usingPrefixNamingStrategy"] != "true"
db_name =
Database.name(resource,
strategy: resource["spec"]["databaseNamingStrategy"] || "prefix_namespace"
)

db_name = Database.name(resource, prefix_namespace: using_prefix_strategy?)
db_params = Params.new!(resource["spec"]["params"] || %{})
instance = resource |> instance_id() |> Instance.lookup()

Expand Down Expand Up @@ -136,8 +137,12 @@ defmodule Kompost.Kompo.Postgres.Controller.DatabaseController do
@spec delete_resources(Bonny.Axn.t()) :: {:ok, Bonny.Axn.t()} | {:error, Bonny.Axn.t()}
def delete_resources(axn) do
resource = axn.resource
using_prefix_strategy? = resource["spec"]["usingPrefixNamingStrategy"] != "true"
db_name = Database.name(resource, prefix_namespace: using_prefix_strategy?)

db_name =
Database.name(resource,
strategy: resource["spec"]["databaseNamingStrategy"] || "prefix_namespace"
)

users = resource["status"]["users"]
instance = resource |> instance_id() |> Instance.lookup()

Expand Down
14 changes: 6 additions & 8 deletions lib/kompost/kompo/postgres/database.ex
Original file line number Diff line number Diff line change
Expand Up @@ -15,25 +15,23 @@ defmodule Kompost.Kompo.Postgres.Database do
"default_foo_bar"

iex> resource = %{"metadata" => %{"namespace" => "default", "name" => "foo-bar"}}
...> Kompost.Kompo.Postgres.Database.name(resource, prefix_namespace: false)
...> Kompost.Kompo.Postgres.Database.name(resource, strategy: "resource_name")
"foo_bar"
"""
@spec name(map(), Keyword.t()) :: binary()
def name(resource, opts \\ [])

def name(resource, opts) do
prefix_namespace = Keyword.get(opts, :prefix_namespace, true)

case prefix_namespace do
true ->
case Keyword.get(opts, :strategy, "prefix_namespace") do
"resource_name" ->
Slugger.slugify_downcase(
"#{resource["metadata"]["namespace"]}_#{resource["metadata"]["name"]}",
"#{resource["metadata"]["name"]}",
?_
)

_ ->
"prefix_namespace" ->
Slugger.slugify_downcase(
"#{resource["metadata"]["name"]}",
"#{resource["metadata"]["namespace"]}_#{resource["metadata"]["name"]}",
?_
)
end
Expand Down
6 changes: 4 additions & 2 deletions lib/kompost/kompo/postgres/v1alpha1/postgres_database.ex
Original file line number Diff line number Diff line change
Expand Up @@ -24,8 +24,6 @@ defmodule Kompost.Kompo.Postgres.V1Alpha1.PostgresDatabase do
- required: ["instanceRef"]
- required: ["clusterInstanceRef"]
properties:
usingPrefixNamingStrategy:
type: boolean
instanceRef:
type: object
properties:
Expand All @@ -36,6 +34,10 @@ defmodule Kompost.Kompo.Postgres.V1Alpha1.PostgresDatabase do
properties:
name:
type: string
databaseNamingStrategy:
type: string
enum: ["resource_name", "prefix_namespace"]
description: "(Optional) Strategy to derive the name of the `database` on the server. resource_name uses the resource name as DB name. `prefix_namespace` prefixes the resource name with the namespace. Defaults to `prefix_namespace`"
params:
description: "Parameters passed to CREATE TEMPLATE."
type: object
Expand Down
8 changes: 6 additions & 2 deletions priv/manifest/postgresdatabase.crd.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,10 @@ spec:
name:
type: string
type: object
databaseNamingStrategy:
type: string
enum: ["resource_name", "prefix_namespace"]
description: "(Optional) Strategy to derive the name of the `database` on the server. resource_name uses the resource name as DB name. `prefix_namespace` prefixes the resource name with the namespace. Defaults to `prefix_namespace`"
params:
description: Parameters passed to CREATE TEMPLATE.
properties:
Expand Down Expand Up @@ -84,8 +88,8 @@ spec:
type: string
status:
enum:
- 'True'
- 'False'
- "True"
- "False"
type: string
type:
type: string
Expand Down
Loading