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

feat: add mysql election logic #5694

Open
wants to merge 15 commits into
base: main
Choose a base branch
from

Conversation

CookiePieWw
Copy link
Collaborator

@CookiePieWw CookiePieWw commented Mar 12, 2025

I hereby agree to the terms of the GreptimeDB CLA.

Refer to a related PR or issue link (optional)

#5528

What's changed and what's your intention?

As title.

PR Checklist

Please convert it to a draft if some of the following conditions are not met.

  • I have written the necessary rustdoc comments.
  • I have added the necessary unit tests and integration tests.
  • This PR requires documentation updates.
  • API changes are backward compatible.
  • Schema or data changes are backward compatible.

Copy link
Contributor

coderabbitai bot commented Mar 12, 2025

Important

Review skipped

Auto reviews are disabled on this repository.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.


Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Generate unit testing code for this file.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai generate unit testing code for this file.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and generate unit testing code.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@github-actions github-actions bot added the docs-not-required This change does not impact docs. label Mar 12, 2025
@CookiePieWw CookiePieWw marked this pull request as ready for review March 17, 2025 02:40
@CookiePieWw CookiePieWw requested review from MichaelScofield and a team as code owners March 17, 2025 02:40
fn create_table_sql(&self) -> String {
format!(
r#"
CREATE TABLE IF NOT EXISTS {} (
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Better quote the table name in all places:

Suggested change
CREATE TABLE IF NOT EXISTS {} (
CREATE TABLE IF NOT EXISTS `{}` (

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

all the SQLs below should be quoted, too

}

impl MySqlElection {
pub async fn with_mysql_client(
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Does the mysql sqls and features in use compatible across all mysql versions? If not, or for future compatible consideration, I suggest check mysql version and some of the critical options first. We can target for the most widely used mysql version, 5.7, or the current stable 8.0.

Copy link
Collaborator Author

@CookiePieWw CookiePieWw Mar 17, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I ran sqlness test locally for mysql 8.0, and the sqlness test for ci uses a mysql 5.7, so it should be alright for now. Do we need a compatible check or just leave some comments for future changes?

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think a check beforehand is needed, to not cause any runtime surprise to users after metasrv is started. WDYT @fengjiachun

Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

That sounds good. I think we can check it before the metasrv starts.

@WenyXu WenyXu self-requested a review March 17, 2025 09:33
sqlx::query(&sql_factory.create_table_sql())
.execute(&mut client)
.await
.context(MySqlExecutionSnafu)?;
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we add the exeucted sql to MySqlExecutionSnafu?

Comment on lines +386 to +388
if !res {
self.delete_value(&key, &mut executor).await?;
self.put_value_with_lease(
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if !res {
self.delete_value(&key, &mut executor).await?;
self.put_value_with_lease(
if !res {
warn!("Candidate {} already registered, delete and register again.", key);
self.delete_value(&key, &mut executor).await?;
self.put_value_with_lease(

Comment on lines +401 to +427
loop {
let _ = keep_alive_interval.tick().await;
let client = self.client.lock().await;
let mut executor = Executor::Default(client);
let (_, prev_expire_time, current_time, origin) = self
.get_value_with_lease(&key, true, &mut executor)
.await?
.unwrap_or_default();

ensure!(
prev_expire_time > current_time,
UnexpectedSnafu {
violated: format!(
"Candidate lease expired at {:?} (current time: {:?}), key: {:?}",
prev_expire_time,
current_time,
String::from_utf8_lossy(&key.into_bytes())
),
}
);

// Safety: origin is Some since we are using `get_value_with_lease` with `true`.
let origin = origin.unwrap();
self.update_value_with_lease(&key, &origin, &node_info, &mut executor)
.await?;
std::mem::drop(executor);
}
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

use scope

Suggested change
loop {
let _ = keep_alive_interval.tick().await;
let client = self.client.lock().await;
let mut executor = Executor::Default(client);
let (_, prev_expire_time, current_time, origin) = self
.get_value_with_lease(&key, true, &mut executor)
.await?
.unwrap_or_default();
ensure!(
prev_expire_time > current_time,
UnexpectedSnafu {
violated: format!(
"Candidate lease expired at {:?} (current time: {:?}), key: {:?}",
prev_expire_time,
current_time,
String::from_utf8_lossy(&key.into_bytes())
),
}
);
// Safety: origin is Some since we are using `get_value_with_lease` with `true`.
let origin = origin.unwrap();
self.update_value_with_lease(&key, &origin, &node_info, &mut executor)
.await?;
std::mem::drop(executor);
}
loop {
let _ = keep_alive_interval.tick().await;
let client = self.client.lock().await;
{
let mut executor = Executor::Default(client);
let (_, prev_expire_time, current_time, origin) = self
.get_value_with_lease(&key, true, &mut executor)
.await?
.unwrap_or_default();
ensure!(
prev_expire_time > current_time,
UnexpectedSnafu {
violated: format!(
"Candidate lease expired at {:?} (current time: {:?}), key: {:?}",
prev_expire_time,
current_time,
String::from_utf8_lossy(&key.into_bytes())
),
}
);
// Safety: origin is Some since we are using `get_value_with_lease` with `true`.
let origin = origin.unwrap();
self.update_value_with_lease(&key, &origin, &node_info, &mut executor)
.await?;
}
}

Comment on lines +189 to +194
.context(UnexpectedSnafu {
violated: format!(
"Invalid value {}, expect node info || {} || expire time",
value, LEASE_SEP
),
})?;
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
.context(UnexpectedSnafu {
violated: format!(
"Invalid value {}, expect node info || {} || expire time",
value, LEASE_SEP
),
})?;
.with_context(|| UnexpectedSnafu {
violated: format!(
"Invalid value {}, expect node info || {} || expire time",
value, LEASE_SEP
),
})?;

}

enum Executor<'a> {
Default(MutexGuard<'a, MySqlConnection>),
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Why not always use the txn? The election is racing against other metasrv process.

@@ -579,6 +579,9 @@ jobs:
- name: "Pg Kvbackend"
opts: "--setup-pg"
kafka: false
- name: "Mysql Kvbackend"
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- name: "Mysql Kvbackend"
- name: "MySQL KvBackend"

@@ -579,6 +579,9 @@ jobs:
- name: "Pg Kvbackend"
Copy link
Collaborator

@fengjiachun fengjiachun Mar 18, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
- name: "Pg Kvbackend"
- name: "PostgreSQL KvBackend"

// Currently the session timeout is longer than the leader lease time.
// So the leader will renew the lease twice before the session timeout if everything goes well.
fn set_idle_session_timeout_sql(&self) -> String {
format!("SET idle_session_timeout = '{}s';", META_LEASE_SECS + 1)
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

👍🏻

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
docs-not-required This change does not impact docs.
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants