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: update codis fe / proxy with tls; topom updated #2383

Open
wants to merge 27 commits into
base: unstable
Choose a base branch
from

Conversation

kolinfluence
Copy link

@kolinfluence kolinfluence commented Feb 1, 2024

codis fe / proxy tls + topom update

Summary by CodeRabbit

  • New Features

    • Added TLS configuration options for secure communication (--tls-cert, --tls-key, --tls=N).
    • Introduced TLS support for the proxy server including configuration and listener creation.
    • Enhanced Redis Sentinel configuration settings for improved reliability.
  • Bug Fixes

    • Improved lock release logic in Topom struct to handle token-based releases.
  • Refactor

    • Updated Proxy struct to include TLS-related fields.
    • Adjusted listener creation logic to handle TLS configuration.

@github-actions github-actions bot added 🧹 Updates This will not be worked on Invalid PR Title labels Feb 1, 2024
@kolinfluence kolinfluence changed the title codis fe / proxy tls + topom update feat: update codis fe / proxy with tls; topom updated Feb 2, 2024
@sprappcom
Copy link

@AlexStocks please look into it.

codis/config/dashboard.toml Outdated Show resolved Hide resolved
codis/pkg/proxy/.proxy.go.swo Outdated Show resolved Hide resolved
codis/admin/.codis-fe-admin.sh.swo Outdated Show resolved Hide resolved
codis/cert.pem Outdated
Copy link
Collaborator

Choose a reason for hiding this comment

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

It's better not to provide the public key file. Instead, you can add a generation command in the readme.

Copy link
Author

Choose a reason for hiding this comment

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

@machinly the public key file is definitely a dummy one.
you put "filesystem" as default, surely a dummy version is fine right? ... maybe you can modify with error message generated when there's no cert / key files present after you merge this and delete them. will that do fine?

Copy link
Collaborator

Choose a reason for hiding this comment

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

Do not modify the default configuration

Copy link
Author

Choose a reason for hiding this comment

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

can you only pull what is needed?

codis/key.pem Outdated
Copy link
Collaborator

Choose a reason for hiding this comment

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

It's better not to provide the private key file. Instead, you can add a generation command in the readme.

jodis_name = ""
jodis_addr = ""
jodis_name = "etcd"
jodis_addr = "127.0.0.1:2379"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do not modify the default parameter values

Copy link
Author

Choose a reason for hiding this comment

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

can you only pull what is needed?

@@ -25,8 +25,10 @@ const DefaultConfig = `
# Set Coordinator, only accept "zookeeper" & "etcd" & "filesystem".
# for zookeeper/etcd, coorinator_auth accept "user:password"
# Quick Start
coordinator_name = "filesystem"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do not modify the default parameter values

Copy link
Author

Choose a reason for hiding this comment

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

can you only pull what is needed?

codis/pkg/models/store.go Outdated Show resolved Hide resolved
# slow command list e.g. hgetall, mset
slow_cmd_list = ""
# quick command list
quick_cmd_list = "get,set"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Do not modify the default configuration

CODIS_FE_ADDR="0.0.0.0:9090"
CODIS_FE_TLS=1
CODIS_FE_TLS_KEY="/usr/local/src/pika/codis/key.pem"
Copy link
Collaborator

Choose a reason for hiding this comment

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

Comment this code

Copy link
Author

Choose a reason for hiding this comment

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

Can you help add the rest?

@kolinfluence
Copy link
Author

noted. will revert.

@github-actions github-actions bot added the ✏️ Feature New feature or request label Mar 14, 2024
@luky116
Copy link
Collaborator

luky116 commented Apr 21, 2024

Judging from your code, you want to add the TLS protocol to the redis protocol port of the proxy layer. If so, can dashboard and fe not add TLS? Because they interact through the http protocol, the proxy's redis protocol port is only responsible for the user's redis client connection.

@kolinfluence
Copy link
Author

kolinfluence commented Apr 21, 2024

@luky116 sorry was busy playing with lru benchmark tests update here so a bit lagged behind on pika (but it's on my radar daily).
https://github.com/cloudxaas/gocache/tree/main/lrux/bytes
need fast lru. (promoting it coz may be able to be used in codis too and would hope for improvement to make it faster, kind of applicable to cache)

back to your question...

  1. the dashboard and fe is added for remote users to the dashboard and fe. it's optional configuration parameter. if you set tls = true, then it will do the tls feature, else wont affect performance at runtime.

  2. it'll be useful for wider adoption considering a lot of dev can remotely access their dashboard / fe etc knowing it's more secure. basically it wont affect the runtime performance.

  3. dashboard and fe why not add tls to interact with https protocol too?
    ok i see your point. so maybe we can also do a tlsfe = 1, tlsdashboard = 1, tlspika = 1 etc kind of parameter too. we can allow http/https to run concurrently without affecting performance and the fe/dashboard choosing which to connect to.

good?

@kolinfluence
Copy link
Author

kolinfluence commented Apr 21, 2024

proxy cannot connect?

image

you need to use redis-cli with secure tls to connect put
redis-cli --tls
as option parameter

pls remember it will only use tls for proxy if it's set to true. so accordingly, we will need to put tls-something for everything else etc where we want tls to have. so maybe tls-pika = true in future when pika has tls? but proxy shld definitely have tls.

@AlexStocks
Copy link
Collaborator

@CodiumAI-Agent /review

@CodiumAI-Agent
Copy link

PR Review 🔍

⏱️ Estimated effort to review [1-5]

4, because the PR involves multiple files with significant changes including the introduction of TLS in the network layer, modifications to configuration handling, and updates to the proxy and topom modules. The complexity of the changes and the security implications of correctly implementing TLS require careful review to ensure reliability and security.

🧪 Relevant tests

No

⚡ Possible issues

Possible Bug: The error handling in the TLS setup could be improved by providing more specific error messages or handling specific types of errors differently.

Performance Concern: The introduction of TLS might impact the performance due to encryption overhead. It would be beneficial to benchmark the performance before and after these changes to ensure that the impact is within acceptable limits.

🔒 Security concerns

No

Code feedback:
relevant filecodis/cmd/fe/main.go
suggestion      

Consider setting more fields in the tls.Config to ensure better security, such as MinVersion to enforce the use of TLS 1.2 or higher. This helps prevent the use of older, less secure versions of TLS. [important]

relevant lineCertificates: []tls.Certificate{cert},

relevant filecodis/pkg/proxy/proxy.go
suggestion      

Add error logging before returning the error when the TLS certificate fails to load. This will help in debugging issues related to TLS configuration by providing a clear log message about what went wrong. [important]

relevant linereturn errors.Trace(err)

relevant filecodis/pkg/models/store.go
suggestion      

Implement error handling for the case when Decode returns nil but no error. This could potentially lead to a situation where the function proceeds without a valid token, which might not be the intended behavior. [medium]

relevant lineif t.Token == token {

relevant filecodis/pkg/topom/topom.go
suggestion      

Add validation for the input byte slice b in the Decode function to check if it's nil or empty before attempting to decode it. This prevents unnecessary processing and potential errors when dealing with empty data. [medium]

relevant lineif err := jsonDecode(s, b); err != nil {

@AlexStocks
Copy link
Collaborator

@CodiumAI-Agent /improve

@CodiumAI-Agent
Copy link

PR Code Suggestions ✨

CategorySuggestion                                                                                                                                    Score
Security
Remove the private key from the codebase to enhance security

It is highly insecure to store private keys within the codebase, especially in plaintext
format. This can lead to security vulnerabilities as unauthorized users could potentially
access sensitive information. Consider using environment variables or a secure vault
solution to manage private keys.

codis/key.pem [1-28]

------BEGIN PRIVATE KEY-----
-MIIEvAIBADANBgkqhkiG9w0BAQEFAASCBKYwggSiAgEAAoIBAQClOgprziC/+nQe
-...
------END PRIVATE KEY-----
+# Private key securely stored outside of the codebase
 
Suggestion importance[1-10]: 10

Why: Storing private keys in the codebase is a significant security risk. Using environment variables or secure vault solutions is a best practice to prevent unauthorized access to sensitive information.

10
Possible bug
Add checks for TLS certificate and key file paths before loading them

Consider adding a check for the --tls-cert and --tls-key flags before attempting to load
the TLS key pair. This ensures that the necessary parameters are provided, avoiding
runtime panics due to missing arguments.

codis/cmd/fe/main.go [205]

-cert, err := tls.LoadX509KeyPair(utils.ArgumentMust(d, "--tls-cert"), utils.ArgumentMust(d, "--tls-key"))
+certFile, keyFile := utils.ArgumentMust(d, "--tls-cert"), utils.ArgumentMust(d, "--tls-key")
+if certFile == "" || keyFile == "" {
+    log.Panic("TLS certificate or key file path must be provided")
+}
+cert, err := tls.LoadX509KeyPair(certFile, keyFile)
 
Suggestion importance[1-10]: 9

Why: This suggestion addresses a potential runtime panic by ensuring that the necessary TLS certificate and key file paths are provided before attempting to load them. This is a crucial check that enhances the robustness of the code.

9
Ensure safe token comparison by checking for nil after decoding

Add error handling for the Decode function to ensure that the token comparison only occurs
if the decoding is successful. This prevents potential nil pointer dereferences.

codis/pkg/models/store.go [133-138]

-t, err := Decode(b); 
+t, err := Decode(b)
 if err != nil {
     return err
 }
-if t.Token == token {
+if t != nil && t.Token == token {
     return s.Release()
 }
 
Suggestion importance[1-10]: 8

Why: This suggestion prevents potential nil pointer dereferences by ensuring that the token comparison only occurs if the decoding is successful. This is an important fix to avoid runtime errors.

8
Enhancement
Improve error handling for IP replacement to manage failures more effectively

Add error handling for utils.ReplaceUnspecifiedIP to handle potential failures gracefully
instead of only logging the error. This ensures that the function's failure is properly
managed.

codis/pkg/proxy/proxy.go [145-147]

 x, err := utils.ReplaceUnspecifiedIP(proto, l.Addr().String(), config.HostProxy)
 if err != nil {
+    log.Errorf("Failed to replace unspecified IP: %s", err)
     return err
 }
 
Suggestion importance[1-10]: 7

Why: The suggestion improves error handling by logging the error and returning it, which helps in debugging and ensures that failures are managed properly. However, it is a minor enhancement rather than a critical fix.

7
Wrap errors in the Decode function to enhance error information

Add error wrapping in the Decode function to provide more context about the error, which
can be useful for debugging.

codis/pkg/topom/topom.go [24-25]

 if err := jsonDecode(s, b); err != nil {
-    return nil,err
+    return nil, fmt.Errorf("json decode error: %w", err)
 }
 
Suggestion importance[1-10]: 6

Why: The suggestion enhances error information by wrapping errors with additional context. This is useful for debugging but is a minor improvement.

6

@sprappcom
Copy link

will get back next week.

i was wondering if i can also improve the whole net thing with gnet. the performance will be much faster.

https://github.com/panjf2000/gnet

what do u guys think?

Copy link

coderabbitai bot commented Jul 5, 2024

Warning

Rate limit exceeded

@kolinfluence has exceeded the limit for the number of commits or files that can be reviewed per hour. Please wait 20 minutes and 2 seconds before requesting another review.

How to resolve this issue?

After the wait time has elapsed, a review can be triggered using the @coderabbitai review command as a PR comment. Alternatively, push new commits to this PR.

We recommend that you space out your commits to avoid hitting the rate limit.

How do rate limits work?

CodeRabbit enforces hourly rate limits for each developer per organization.

Our paid plans have higher rate limits than the trial, open-source and free plans. In all cases, we re-allow further reviews after a brief timeout.

Please see our FAQ for further information.

Commits

Files that changed from the base of the PR and between 1a4e5c4 and c491c6a.

Walkthrough

The changes introduce TLS support for secure communication across various components of the Codis project. This involves updates to configuration files, enhancements to proxy and main function logic, and modifications to the Store and Topom structs for improved locking and decoding functionalities.

Changes

File Change Summary
codis/cmd/fe/main.go Added TLS configuration, options for TLS certificate and key, and modified listener logic for TLS support.
codis/config/proxy.toml Introduced TLS configuration options for the proxy with proxy_tls, proxy_tls_cert, and proxy_tls_key.
codis/pkg/models/proxy.go Added TLS-related fields to the Proxy struct.
codis/pkg/models/store.go Added ReleaseByToken method to the Store struct.
codis/pkg/models/topom.go Added Decode function to the Topom struct.
codis/pkg/proxy/config.go Added TLS-related fields and variables to the Config struct.
codis/pkg/proxy/proxy.go Introduced TLS support in the proxy server, adjusting the setup method for TLS configuration.
codis/pkg/topom/config.go Enhanced Redis Sentinel configuration settings for improved failover and server state checking intervals.
codis/pkg/topom/topom.go Modified Close method in Topom struct to use ReleaseByToken for releasing locks with token.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Main as Main.go
    participant Proxy as Proxy.go
    participant Config as Config.go

    User->>Main: Start Codis Server
    Main->>Config: Load Configuration
    Main->>Proxy: Initialize Proxy with Config
    alt TLS Enabled
        Proxy->>Config: Check TLS Settings
        Proxy->>Proxy: Load TLS Certificate and Key
        Proxy->>Proxy: Create TLS Listener
    else TLS Disabled
        Proxy->>Proxy: Create Standard Listener
    end
    Proxy->>User: Server Ready
Loading

Poem

In Codis lands where data flows,
Secure channels now will grow.
With TLS we guard the gates,
Protecting secrets, thwarting fates.
Proxies strengthened, new paths arise,
As tokens lock and errors paralyze.
Codis evolves to safer shores,
A haven built for data stores.


Thank you for using CodeRabbit. We offer it for free to the OSS community and would appreciate your support in helping us grow. If you find it useful, would you consider giving us a shout-out on your favorite social media?

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>.
    • 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 generate interesting stats about this repository and render them as a table.
    • @coderabbitai show all the console.log statements in this repository.
    • @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 as 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 resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Additionally, you can add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.

CodeRabbit Configration File (.coderabbit.yaml)

  • You can programmatically configure CodeRabbit by adding a .coderabbit.yaml file to the root of your repository.
  • Please see the configuration documentation for more information.
  • If your editor has YAML language server enabled, you can add the path at the top of this file to enable auto-completion and validation: # yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json

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.

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Outside diff range and nitpick comments (2)
codis/cmd/fe/main.go (2)

7-7: Ensure proper import aliasing.

Consider aliasing the tls import to avoid potential name conflicts.

import (
	cryptoTLS "crypto/tls"
	// other imports
)

60-60: Update usage message to reflect new TLS options.

The usage message should clearly describe the new TLS options.

-	--listen=ADDR                   set the listen address.
+	--listen=ADDR                   set the listen address.
+	--tls-cert=FILE                 set the TLS certificate file.
+	--tls-key=FILE                  set the TLS key file.
+	--tls=N                         set to 1 to enable TLS, 0 to disable.
Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between a885758 and e8f24eb.

Files ignored due to path filters (2)
  • codis/cert.pem is excluded by !**/*.pem
  • codis/key.pem is excluded by !**/*.pem
Files selected for processing (10)
  • codis/admin/codis-fe-admin.sh (2 hunks)
  • codis/cmd/fe/main.go (3 hunks)
  • codis/config/proxy.toml (1 hunks)
  • codis/pkg/models/proxy.go (1 hunks)
  • codis/pkg/models/store.go (1 hunks)
  • codis/pkg/models/topom.go (1 hunks)
  • codis/pkg/proxy/config.go (2 hunks)
  • codis/pkg/proxy/proxy.go (2 hunks)
  • codis/pkg/topom/config.go (2 hunks)
  • codis/pkg/topom/topom.go (1 hunks)
Additional comments not posted (16)
codis/pkg/models/topom.go (1)

Line range hint 15-17:
LGTM!

The Encode function looks good.

codis/pkg/models/proxy.go (3)

14-14: LGTM!

The addition of the ProxyTLS field looks good.


15-15: LGTM!

The addition of the ProxyTLSCert field looks good.


16-16: LGTM!

The addition of the ProxyTLSKey field looks good.

codis/admin/codis-fe-admin.sh (2)

21-21: LGTM!

The addition of the CODIS_FE_TLS variable looks good.


22-23: LGTM!

The addition of the CODIS_FE_TLS_KEY and CODIS_FE_TLS_CERT variables looks good.

codis/config/proxy.toml (3)

24-24: LGTM!

The addition of the proxy_tls field looks good.


25-25: LGTM!

The addition of the proxy_tls_cert field looks good.


26-26: LGTM!

The addition of the proxy_tls_key field looks good.

codis/pkg/proxy/config.go (2)

40-42: Verify the TLS configuration defaults.

The new TLS configuration options are commented out by default. Ensure that the default values are appropriate and secure.


172-174: Confirm the addition of TLS configuration fields.

The new fields for TLS configuration have been added to the Config struct. Ensure that these fields are correctly used and validated in the code.

codis/pkg/proxy/proxy.go (5)

7-7: Verify the necessity of the crypto/tls import.

The crypto/tls package has been imported to handle TLS functionality. Ensure that it is used correctly and is necessary for the changes implemented.


107-110: Initialize l and err variables appropriately.

The l and err variables are declared without initialization. Ensure that they are correctly initialized before use.


111-130: Ensure proper error handling and logging for TLS setup.

The TLS setup includes loading certificates and creating a TLS listener. Verify that errors are correctly handled and logged.


132-137: Ensure proper error handling and logging for non-TLS setup.

The non-TLS setup includes creating a standard listener. Verify that errors are correctly handled and logged.


141-153: Confirm common setup for both TLS and non-TLS listeners.

The common setup for both TLS and non-TLS listeners includes updating the proxy model and replacing unspecified IP addresses. Ensure that this setup is correctly implemented.

Comment on lines 126 to 143
func (s *Store) ReleaseByToken(token string) error {
b, err := s.client.Read(s.LockPath(),false)
if err != nil {
return err
}

if b != nil {
t, err := Decode(b);
if err != nil {
return err
}
if t.Token == token {
return s.Release()
}
}

return nil
}
Copy link

@coderabbitai coderabbitai bot Jul 5, 2024

Choose a reason for hiding this comment

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

Reduce nesting and improve readability.

The nested if statements can be reduced to improve readability.

func (s *Store) ReleaseByToken(token string) error {
	b, err := s.client.Read(s.LockPath(), false)
	if err != nil {
		return err
	}
	if b == nil {
		return nil
	}

	t, err := Decode(b)
	if err != nil {
		return err
	}
	if t.Token == token {
		return s.Release()
	}
	return nil
}

Copy link
Author

Choose a reason for hiding this comment

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

@coderabbitai no. nesting is fine here.

Copy link

Choose a reason for hiding this comment

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

@kolinfluence Understood, I'll respect your decision to keep the nesting as is. If you need any further assistance, feel free to ask.

Comment on lines 22 to 27
func Decode(b []byte) (*Topom, error) {
s := &Topom{}
if err := jsonDecode(s, b); err != nil {
return nil,err
}
return s,nil
Copy link

Choose a reason for hiding this comment

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

Fix formatting issues.

There are minor formatting issues in the Decode function. Ensure there is a space after the comma in the return statements.

-    return nil,err
+    return nil, err

-    return s,nil
+    return s, nil
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
func Decode(b []byte) (*Topom, error) {
s := &Topom{}
if err := jsonDecode(s, b); err != nil {
return nil,err
}
return s,nil
func Decode(b []byte) (*Topom, error) {
s := &Topom{}
if err := jsonDecode(s, b); err != nil {
return nil, err
}
return s, nil

sentinel_check_server_state_interval = "10s"
sentinel_check_master_failover_interval = "2s"
sentinel_master_dead_check_times = 10
sentinel_check_offline_server_interval = "2s"
Copy link

Choose a reason for hiding this comment

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

Tip

Codebase Verification

Ensure new configuration setting is used.

The new configuration setting sentinel_check_offline_server_interval is defined but not used anywhere in the codebase. Please ensure that this setting is utilized where necessary or remove it if it is not required.

  • codis/pkg/topom/config.go: Definition found, but no usage detected.
Analysis chain

Ensure new configuration setting is used.

The new configuration setting sentinel_check_offline_server_interval should be used in the code. Verify its usage or remove it if unnecessary.

Scripts executed

The following scripts were executed for the analysis:

Script:

#!/bin/bash
# Description: Verify the usage of the new configuration setting `sentinel_check_offline_server_interval`.

# Test: Search for the usage of the new configuration setting. Expect: At least one occurrence.
rg --type go 'sentinel_check_offline_server_interval'

Length of output: 300


Script:

#!/bin/bash
# Description: Verify the usage of the configuration setting `SentinelCheckOfflineServerInterval`.

# Test: Search for the usage of the configuration setting. Expect: At least one occurrence.
rg --type go 'SentinelCheckOfflineServerInterval'

Length of output: 224

Comment on lines +202 to +232
if n, ok := utils.ArgumentInteger(d, "--tls"); ok && n == 1 {

// Load server certificate and key
certFile, keyFile := utils.ArgumentMust(d, "--tls-cert"), utils.ArgumentMust(d, "--tls-key")
if certFile == "" || keyFile == "" {
log.Panic("TLS certificate or key file path must be provided")
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.PanicErrorf(err, "failed to load key pair: %s", err)
}

// Create a TLS config
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}

// Create a TLS listener
l, err = tls.Listen("tcp", listen, tlsConfig)
if err != nil {
log.PanicErrorf(err, "listen %s failed", listen)
}


}else{

l, err = net.Listen("tcp", listen)
if err != nil {
log.PanicErrorf(err, "listen %s failed", listen)
}

Copy link

Choose a reason for hiding this comment

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

Improve error handling and logging for TLS setup.

Ensure that all potential errors are logged appropriately and provide more context.

	if n, ok := utils.ArgumentInteger(d, "--tls"); ok && n == 1 {
		// Load server certificate and key
		certFile, keyFile := utils.ArgumentMust(d, "--tls-cert"), utils.ArgumentMust(d, "--tls-key")
		if certFile == "" || keyFile == "" {
			log.Panic("TLS certificate or key file path must be provided")
		}
		cert, err := tls.LoadX509KeyPair(certFile, keyFile)
		if err != nil {
			log.PanicErrorf(err, "failed to load key pair: %s", err)
		}

		// Create a TLS config
		tlsConfig := &tls.Config{
			Certificates: []tls.Certificate{cert},
		}

		// Create a TLS listener
		l, err = tls.Listen("tcp", listen, tlsConfig)
		if err != nil {
			log.PanicErrorf(err, "TLS listen on %s failed: %v", listen, err)
		}
		log.Warnf("TLS enabled, listening on %s", listen)
	} else {
		l, err = net.Listen("tcp", listen)
		if err != nil {
			log.PanicErrorf(err, "listen on %s failed: %v", listen, err)
		}
		log.Warnf("Listening on %s without TLS", listen)
	}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
if n, ok := utils.ArgumentInteger(d, "--tls"); ok && n == 1 {
// Load server certificate and key
certFile, keyFile := utils.ArgumentMust(d, "--tls-cert"), utils.ArgumentMust(d, "--tls-key")
if certFile == "" || keyFile == "" {
log.Panic("TLS certificate or key file path must be provided")
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.PanicErrorf(err, "failed to load key pair: %s", err)
}
// Create a TLS config
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
// Create a TLS listener
l, err = tls.Listen("tcp", listen, tlsConfig)
if err != nil {
log.PanicErrorf(err, "listen %s failed", listen)
}
}else{
l, err = net.Listen("tcp", listen)
if err != nil {
log.PanicErrorf(err, "listen %s failed", listen)
}
if n, ok := utils.ArgumentInteger(d, "--tls"); ok && n == 1 {
// Load server certificate and key
certFile, keyFile := utils.ArgumentMust(d, "--tls-cert"), utils.ArgumentMust(d, "--tls-key")
if certFile == "" || keyFile == "" {
log.Panic("TLS certificate or key file path must be provided")
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
log.PanicErrorf(err, "failed to load key pair: %s", err)
}
// Create a TLS config
tlsConfig := &tls.Config{
Certificates: []tls.Certificate{cert},
}
// Create a TLS listener
l, err = tls.Listen("tcp", listen, tlsConfig)
if err != nil {
log.PanicErrorf(err, "TLS listen on %s failed: %v", listen, err)
}
log.Warnf("TLS enabled, listening on %s", listen)
} else {
l, err = net.Listen("tcp", listen)
if err != nil {
log.PanicErrorf(err, "listen on %s failed: %v", listen, err)
}
log.Warnf("Listening on %s without TLS", listen)
}

Comment on lines +171 to +172
err := s.store.ReleaseByToken(s.model.Token);
if err != nil {
Copy link

Choose a reason for hiding this comment

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

Improve error handling in Close method.

Ensure that the error is logged and handled appropriately.

	if s.online {
		err := s.store.ReleaseByToken(s.model.Token)
		if err != nil {
			log.ErrorErrorf(err, "store: release lock of %s failed", s.config.ProductName)
			return errors.Errorf("store: release lock of %s failed", s.config.ProductName)
		}
	}
Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
err := s.store.ReleaseByToken(s.model.Token);
if err != nil {
if s.online {
err := s.store.ReleaseByToken(s.model.Token)
if err != nil {
log.ErrorErrorf(err, "store: release lock of %s failed", s.config.ProductName)
return errors.Errorf("store: release lock of %s failed", s.config.ProductName)
}
}

Copy link

@coderabbitai coderabbitai bot left a comment

Choose a reason for hiding this comment

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

Actionable comments posted: 0

Review details

Configuration used: CodeRabbit UI
Review profile: CHILL

Commits

Files that changed from the base of the PR and between e8f24eb and 1a4e5c4.

Files selected for processing (2)
  • codis/pkg/models/store.go (1 hunks)
  • codis/pkg/proxy/proxy.go (2 hunks)
Files skipped from review as they are similar to previous changes (2)
  • codis/pkg/models/store.go
  • codis/pkg/proxy/proxy.go

@kolinfluence
Copy link
Author

@machinly @chejinge ok?

@luky116 luky116 removed the 3.5.5 label Aug 7, 2024
@baerwang baerwang requested a review from machinly August 18, 2024 12:43
@sprappcom
Copy link

can someone pull this? have more assurance to have tls connection

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
4.0.1 ✏️ Feature New feature or request 🧹 Updates This will not be worked on
Projects
None yet
Development

Successfully merging this pull request may close these issues.

7 participants