This repository has been archived by the owner on May 24, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
cluster.go
99 lines (83 loc) · 2.28 KB
/
cluster.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
package gocqlastra
import (
"archive/zip"
"crypto/tls"
"crypto/x509"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"github.com/gocql/gocql"
)
type clusterConfig struct {
config *gocql.ClusterConfig
secureConnectBundle string
}
// NewCluster generates a new config for the default cluster implementation
// and implemented required configuration for connecting to Astra Cassandra.
func NewCluster(secureConnectBundle string) (*gocql.ClusterConfig, error) {
cluster := &clusterConfig{
config: gocql.NewCluster(),
secureConnectBundle: secureConnectBundle,
}
if err := parseZipFile(cluster); err != nil {
return nil, err
}
return cluster.config, nil
}
func (c *clusterConfig) setSSLOptions(entries map[string][]byte) error {
rootCAs := x509.NewCertPool()
rootCAs.AppendCertsFromPEM(entries["ca.crt"])
cert, err := tls.X509KeyPair(entries["cert"], entries["key"])
if err != nil {
return fmt.Errorf("cannot parse a public/private key pair from a pair of PEM encoded data: %v", err)
}
tlsConfig := &tls.Config{
ServerName: "*.db.astra.datastax.com",
RootCAs: rootCAs,
Certificates: []tls.Certificate{cert},
}
c.config.SslOpts = &gocql.SslOptions{
Config: tlsConfig,
EnableHostVerification: true,
}
return nil
}
type bundleConfig struct {
Host *string `json:"host"`
CQLPort *int64 `json:"cql_port"`
}
func parseZipFile(cluster *clusterConfig) error {
r, err := zip.OpenReader(cluster.secureConnectBundle)
if err != nil {
return err
}
defer func() {
_ = r.Close()
}()
zipEntries := make(map[string][]byte)
for _, f := range r.File {
rc, err := f.Open()
if err != nil {
continue
}
buf, err := ioutil.ReadAll(rc)
if err != nil {
continue
}
_ = rc.Close()
zipEntries[f.Name] = buf
}
if _, ok := zipEntries["config.json"]; !ok {
return errors.New("config file must be contained in secure bundle")
}
var bundleCfg *bundleConfig
if err := json.Unmarshal(zipEntries["config.json"], &bundleCfg); err != nil {
return err
}
if bundleCfg.Host == nil || bundleCfg.CQLPort == nil {
return errors.New("config file must include host and cql_port information")
}
cluster.config.Hosts = []string{fmt.Sprintf("%s:%d", *bundleCfg.Host, *bundleCfg.CQLPort)}
return cluster.setSSLOptions(zipEntries)
}