Reorganized adding cobra commands

This commit is contained in:
David J. Allen 2023-08-29 14:36:57 -06:00
parent 25a885b18c
commit c202469c50
9 changed files with 435 additions and 208 deletions

View file

@ -2,12 +2,10 @@ package magellan
import (
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"fmt"
"net"
"net/http"
"os"
"sync"
"time"
@ -16,6 +14,8 @@ import (
"github.com/go-logr/logr"
"github.com/jacobweinstock/registrar"
"github.com/jmoiron/sqlx"
_ "github.com/mattn/go-sqlite3"
_ "github.com/stmcginnis/gofish"
)
const (
@ -26,22 +26,23 @@ const (
)
type bmcProbeResult struct {
Host string
Port int
Protocol string
State bool
Host string `json:"host"`
Port int `json:"port"`
Protocol string `json:"protocol"`
State bool `json:"state"`
}
// NOTE: ...params were getting too long...
type QueryParams struct {
Host string
Port int
User string
Pass string
Drivers []string
Timeout int
Host string
Port int
User string
Pass string
Drivers []string
Timeout int
WithSecureTLS bool
CertPoolFile string
CertPoolFile string
Verbose bool
}
func rawConnect(host string, ports []int, timeout int, keepOpenOnly bool) []bmcProbeResult {
@ -88,7 +89,7 @@ func GenerateHosts(subnet string, begin uint8, end uint8) []string {
}
func ScanForAssets(hosts []string, ports []int, threads int, timeout int) []bmcProbeResult {
states := []bmcProbeResult{}
states := make([]bmcProbeResult, 0, len(hosts))
done := make(chan struct{}, threads+1)
chanHost := make(chan string, threads+1)
// chanPort := make(chan int, threads+1)
@ -133,12 +134,12 @@ func StoreStates(path string, states *[]bmcProbeResult) error {
// create database if it doesn't already exist
schema := `
CREATE IF NOT EXISTS TABLE scanned_ports (
host text,
port integer,
protocol text,
state integer
)
CREATE TABLE IF NOT EXISTS magellan_scanned_ports (
host TEXT PRIMARY KEY NOT NULL,
port INTEGER,
protocol TEXT,
state INTEGER
);
`
db, err := sqlx.Open("sqlite3", path)
if err != nil {
@ -149,8 +150,12 @@ func StoreStates(path string, states *[]bmcProbeResult) error {
// insert all probe states into db
tx := db.MustBegin()
for _, state := range *states {
tx.NamedExec(`INSERT INTO scanned_ports (host, port, protocol, state)
VALUES (:Host, :Port, :Protocol, :State)`, &state)
sql := `INSERT OR REPLACE INTO magellan_scanned_ports (host, port, protocol, state)
VALUES (:host, :port, :protocol, :state);`
_, err := tx.NamedExec(sql, &state)
if err != nil {
fmt.Printf("could not execute transaction: %v\n", err)
}
}
err = tx.Commit()
if err != nil {
@ -166,7 +171,7 @@ func GetStates(path string) ([]bmcProbeResult, error) {
}
results := []bmcProbeResult{}
err = db.Select(&results, "SELECT * FROM scanned_ports ORDER BY host ASC")
err = db.Select(&results, "SELECT * FROM magellan_scanned_ports ORDER BY host ASC")
if err != nil {
return nil, fmt.Errorf("could not retrieve probes: %v", err)
}
@ -177,17 +182,77 @@ func GetDefaultPorts() []int {
return []int{SSH_PORT, TLS_PORT, IPMI_PORT, REDFISH_PORT}
}
func QueryInventory(l *logr.Logger, q *QueryParams) ([]byte, error) {
// discover.ScanAndConnect(url, user, pass, clientOpts)
client, err := makeClient(l, q)
if err != nil {
return nil, fmt.Errorf("could not make query: %v", err)
func NewClient(l *logr.Logger, q *QueryParams) (*bmclib.Client, error) {
// NOTE: bmclib.NewClient(host, port, user, pass)
// ...seems like the `port` params doesn't work like expected depending on interface
// tr := &http.Transport{
// TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
// }
// httpClient := http.Client{
// Transport: tr,
// }
// init client
clientOpts := []bmclib.Option{
// bmclib.WithSecureTLS(),
// bmclib.WithHTTPClient(&httpClient),
bmclib.WithLogger(*l),
// bmclib.WithRedfishHTTPClient(&httpClient),
bmclib.WithRedfishPort(fmt.Sprint(q.Port)),
bmclib.WithRedfishUseBasicAuth(true),
bmclib.WithIpmitoolPort(fmt.Sprint(q.Port)),
}
// only work if valid cert is provided
if q.WithSecureTLS {
var pool *x509.CertPool
if q.CertPoolFile != "" {
pool = x509.NewCertPool()
data, err := os.ReadFile(q.CertPoolFile)
if err != nil {
return nil, fmt.Errorf("could not read cert pool file: %v", err)
}
pool.AppendCertsFromPEM(data)
}
// a nil pool uses the system certs
clientOpts = append(clientOpts, bmclib.WithSecureTLS(pool))
}
// url := fmt.Sprintf("https://%s:%s@%s", q.User, q.Pass, q.Host)
url := ""
if q.WithSecureTLS {
url = "https://"
} else {
url = "http://"
}
if q.User != "" && q.Pass != "" {
url += fmt.Sprintf("%s:%s@%s", q.User, q.Pass, q.Host)
} else {
url += fmt.Sprintf("%s", q.Host)
}
client := bmclib.NewClient(url, q.User, q.Pass, clientOpts...)
ds := registrar.Drivers{}
for _, driver := range q.Drivers {
ds = append(ds, client.Registry.Using(driver)...) // ipmi, gofish, redfish
}
client.Registry.Drivers = ds
return client, nil
}
func QueryMetadata(client *bmclib.Client, l *logr.Logger, q *QueryParams) ([]byte, error) {
// client, err := NewClient(l, q)
// if err != nil {
// return nil, fmt.Errorf("could not make query: %v", err)
// }
// open BMC session and update driver registry
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second*time.Duration(q.Timeout))
client.Registry.FilterForCompatible(ctx)
err = client.Open(ctx)
err := client.Open(ctx)
if err != nil {
ctxCancel()
return nil, fmt.Errorf("could not open BMC client: %v", err)
@ -195,6 +260,44 @@ func QueryInventory(l *logr.Logger, q *QueryParams) ([]byte, error) {
defer client.Close(ctx)
metadata := client.GetMetadata()
if err != nil {
ctxCancel()
return nil, fmt.Errorf("could not get metadata: %v", err)
}
// retrieve inventory data
b, err := json.MarshalIndent(metadata, "", " ")
if err != nil {
ctxCancel()
return nil, fmt.Errorf("could not marshal JSON: %v", err)
}
if q.Verbose {
fmt.Printf("metadata: %v\n", string(b))
}
ctxCancel()
return []byte(b), nil
}
func QueryInventory(client *bmclib.Client, l *logr.Logger, q *QueryParams) ([]byte, error) {
// discover.ScanAndConnect(url, user, pass, clientOpts)
// client, err := NewClient(l, q)
// if err != nil {
// return nil, fmt.Errorf("could not make query: %v", err)
// }
// open BMC session and update driver registry
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second*time.Duration(q.Timeout))
// client.Registry.FilterForCompatible(ctx)
err := client.Open(ctx)
if err != nil {
ctxCancel()
return nil, fmt.Errorf("could not open client: %v", err)
}
defer client.Close(ctx)
inventory, err := client.Inventory(ctx)
if err != nil {
ctxCancel()
@ -208,22 +311,37 @@ func QueryInventory(l *logr.Logger, q *QueryParams) ([]byte, error) {
return nil, fmt.Errorf("could not marshal JSON: %v", err)
}
fmt.Printf("inventory: %v\n", string(b))
if q.Verbose {
fmt.Printf("inventory: %v\n", string(b))
}
ctxCancel()
return []byte(b), nil
}
func QueryUsers(l *logr.Logger, q *QueryParams) ([]byte, error) {
// func QueryInventoryV2(host string, port int, user string, pass string) ([]byte, error) {
// url := fmt.Sprintf("http://%s:%s@%s:%s/redfish/v1/", user, pass, host, fmt.Sprint(port))
// res, body, err := api.MakeRequest(url, "GET", nil)
// if err != nil {
// return nil , fmt.Errorf("could not get endpoint: %v", err)
// }
// fmt.Println(res)
// fmt.Println(string(body))
// return body, err
// }
func QueryUsers(client *bmclib.Client, l *logr.Logger, q *QueryParams) ([]byte, error) {
// discover.ScanAndConnect(url, user, pass, clientOpts)
client, err := makeClient(l, q)
if err != nil {
return nil, fmt.Errorf("could not make query: %v", err)
}
// client, err := NewClient(l, q)
// if err != nil {
// return nil, fmt.Errorf("could not make query: %v", err)
// }
// open BMC session and update driver registry
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second*time.Duration(q.Timeout))
client.Registry.FilterForCompatible(ctx)
err = client.Open(ctx)
err := client.Open(ctx)
if err != nil {
ctxCancel()
return nil, fmt.Errorf("could not open BMC client: %v", err)
@ -246,75 +364,31 @@ func QueryUsers(l *logr.Logger, q *QueryParams) ([]byte, error) {
// return b, nil
ctxCancel()
fmt.Printf("users: %v\n", string(b))
if q.Verbose {
fmt.Printf("users: %v\n", string(b))
}
return []byte(b), nil
}
// func QueryBios(l *logr.Logger, q *QueryParams) ([]byte, error){
// client, err := makeClient(l, q)
// if err != nil {
// return nil, fmt.Errorf("could not make query: %v", err)
// }
// return makeRequest(client, client.GetBiosConfiguration, q.Timeout)
// }
func makeClient(l *logr.Logger, q *QueryParams) (*bmclib.Client, error) {
// NOTE: bmclib.NewClient(host, port, user, pass)
// ...seems like the `port` params doesn't work like expected depending on interface
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
func QueryBios(client *bmclib.Client, l *logr.Logger, q *QueryParams) ([]byte, error) {
// client, err := NewClient(l, q)
// if err != nil {
// return nil, fmt.Errorf("could not make query: %v", err)
// }
b, err := makeRequest(client, client.GetBiosConfiguration, q.Timeout)
if q.Verbose {
fmt.Printf("bios: %v\n", string(b))
}
httpClient := http.Client{
Transport: tr,
}
// init client
clientOpts := []bmclib.Option{
// bmclib.WithSecureTLS(),
bmclib.WithHTTPClient(&httpClient),
bmclib.WithLogger(*l),
// bmclib.WithRedfishHTTPClient(&httpClient),
bmclib.WithRedfishPort(fmt.Sprint(q.Port)),
// bmclib.WithRedfishUseBasicAuth(true),
// bmclib.WithDellRedfishUseBasicAuth(true),
bmclib.WithIpmitoolPort(fmt.Sprint(q.Port)),
}
// only work if valid cert is provided
if q.WithSecureTLS {
var pool *x509.CertPool
if q.CertPoolFile != "" {
pool = x509.NewCertPool()
data, err := os.ReadFile(q.CertPoolFile)
if err != nil {
return nil, fmt.Errorf("could not read cert pool file: %v", err)
}
pool.AppendCertsFromPEM(data)
}
// a nil pool uses the system certs
clientOpts = append(clientOpts, bmclib.WithSecureTLS(pool))
}
// url := fmt.Sprintf("https://%s:%s@%s", q.User, q.Pass, q.Host)
url := fmt.Sprintf("https://%s:%s@%s", q.User, q.Pass, q.Host)
fmt.Println("url: ", url)
client := bmclib.NewClient(url, q.User, q.Pass, clientOpts...)
ds := registrar.Drivers{}
for _, driver := range q.Drivers {
ds = append(ds, client.Registry.Using(driver)...) // ipmi, gofish, redfish
}
client.Registry.Drivers = ds
return client, nil
return b, err
}
func makeRequest[T interface{}](client *bmclib.Client, fn func(context.Context) (T, error), timeout int) ([]byte, error){
func makeRequest[T interface{}](client *bmclib.Client, fn func(context.Context) (T, error), timeout int) ([]byte, error) {
ctx, ctxCancel := context.WithTimeout(context.Background(), time.Second*time.Duration(timeout))
client.Registry.FilterForCompatible(ctx)
err := client.Open(ctx)
if err != nil {
ctxCancel()
return nil, fmt.Errorf("could not open BMC client: %v", err)
return nil, fmt.Errorf("could not open client: %v", err)
}
defer client.Close(ctx)
@ -335,4 +409,4 @@ func makeJson(object interface{}) ([]byte, error) {
return nil, fmt.Errorf("could not marshal JSON: %v", err)
}
return []byte(b), nil
}
}