Files
certmanager/pkg/client/control.go
Олег Бородин 42cd5f4800 working changes
2024-07-30 23:14:54 +02:00

96 lines
2.2 KiB
Go

package client
import (
"context"
"crypto/tls"
"fmt"
"time"
cmapi "certmanager/api/certmanagercontrol"
"google.golang.org/grpc"
"google.golang.org/grpc/credentials"
)
const (
DefaultWrpcPort int = 20311
DefaultGrpcPort int = 20312
)
type Access struct {
Hostname string
Port int
Username string
Password string
}
type Control struct {
conn *grpc.ClientConn
client cmapi.ControlClient
}
func NewControl(access *Access) (*Control, error) {
var err error
cont := &Control{}
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
const dialTimeout time.Duration = 1 * time.Second
const idleTimeout time.Duration = 5 * time.Second
authCred := NewAuthCredential(access.Username, access.Password)
dialOpts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithPerRPCCredentials(authCred),
grpc.WithBlock(),
grpc.WithIdleTimeout(idleTimeout),
}
address := fmt.Sprintf("%s:%d", access.Hostname, access.Port)
ctx, _ := context.WithTimeout(context.Background(), dialTimeout)
conn, err := grpc.DialContext(ctx, address, dialOpts...)
if err != nil {
return cont, fmt.Errorf("Dial error: %v", err)
}
cont.conn = conn
cont.client = cmapi.NewControlClient(conn)
if cont.client == nil {
return cont, fmt.Errorf("Nil control client")
}
return cont, err
}
func (cont *Control) Close() {
if cont.client != nil {
cont.conn.Close()
}
}
func NewClient(access *Access) (cmapi.ControlClient, error) {
var err error
var cli cmapi.ControlClient
tlsConfig := &tls.Config{
InsecureSkipVerify: true,
}
const dialTimeout time.Duration = 1 * time.Second
const idleTimeout time.Duration = 5 * time.Second
authCred := NewAuthCredential(access.Username, access.Password)
dialOpts := []grpc.DialOption{
grpc.WithTransportCredentials(credentials.NewTLS(tlsConfig)),
grpc.WithPerRPCCredentials(authCred),
grpc.WithBlock(),
grpc.WithIdleTimeout(idleTimeout),
}
address := fmt.Sprintf("%s:%d", access.Hostname, access.Port)
ctx, _ := context.WithTimeout(context.Background(), dialTimeout)
conn, err := grpc.DialContext(ctx, address, dialOpts...)
if err != nil {
return cli, fmt.Errorf("Dial error: %v", err)
}
cli = cmapi.NewControlClient(conn)
return cli, err
}