Skip to content

Commit

Permalink
Update Cassandra/client.go (#143)
Browse files Browse the repository at this point in the history
Signed-off-by: Sabbir <[email protected]>
  • Loading branch information
sabbir-hossain70 authored Nov 8, 2024
1 parent 8f47085 commit e821040
Show file tree
Hide file tree
Showing 22 changed files with 484 additions and 96 deletions.
71 changes: 32 additions & 39 deletions cassandra/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,10 @@ package cassandra

import (
"fmt"
"log"

"k8s.io/klog/v2"
health "kmodules.xyz/client-go/tools/healthchecker"
"time"

"github.com/gocql/gocql"
"k8s.io/klog/v2"
)

type Client struct {
Expand All @@ -16,78 +14,73 @@ type Client struct {

// CreateKeyspace creates a keyspace
func (c *Client) CreateKeyspace() error {
return c.Query(`CREATE KEYSPACE IF NOT EXISTS mykeyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '2'}`).Exec()
return c.Query(`CREATE KEYSPACE IF NOT EXISTS kubedb_keyspace WITH replication = {'class': 'SimpleStrategy', 'replication_factor': '2'}`).Exec()
}

// CreateTable creates a table
func (c *Client) CreateTable() error {
return c.Query(`CREATE TABLE IF NOT EXISTS mykeyspace.users (
id UUID PRIMARY KEY,
name TEXT,
age INT,
email TEXT
return c.Query(`CREATE TABLE IF NOT EXISTS kubedb_keyspace.healthcheck_table (
name TEXT PRIMARY KEY,
product TEXT
)`).Exec()
}

// InsertUser inserts a user into the table
func (c *Client) InsertUser(id gocql.UUID, name string, age int, email string) error {
return c.Query(`INSERT INTO mykeyspace.users (id, name, age, email) VALUES (?, ?, ?, ?)`,
id, name, age, email).Exec()
}
// UpdateData updates a record in the table
func (c *Client) UpdateData(name string, product string) error {
currentTime := time.Now().Format("2006-01-02 15:04:05")
updatedProduct := fmt.Sprintf("%s - %s", product, currentTime)

func (c *Client) DeleteUser(id gocql.UUID) error {
return c.Query(`DELETE FROM mykeyspace.users WHERE id = ?`, id).Exec()
return c.Query(`UPDATE kubedb_keyspace.healthcheck_table SET product = ? where name = ? `,
updatedProduct, name).Exec()
}

// QueryUser queries a user by ID
func (c *Client) QueryUser(id gocql.UUID) (string, int, string, error) {
var name string
var age int
var email string
// queries a Data by ID
func (c *Client) QueryData(name string) error {
var product string

iter := c.Query(`SELECT name, age, email FROM mykeyspace.users WHERE id = ?`, id).Iter()
if iter.Scan(&name, &age, &email) {
iter := c.Query(`SELECT product FROM kubedb_keyspace.healthcheck_table WHERE name = ?`, name).Iter()
if iter.Scan(&product) {
if err := iter.Close(); err != nil {
return "", 0, "", fmt.Errorf("unable to query data: %v", err)
return fmt.Errorf("unable to query data: %v", err)
}
return name, age, email, nil
return nil
}
return "", 0, "", fmt.Errorf("no data found")
return fmt.Errorf("no data found")
}

func (c *Client) CheckDbReadWrite() error {
if err := c.CreateKeyspace(); err != nil {
log.Fatal("Unable to create keyspace:", err)
klog.Error("Unable to create keyspace:", err)
return err
}
if err := c.CreateTable(); err != nil {
log.Fatal("Unable to create table:", err)
klog.Error("Unable to create table:", err)
return err
}
id := gocql.TimeUUID()
if err := c.InsertUser(id, "John Doe", 30, "[email protected]"); err != nil {
log.Fatal("Unable to insert data:", err)
if err := c.UpdateData("Appscode", "KubeDB"); err != nil {
klog.Error("Unable to update data:", err)
return err
}

name, age, email, err := c.QueryUser(id)
err := c.QueryData("Appscode")
if err != nil {
klog.Error("Unable to query data:", err)
return err
}
klog.Infoln("DB Read Write Successful")
fmt.Printf("Name: %s, Age: %d, Email: %s\n", name, age, email)
err = c.DeleteUser(id)
return err
return nil
}

func (c *Client) PingCassandra() error {
query := c.Query("SELECT now() FROM system.local")
if err := query.Exec(); err != nil {
klog.Error("Unable to ping cassandra:", err)
return err
}
return nil
}

func (c *Client) CloseCassandraClient(hcf *health.HealthCard) {
func (c *Client) CloseCassandraClient() {
if c != nil {
c.Close()
}
hcf.ClientClosed()
}
10 changes: 3 additions & 7 deletions cassandra/kubedb_client_builder.go
Original file line number Diff line number Diff line change
Expand Up @@ -45,8 +45,8 @@ func (o *KubeDBClientBuilder) WithContext(ctx context.Context) *KubeDBClientBuil
o.ctx = ctx
return o
}
func (o *KubeDBClientBuilder) GetCassandraClient(dns string) (*Client, error) {
host := dns
func (o *KubeDBClientBuilder) GetCassandraClient() (*Client, error) {
host := o.url
cluster := gocql.NewCluster(host)
cluster.Port = kubedb.CassandraNativeTcpPort
cluster.Keyspace = "system"
Expand All @@ -56,15 +56,11 @@ func (o *KubeDBClientBuilder) GetCassandraClient(dns string) (*Client, error) {
cluster.Consistency = gocql.Quorum
}
if !o.db.Spec.DisableSecurity {
if o.db.Spec.AuthSecret == nil {
klog.Error("AuthSecret not set")
return nil, errors.New("auth-secret is not set")
}

authSecret := &core.Secret{}
err := o.kc.Get(o.ctx, types.NamespacedName{
Namespace: o.db.Namespace,
Name: o.db.Spec.AuthSecret.Name,
Name: o.db.GetAuthSecretName(),
}, authSecret)
if err != nil {
if kerr.IsNotFound(err) {
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ require (
k8s.io/klog/v2 v2.130.1
kmodules.xyz/client-go v0.30.28
kmodules.xyz/custom-resources v0.30.0
kubedb.dev/apimachinery v0.48.1-0.20241031104503-a7bc124e382b
kubedb.dev/apimachinery v0.48.1-0.20241101074809-3a305bf59ab1
sigs.k8s.io/controller-runtime v0.18.4
xorm.io/xorm v1.3.6
)
Expand Down
4 changes: 2 additions & 2 deletions go.sum
Original file line number Diff line number Diff line change
Expand Up @@ -804,8 +804,8 @@ kmodules.xyz/monitoring-agent-api v0.30.2 h1:sAgz5P5EXZqhlj1NzJ+QltAgeIx5bGSMj+a
kmodules.xyz/monitoring-agent-api v0.30.2/go.mod h1:BoZFPDDRB7J39CcUsSDlzgW8PQCwik4ILPleyUob+Mg=
kmodules.xyz/offshoot-api v0.30.1 h1:TrulAYO+oBsXe9sZZGTmNWIuI8qD2izMpgcTSPvgAmI=
kmodules.xyz/offshoot-api v0.30.1/go.mod h1:T3mpjR6fui0QzOcmQvIuANytW48fe9ytmy/1cgx6D4g=
kubedb.dev/apimachinery v0.48.1-0.20241031104503-a7bc124e382b h1:4XiqS+WHcF21LkS0Fcsvn3F5y+PhX8oMKBAD3dh4zzg=
kubedb.dev/apimachinery v0.48.1-0.20241031104503-a7bc124e382b/go.mod h1:NCiS4uS+F8DUyU9/tUQO3wqyNRNf0busab5/0Q2nYA0=
kubedb.dev/apimachinery v0.48.1-0.20241101074809-3a305bf59ab1 h1:wSfneVFQ57FYIpV+XHA3xsfi8cCr4fWUSKetlI9AlIM=
kubedb.dev/apimachinery v0.48.1-0.20241101074809-3a305bf59ab1/go.mod h1:NCiS4uS+F8DUyU9/tUQO3wqyNRNf0busab5/0Q2nYA0=
kubeops.dev/petset v0.0.7 h1:F77BTRfUqRVO7kNc8q2oFSSviDmYBqni/osXqu0kgJ4=
kubeops.dev/petset v0.0.7/go.mod h1:lt0SZV4ohRy7RiwLNUnMoauG4lCbcRbSqhMg20rdUQg=
lukechampine.com/uint128 v1.1.1/go.mod h1:c4eWIwlEGaxC/+H1VguhU4PHXNWDCDMUlWdIWl2j1gk=
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,9 @@ type CassandraVersionSpec struct {
// Database Image
DB CassandraVersionDatabase `json:"db"`

// Exporter Image
Exporter CassandraVersionExporter `json:"exporter"`

// Database Image
InitContainer CassandraInitContainer `json:"initContainer"`

Expand All @@ -71,6 +74,11 @@ type CassandraVersionSpec struct {
UI []ChartInfo `json:"ui,omitempty"`
}

// CassandraVersionExporter is the image for the Cassandra exporter
type CassandraVersionExporter struct {
Image string `json:"image"`
}

// CassandraVersionDatabase is the Cassandra Database image
type CassandraVersionDatabase struct {
Image string `json:"image"`
Expand Down

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 4 additions & 1 deletion vendor/kubedb.dev/apimachinery/apis/kubedb/constants.go
Original file line number Diff line number Diff line change
Expand Up @@ -400,6 +400,7 @@ const (
MSSQLDatabasePort = 1433
MSSQLDatabaseMirroringEndpointPort = 5022
MSSQLCoordinatorPort = 2381
MSSQLMonitoringDefaultServicePort = 9399

// environment variables
EnvAcceptEula = "ACCEPT_EULA"
Expand Down Expand Up @@ -1478,15 +1479,17 @@ const (
CassandraInterNodePort = 7000
CassandraInterNodeSslPort = 7001
CassandraJmxPort = 7199
CassandraExporterPort = 8080

CassandraNativeTcpPortName = "cql"
CassandraInterNodePortName = "internode"
CassandraInterNodeSslPortName = "internode-ssl"
CassandraJmxPortName = "jmx"
CassandraExporterPortName = "exporter"

CassandraUserAdmin = "admin"

CassandraAuthCommand = "/usr/local/bin/docker-entrypoint.sh cassandra -f & /tmp/sc/cassandra-auth.sh"
CassandraAuthCommand = "/tmp/sc/cassandra-auth.sh"
CassandraMetadataName = "metadata.name"
CassandraMetadataNamespace = "metadata.namespace"
CassandraStatusPodIP = "status.podIP"
Expand Down
Loading

0 comments on commit e821040

Please sign in to comment.