mirror of
https://github.com/GreptimeTeam/greptimedb.git
synced 2026-11-26 12:44:10 +00:00
feat(meta): add object-store authority head storage (#10465)
* feat(meta): add object-store authority head storage Signed-off-by: hahaha <a310608318@gmail.com> * refactor(meta): address authority head review feedback Signed-off-by: hahaha <a310608318@gmail.com> * fix: fix Clippy lints Signed-off-by: hahaha <a310608318@gmail.com> --------- Signed-off-by: hahaha <a310608318@gmail.com>
This commit is contained in:
@@ -104,3 +104,4 @@ common-procedure-test.workspace = true
|
||||
common-test-util.workspace = true
|
||||
common-wal = { workspace = true, features = ["testing"] }
|
||||
datatypes.workspace = true
|
||||
object-store = { workspace = true, features = ["testing"] }
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
// limitations under the License.
|
||||
|
||||
pub mod etcd;
|
||||
pub mod object_store;
|
||||
#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
|
||||
pub mod rds;
|
||||
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
//! Authority Head v1 codec and non-retrying conditional object storage.
|
||||
|
||||
mod head;
|
||||
mod probe;
|
||||
mod store;
|
||||
#[cfg(test)]
|
||||
mod tests;
|
||||
|
||||
pub use head::{AuthorityHead, HEAD_FORMAT_VERSION, NodeIdentity};
|
||||
pub use store::{AuthorityState, HeadStore};
|
||||
@@ -0,0 +1,128 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use serde::{Deserialize, Deserializer, Serialize};
|
||||
use snafu::{OptionExt, ResultExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::error::{self, Result};
|
||||
|
||||
/// Persisted Authority Head format supported by this reader and writer.
|
||||
pub const HEAD_FORMAT_VERSION: u32 = 1;
|
||||
|
||||
/// A process identity, generated once at startup and retained by the caller.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct NodeIdentity {
|
||||
pub addr: String,
|
||||
pub incarnation_id: Uuid,
|
||||
}
|
||||
|
||||
impl NodeIdentity {
|
||||
/// Creates a fresh process incarnation, even when the address is reused.
|
||||
pub fn new(addr: String) -> Self {
|
||||
Self {
|
||||
addr,
|
||||
incarnation_id: Uuid::new_v4(),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// Version-one persisted authority payload. Lease deadline is diagnostic only.
|
||||
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
|
||||
pub struct AuthorityHead {
|
||||
pub format_version: u32,
|
||||
// Serde normally treats a missing Option as None. The design requires owner to
|
||||
// be present while still allowing its value to be null.
|
||||
#[serde(deserialize_with = "required_owner")]
|
||||
pub owner: Option<NodeIdentity>,
|
||||
epoch: u64,
|
||||
pub lease_deadline_ms: u64,
|
||||
write_seq: u64,
|
||||
}
|
||||
|
||||
fn required_owner<'de, D: Deserializer<'de>>(
|
||||
deserializer: D,
|
||||
) -> std::result::Result<Option<NodeIdentity>, D::Error> {
|
||||
Option::deserialize(deserializer)
|
||||
}
|
||||
|
||||
impl AuthorityHead {
|
||||
/// Empty Head for explicit initialization of a new namespace.
|
||||
pub fn initial() -> Self {
|
||||
Self {
|
||||
format_version: HEAD_FORMAT_VERSION,
|
||||
owner: None,
|
||||
epoch: 0,
|
||||
lease_deadline_ms: 0,
|
||||
write_seq: 0,
|
||||
}
|
||||
}
|
||||
|
||||
/// Validates the format and encodes compact deterministic JSON.
|
||||
pub fn encode(&self) -> Result<Vec<u8>> {
|
||||
self.validate()?;
|
||||
serde_json::to_vec(self).context(error::AuthorityFormatSnafu {
|
||||
operation: "encode",
|
||||
})
|
||||
}
|
||||
|
||||
/// Decodes required fields and rejects unknown protocol versions.
|
||||
pub fn decode(bytes: &[u8]) -> Result<Self> {
|
||||
let head: Self = serde_json::from_slice(bytes).context(error::AuthorityFormatSnafu {
|
||||
operation: "decode",
|
||||
})?;
|
||||
head.validate()?;
|
||||
Ok(head)
|
||||
}
|
||||
|
||||
fn validate(&self) -> Result<()> {
|
||||
if self.format_version != HEAD_FORMAT_VERSION {
|
||||
return error::AuthorityVersionSnafu {
|
||||
version: self.format_version,
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Returns the logical epoch in this payload.
|
||||
pub fn epoch(&self) -> u64 {
|
||||
self.epoch
|
||||
}
|
||||
|
||||
/// Returns the write sequence in this payload.
|
||||
pub fn write_seq(&self) -> u64 {
|
||||
self.write_seq
|
||||
}
|
||||
|
||||
/// Returns a payload with its epoch advanced, rejecting overflow before mutation.
|
||||
pub fn with_next_epoch(mut self) -> Result<Self> {
|
||||
self.epoch = self
|
||||
.epoch
|
||||
.checked_add(1)
|
||||
.context(error::AuthorityOverflowSnafu { counter: "epoch" })?;
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Returns a payload with its write sequence advanced, rejecting overflow.
|
||||
pub fn with_next_write_seq(mut self) -> Result<Self> {
|
||||
self.write_seq = self
|
||||
.write_seq
|
||||
.checked_add(1)
|
||||
.context(error::AuthorityOverflowSnafu {
|
||||
counter: "write_seq",
|
||||
})?;
|
||||
Ok(self)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use common_telemetry::warn;
|
||||
use object_store::util;
|
||||
use object_store::{ErrorKind, Metadata};
|
||||
use snafu::{IntoError, ResultExt};
|
||||
use uuid::Uuid;
|
||||
|
||||
use crate::election::object_store::{AuthorityHead, AuthorityState, HeadStore};
|
||||
use crate::error::{self, Result};
|
||||
use crate::metrics::METRIC_AUTHORITY_STORAGE_EVENTS;
|
||||
|
||||
impl HeadStore {
|
||||
pub(crate) fn check_capabilities(&self) -> Result<()> {
|
||||
let info = self.operator.info();
|
||||
let scheme = info.scheme();
|
||||
// TODO(alorun): Replace the allow-list with capability-based admission after
|
||||
// GCS passes real-endpoint generation-based conditional-write qualification.
|
||||
let reason = match scheme {
|
||||
"s3" | "azblob" => None,
|
||||
"gcs" => {
|
||||
Some("GCS generation-based conditional writes require real-endpoint validation")
|
||||
}
|
||||
"oss" => Some("OSS PutObject rejects If-Match and If-None-Match conditions"),
|
||||
"fs" | "memory" => {
|
||||
Some("backend lacks the required atomic conditional replacement semantics")
|
||||
}
|
||||
_ => Some("backend has not been qualified for Authority Head conditional replacement"),
|
||||
};
|
||||
if let Some(reason) = reason {
|
||||
return error::AuthorityCapabilitySnafu { scheme, reason }.fail();
|
||||
}
|
||||
let c = info.capability();
|
||||
if !(c.read
|
||||
&& c.write
|
||||
&& c.list
|
||||
&& c.delete
|
||||
&& c.write_with_if_not_exists
|
||||
&& (c.write_with_if_version_match || c.write_with_if_match))
|
||||
{
|
||||
return error::AuthorityCapabilitySnafu {
|
||||
scheme,
|
||||
reason: "read/write/list/delete and atomic conditional create/replace are required",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn probe_conditional_writes(&self) -> Result<()> {
|
||||
let path = util::join_path(&self.probe_prefix, &format!("{}.json", Uuid::new_v4()));
|
||||
let result = self.probe_at(&path).await;
|
||||
let cleanup = self.cleanup_probe(&path).await;
|
||||
if result.is_err() {
|
||||
METRIC_AUTHORITY_STORAGE_EVENTS
|
||||
.with_label_values(&["probe_failure"])
|
||||
.inc();
|
||||
if let Err(error) = cleanup {
|
||||
warn!(error; "Authority probe cleanup also failed");
|
||||
}
|
||||
return result;
|
||||
}
|
||||
cleanup
|
||||
}
|
||||
|
||||
async fn probe_at(&self, path: &str) -> Result<()> {
|
||||
let initial = AuthorityHead::initial();
|
||||
self.create_at(path, &initial).await?;
|
||||
let first = self.read_at(path).await?;
|
||||
self.require_probe(first.head() == &initial, "initial contents differ")?;
|
||||
let next = initial.clone().with_next_write_seq()?;
|
||||
match self.create_at(path, &next).await {
|
||||
Err(error)
|
||||
if matches!(
|
||||
error.authority_storage_error().map(|e| e.kind()),
|
||||
Some(ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists)
|
||||
) => {}
|
||||
Err(error) => return Err(error),
|
||||
Ok(()) => {
|
||||
return error::AuthorityProbeSnafu {
|
||||
reason: "duplicate create was accepted",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
let unchanged = self.read_at(path).await?;
|
||||
self.verify_probe(&unchanged, &initial, first.metadata(), true)?;
|
||||
self.replace_at(path, &first, &next).await?;
|
||||
let current = self.read_at(path).await?;
|
||||
self.verify_probe(¤t, &next, first.metadata(), false)?;
|
||||
let stale = next.clone().with_next_write_seq()?;
|
||||
match self.replace_at(path, &first, &stale).await {
|
||||
Err(error)
|
||||
if error.authority_storage_error().map(|e| e.kind())
|
||||
== Some(ErrorKind::ConditionNotMatch) => {}
|
||||
Err(error) => return Err(error),
|
||||
Ok(()) => {
|
||||
return error::AuthorityProbeSnafu {
|
||||
reason: "stale replacement was accepted",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
}
|
||||
let unchanged = self.read_at(path).await?;
|
||||
self.verify_probe(&unchanged, &next, current.metadata(), true)?;
|
||||
// Exercise plain PUT and listing permission, without using listing for authority.
|
||||
self.operator
|
||||
.write(path, stale.encode()?)
|
||||
.await
|
||||
.context(error::AuthorityStorageSnafu {
|
||||
operation: "probe plain write",
|
||||
})?;
|
||||
let plain = self.read_at(path).await?;
|
||||
self.verify_probe(&plain, &stale, current.metadata(), false)?;
|
||||
self.operator
|
||||
.list(&self.probe_prefix)
|
||||
.await
|
||||
.context(error::AuthorityStorageSnafu {
|
||||
operation: "probe list",
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn verify_probe(
|
||||
&self,
|
||||
state: &AuthorityState,
|
||||
expected: &AuthorityHead,
|
||||
metadata: &Metadata,
|
||||
same: bool,
|
||||
) -> Result<()> {
|
||||
self.require_probe(
|
||||
state.head() == expected && self.same_version(state.metadata(), metadata)? == same,
|
||||
"contents or condition identity differ from expected",
|
||||
)
|
||||
}
|
||||
|
||||
fn require_probe(&self, valid: bool, reason: &'static str) -> Result<()> {
|
||||
if !valid {
|
||||
return error::AuthorityProbeSnafu { reason }.fail();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub(crate) async fn cleanup_probe(&self, path: &str) -> Result<()> {
|
||||
self.operator.delete(path).await.map_err(|error| {
|
||||
METRIC_AUTHORITY_STORAGE_EVENTS
|
||||
.with_label_values(&["probe_cleanup_failure"])
|
||||
.inc();
|
||||
error::AuthorityStorageSnafu {
|
||||
operation: "probe cleanup",
|
||||
}
|
||||
.into_error(error)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,247 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
use common_error::ext::BoxedError;
|
||||
use object_store::config::ObjectStoreConfig;
|
||||
use object_store::factory;
|
||||
use object_store::util;
|
||||
use object_store::{ErrorKind, Metadata, ObjectStore};
|
||||
use snafu::{IntoError, OptionExt, ResultExt};
|
||||
|
||||
use crate::election::object_store::AuthorityHead;
|
||||
use crate::error::{self, Result};
|
||||
use crate::metrics::METRIC_AUTHORITY_STORAGE_EVENTS;
|
||||
|
||||
/// A coherent read. Only this module can pair the payload and response metadata.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct AuthorityState {
|
||||
head: AuthorityHead,
|
||||
metadata: Metadata,
|
||||
scope: Arc<StoreScope>,
|
||||
path: String,
|
||||
}
|
||||
|
||||
impl AuthorityState {
|
||||
/// Payload observed by this read.
|
||||
pub fn head(&self) -> &AuthorityHead {
|
||||
&self.head
|
||||
}
|
||||
/// Complete metadata returned by the same read.
|
||||
pub fn metadata(&self) -> &Metadata {
|
||||
&self.metadata
|
||||
}
|
||||
}
|
||||
|
||||
/// Protocol-specific storage. Writes are never transparently retried.
|
||||
pub struct HeadStore {
|
||||
pub(crate) operator: ObjectStore,
|
||||
pub(crate) head_path: String,
|
||||
pub(crate) probe_prefix: String,
|
||||
scope: Arc<StoreScope>,
|
||||
}
|
||||
|
||||
// A fresh allocation identifies the store instance that produced each state.
|
||||
#[derive(Debug)]
|
||||
struct StoreScope;
|
||||
|
||||
enum ConditionIdentity<'a> {
|
||||
Version(&'a str),
|
||||
Etag(&'a str),
|
||||
}
|
||||
|
||||
impl HeadStore {
|
||||
/// Opens storage without creating or changing the official Head.
|
||||
///
|
||||
/// Every call performs remote capability probes. Initialize once at node startup
|
||||
/// and share this instance. An `AuthorityState` is bound to the instance that read
|
||||
/// it; conditional replacement must use that same instance.
|
||||
///
|
||||
/// `prefix` is relative to the configured storage root, which is applied once by
|
||||
/// the operator. An empty prefix is for an exclusively owned root. Clusters sharing
|
||||
/// a root must use non-empty, unique, stable prefixes. Path joining collapses
|
||||
/// repeated `/` separators and preserves at most one leading `/`; that leading `/`
|
||||
/// is still resolved within the operator root, not the host filesystem root.
|
||||
pub async fn open(config: &ObjectStoreConfig, data_home: &str, prefix: &str) -> Result<Self> {
|
||||
let operator = factory::new_raw_object_store(config, data_home)
|
||||
.await
|
||||
.context(error::AuthorityOpenSnafu)?;
|
||||
let store = Self::new(operator, prefix);
|
||||
store.check_capabilities()?;
|
||||
store.probe_conditional_writes().await?;
|
||||
Ok(store)
|
||||
}
|
||||
|
||||
// The only Head operator layer assembly site, shared by open() and fault tests.
|
||||
// The input must be raw: never add RetryLayer or clone a general-purpose operator.
|
||||
fn new(operator: ObjectStore, prefix: &str) -> Self {
|
||||
let operator = util::with_instrument_layers(operator, false);
|
||||
Self {
|
||||
operator,
|
||||
head_path: util::join_path(prefix, "authority/head.json"),
|
||||
probe_prefix: util::join_dir(prefix, "probes"),
|
||||
scope: Arc::new(StoreScope),
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub(crate) fn new_for_test(operator: ObjectStore, prefix: &str) -> Self {
|
||||
Self::new(operator, prefix)
|
||||
}
|
||||
|
||||
/// Reads one full response and its metadata; absence requires operator recovery.
|
||||
pub async fn read_head(&self) -> Result<AuthorityState> {
|
||||
self.read_at(&self.head_path).await
|
||||
}
|
||||
|
||||
/// Explicit create-only initialization. Normal reads never call this method.
|
||||
/// Read back with [`Self::read_head`] when payload and metadata are needed.
|
||||
pub async fn create_initial_head(&self) -> Result<()> {
|
||||
self.create_at(&self.head_path, &AuthorityHead::initial())
|
||||
.await
|
||||
}
|
||||
|
||||
/// Replaces the observed version. Term and owner checks belong to the authority.
|
||||
/// Success confirms the PUT only; a subsequent [`Self::read_head`] reports its own result.
|
||||
pub async fn replace_head(
|
||||
&self,
|
||||
expected: &AuthorityState,
|
||||
next: &AuthorityHead,
|
||||
) -> Result<()> {
|
||||
self.replace_at(&self.head_path, expected, next).await
|
||||
}
|
||||
|
||||
/// Compares opaque conditional identities. Equality does not resolve a timed-out write.
|
||||
pub fn same_version(&self, left: &Metadata, right: &Metadata) -> Result<bool> {
|
||||
let left = self.identity(left)?;
|
||||
let right = self.identity(right)?;
|
||||
match (left, right) {
|
||||
(ConditionIdentity::Version(left), ConditionIdentity::Version(right))
|
||||
| (ConditionIdentity::Etag(left), ConditionIdentity::Etag(right)) => Ok(left == right),
|
||||
_ => error::AuthorityMetadataSnafu {
|
||||
reason: "incomparable condition identities",
|
||||
}
|
||||
.fail(),
|
||||
}
|
||||
}
|
||||
|
||||
fn identity<'a>(&self, metadata: &'a Metadata) -> Result<ConditionIdentity<'a>> {
|
||||
let capability = self.operator.info().capability();
|
||||
if capability.write_with_if_version_match
|
||||
&& let Some(version) = metadata.version()
|
||||
{
|
||||
if version.is_empty() {
|
||||
return error::AuthorityMetadataSnafu {
|
||||
reason: "empty native condition identity",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
return Ok(ConditionIdentity::Version(version));
|
||||
}
|
||||
if capability.write_with_if_match
|
||||
&& let Some(etag) = metadata.etag()
|
||||
&& !etag.is_empty()
|
||||
{
|
||||
return Ok(ConditionIdentity::Etag(etag));
|
||||
}
|
||||
error::AuthorityMetadataSnafu {
|
||||
reason: "missing supported conditional identity",
|
||||
}
|
||||
.fail()
|
||||
}
|
||||
|
||||
pub(crate) async fn read_at(&self, path: &str) -> Result<AuthorityState> {
|
||||
let read = async {
|
||||
let reader = self.operator.reader(path).await?;
|
||||
let body = reader.read(..).await?;
|
||||
Ok::<_, object_store::Error>((body, reader.metadata().cloned()))
|
||||
}
|
||||
.await;
|
||||
let (body, metadata) = read.map_err(|error| {
|
||||
if error.kind() == ErrorKind::NotFound {
|
||||
error::AuthorityMissingSnafu { path }.into_error(error)
|
||||
} else {
|
||||
error::AuthorityStorageSnafu { operation: "read" }.into_error(error)
|
||||
}
|
||||
})?;
|
||||
let metadata = metadata.context(error::AuthorityMetadataSnafu {
|
||||
reason: "read returned no metadata",
|
||||
})?;
|
||||
self.identity(&metadata)?;
|
||||
if metadata.last_modified().is_none() {
|
||||
return error::AuthorityMetadataSnafu {
|
||||
reason: "read returned no last_modified",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
let head = AuthorityHead::decode(&body.to_vec()).map_err(|source| {
|
||||
error::AuthorityReadHeadSnafu { path }.into_error(BoxedError::new(source))
|
||||
})?;
|
||||
Ok(AuthorityState {
|
||||
head,
|
||||
metadata,
|
||||
scope: self.scope.clone(),
|
||||
path: path.into(),
|
||||
})
|
||||
}
|
||||
|
||||
pub(crate) async fn create_at(&self, path: &str, head: &AuthorityHead) -> Result<()> {
|
||||
self.write_result(
|
||||
self.operator
|
||||
.write_with(path, head.encode()?)
|
||||
.if_not_exists(true)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) async fn replace_at(
|
||||
&self,
|
||||
path: &str,
|
||||
expected: &AuthorityState,
|
||||
next: &AuthorityHead,
|
||||
) -> Result<()> {
|
||||
if !Arc::ptr_eq(&self.scope, &expected.scope) || expected.path != path {
|
||||
return error::AuthorityMetadataSnafu {
|
||||
reason: "state belongs to another storage instance or path",
|
||||
}
|
||||
.fail();
|
||||
}
|
||||
self.identity(&expected.metadata)?;
|
||||
self.write_result(
|
||||
self.operator
|
||||
.write_with(path, next.encode()?)
|
||||
.if_not_changed(&expected.metadata)
|
||||
.await,
|
||||
)
|
||||
}
|
||||
|
||||
fn write_result(&self, result: object_store::Result<Metadata>) -> Result<()> {
|
||||
result.map(|_| ()).map_err(|error| {
|
||||
let outcome = match error.kind() {
|
||||
ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists | ErrorKind::Conflict => {
|
||||
"conflict"
|
||||
}
|
||||
_ if error.is_temporary() || error.kind() == ErrorKind::Unexpected => {
|
||||
"unknown_write"
|
||||
}
|
||||
_ => "write_error",
|
||||
};
|
||||
METRIC_AUTHORITY_STORAGE_EVENTS
|
||||
.with_label_values(&[outcome])
|
||||
.inc();
|
||||
error::AuthorityStorageSnafu { operation: "write" }.into_error(error)
|
||||
})
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -1066,6 +1066,89 @@ pub enum Error {
|
||||
reason: String,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to {} Authority Head JSON", operation))]
|
||||
AuthorityFormat {
|
||||
operation: &'static str,
|
||||
#[snafu(source)]
|
||||
error: serde_json::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to decode Authority Head at {}", path))]
|
||||
AuthorityReadHead {
|
||||
path: String,
|
||||
source: BoxedError,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Unsupported Authority Head format version: {}", version))]
|
||||
AuthorityVersion {
|
||||
version: u32,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority Head counter overflow: {}", counter))]
|
||||
AuthorityOverflow {
|
||||
counter: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority Head is missing at {}; operator recovery is required", path))]
|
||||
AuthorityMissing {
|
||||
path: String,
|
||||
#[snafu(source)]
|
||||
error: object_store::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority Head metadata is unusable: {}", reason))]
|
||||
AuthorityMetadata {
|
||||
reason: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display(
|
||||
"Object store {} is not admitted for Authority Head: {}",
|
||||
scheme,
|
||||
reason
|
||||
))]
|
||||
AuthorityCapability {
|
||||
scheme: &'static str,
|
||||
reason: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority storage probe failed: {}", reason))]
|
||||
AuthorityProbe {
|
||||
reason: &'static str,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Authority storage request failed: {}", operation))]
|
||||
AuthorityStorage {
|
||||
operation: &'static str,
|
||||
#[snafu(source)]
|
||||
error: object_store::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to open Authority storage"))]
|
||||
AuthorityOpen {
|
||||
#[snafu(source)]
|
||||
error: object_store::error::Error,
|
||||
#[snafu(implicit)]
|
||||
location: Location,
|
||||
},
|
||||
|
||||
#[snafu(display("Failed to write object, file path: {}", file_path))]
|
||||
WriteObject {
|
||||
#[snafu(implicit)]
|
||||
@@ -1243,6 +1326,15 @@ impl ErrorExt for Error {
|
||||
| ElectionLeaderLeaseExpired { .. }
|
||||
| ElectionLeaderLeaseChanged { .. } => StatusCode::Internal,
|
||||
|
||||
AuthorityFormat { .. } | AuthorityVersion { .. } | AuthorityOverflow { .. } => {
|
||||
StatusCode::IllegalState
|
||||
}
|
||||
AuthorityReadHead { source, .. } => source.status_code(),
|
||||
AuthorityCapability { .. } | AuthorityProbe { .. } => StatusCode::Unsupported,
|
||||
AuthorityMissing { .. }
|
||||
| AuthorityMetadata { .. }
|
||||
| AuthorityStorage { .. }
|
||||
| AuthorityOpen { .. } => StatusCode::StorageUnavailable,
|
||||
NoLeader { .. } => StatusCode::TableUnavailable,
|
||||
ValueNotExist { .. }
|
||||
| ProcedurePoisonConflict { .. }
|
||||
@@ -1459,6 +1551,16 @@ impl ErrorExt for Error {
|
||||
}
|
||||
|
||||
impl Error {
|
||||
/// Returns the original Authority request error without inviting write replay.
|
||||
pub fn authority_storage_error(&self) -> Option<&object_store::Error> {
|
||||
match self {
|
||||
Self::AuthorityStorage { error, .. } | Self::AuthorityMissing { error, .. } => {
|
||||
Some(error)
|
||||
}
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "pg_kvbackend", feature = "mysql_kvbackend"))]
|
||||
/// Check if the error is a serialization error.
|
||||
pub fn is_serialization_error(&self) -> bool {
|
||||
|
||||
@@ -23,6 +23,9 @@ pub const STATS_TYPE_NO_REGION_METADATA: &str = "no_region_metadata";
|
||||
pub const STATS_TYPE_REGION_NOT_OPEN: &str = "region_not_open";
|
||||
|
||||
lazy_static! {
|
||||
pub static ref METRIC_AUTHORITY_STORAGE_EVENTS: IntCounterVec = register_int_counter_vec!(
|
||||
"greptime_meta_authority_storage_events", "Authority storage failures and conflicts", &["outcome"]
|
||||
).unwrap();
|
||||
pub static ref METRIC_META_TXN_REQUEST: HistogramVec = register_histogram_vec!(
|
||||
"greptime_meta_txn_request",
|
||||
"meta txn request",
|
||||
|
||||
@@ -20,9 +20,13 @@ use std::sync::{Arc, Mutex};
|
||||
use derive_builder::Builder;
|
||||
pub use oio::*;
|
||||
pub use opendal::raw::{
|
||||
Layer, OpCopy, OpDelete, OpList, OpRead, OpWrite, RpRead, Service, Servicer, oio,
|
||||
Layer, OpCopy, OpCreateDir, OpDelete, OpList, OpPresign, OpRead, OpRename, OpStat, OpWrite,
|
||||
RpCreateDir, RpPresign, RpRead, RpRename, RpStat, Service, Servicer, Timestamp, oio,
|
||||
};
|
||||
pub use opendal::{
|
||||
Buffer, BytesRange, Capability, Error, ErrorKind, Metadata, MetadataBuilder, OperationContext,
|
||||
Result,
|
||||
};
|
||||
pub use opendal::{Buffer, BytesRange, Error, ErrorKind, Metadata, OperationContext, Result};
|
||||
|
||||
pub type MockWriterFactory = Arc<dyn Fn(&str, OpWrite, oio::Writer) -> oio::Writer + Send + Sync>;
|
||||
pub type MockReaderFactory = Arc<dyn Fn(&str, OpRead, oio::Reader) -> oio::Reader + Send + Sync>;
|
||||
|
||||
@@ -15,8 +15,8 @@
|
||||
pub use opendal::raw::{Service, ServiceInfo, Servicer};
|
||||
pub use opendal::{
|
||||
Buffer, Builder as ObjectStoreBuilder, Entry, EntryMode, Error, ErrorKind, FuturesAsyncReader,
|
||||
FuturesAsyncWriter, HttpTransporter, Lister, OperationContext, Operator as ObjectStore, Reader,
|
||||
Result, Writer, services,
|
||||
FuturesAsyncWriter, HttpTransporter, Lister, Metadata, OperationContext,
|
||||
Operator as ObjectStore, Reader, Result, Writer, services,
|
||||
};
|
||||
|
||||
pub mod config;
|
||||
|
||||
@@ -42,6 +42,7 @@ mod repartition_expr_version;
|
||||
mod export_logical_tables;
|
||||
mod mysql;
|
||||
mod native_prefix;
|
||||
mod object_store_authority;
|
||||
mod object_store_wal;
|
||||
mod reconciliation_event;
|
||||
mod view_ddl_event;
|
||||
|
||||
@@ -0,0 +1,91 @@
|
||||
// Copyright 2023 Greptime Team
|
||||
//
|
||||
// Licensed under the Apache License, Version 2.0 (the "License");
|
||||
// you may not use this file except in compliance with the License.
|
||||
// You may obtain a copy of the License at
|
||||
//
|
||||
// http://www.apache.org/licenses/LICENSE-2.0
|
||||
//
|
||||
// Unless required by applicable law or agreed to in writing, software
|
||||
// distributed under the License is distributed on an "AS IS" BASIS,
|
||||
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
// See the License for the specific language governing permissions and
|
||||
// limitations under the License.
|
||||
|
||||
use common_meta::election::object_store::{AuthorityHead, HeadStore};
|
||||
use object_store::ErrorKind;
|
||||
use tests_integration::test_util::{StorageType, get_test_store_config};
|
||||
|
||||
/// Requires an explicitly configured S3-compatible endpoint (MinIO for PR1 qualification).
|
||||
#[tokio::test]
|
||||
async fn test_minio_head_storage() {
|
||||
if !StorageType::S3.test_on() {
|
||||
common_telemetry::init_default_ut_logging();
|
||||
common_telemetry::warn!(
|
||||
"NOT RUN: Authority storage qualification requires configured S3/MinIO"
|
||||
);
|
||||
return;
|
||||
}
|
||||
for name in [
|
||||
"GT_S3_BUCKET",
|
||||
"GT_S3_ACCESS_KEY_ID",
|
||||
"GT_S3_ACCESS_KEY",
|
||||
"GT_S3_REGION",
|
||||
] {
|
||||
assert!(
|
||||
std::env::var_os(name).is_some(),
|
||||
"Missing {name}; this test requires real storage"
|
||||
);
|
||||
}
|
||||
let (config, _guard) = get_test_store_config(&StorageType::S3);
|
||||
let store = HeadStore::open(&config, "", "authority-test")
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(
|
||||
store
|
||||
.read_head()
|
||||
.await
|
||||
.unwrap_err()
|
||||
.authority_storage_error()
|
||||
.unwrap()
|
||||
.kind(),
|
||||
ErrorKind::NotFound
|
||||
);
|
||||
store.create_initial_head().await.unwrap();
|
||||
let initial = store.read_head().await.unwrap();
|
||||
assert_eq!(initial.head(), &AuthorityHead::initial());
|
||||
assert!(initial.metadata().last_modified().is_some());
|
||||
assert!(initial.metadata().etag().unwrap().starts_with('"'));
|
||||
let e = store.create_initial_head().await.unwrap_err();
|
||||
assert!(matches!(
|
||||
e.authority_storage_error().unwrap().kind(),
|
||||
ErrorKind::ConditionNotMatch | ErrorKind::AlreadyExists
|
||||
));
|
||||
let next = initial.head().clone().with_next_write_seq().unwrap();
|
||||
store.replace_head(&initial, &next).await.unwrap();
|
||||
let current = store.read_head().await.unwrap();
|
||||
assert_eq!(current.head(), &next);
|
||||
assert!(current.metadata().last_modified().is_some());
|
||||
assert!(
|
||||
!store
|
||||
.same_version(initial.metadata(), current.metadata())
|
||||
.unwrap()
|
||||
);
|
||||
assert_eq!(
|
||||
store
|
||||
.replace_head(&initial, &next)
|
||||
.await
|
||||
.unwrap_err()
|
||||
.authority_storage_error()
|
||||
.unwrap()
|
||||
.kind(),
|
||||
ErrorKind::ConditionNotMatch
|
||||
);
|
||||
let after = store.read_head().await.unwrap();
|
||||
assert_eq!(after.head(), &next);
|
||||
assert!(
|
||||
store
|
||||
.same_version(after.metadata(), current.metadata())
|
||||
.unwrap()
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user