probe/auth/info/info.go

122 lines
2.2 KiB
Go
Raw Normal View History

2018-04-12 11:54:56 +00:00
package info
import (
"bytes"
"encoding/base64"
"encoding/json"
"errors"
"net"
"git.loafle.net/commons/util-go/net/gateway"
2018-06-01 09:10:33 +00:00
ocmn "git.loafle.net/overflow/commons-go/model/noauthprobe"
2018-04-12 11:54:56 +00:00
"github.com/shirou/gopsutil/host"
)
func GetRegistHeader(apiKey string) (string, error) {
var err error
2018-06-01 09:10:33 +00:00
nap := ocmn.NoAuthProbe{
2018-04-12 11:54:56 +00:00
APIKey: apiKey,
}
2018-06-01 09:10:33 +00:00
var napd *ocmn.NoAuthProbeDescription
2018-04-12 11:54:56 +00:00
if napd, err = getDescription(); nil != err {
return "", err
}
var buf []byte
if buf, err = json.Marshal(napd); nil != err {
return "", err
}
nap.Description = string(buf)
if buf, err = json.Marshal(nap); nil != err {
return "", err
}
enc := base64.StdEncoding.EncodeToString(buf)
return enc, nil
}
2018-06-01 09:10:33 +00:00
func getDescription() (*ocmn.NoAuthProbeDescription, error) {
2018-04-12 11:54:56 +00:00
var err error
2018-06-01 09:10:33 +00:00
napd := &ocmn.NoAuthProbeDescription{}
2018-04-12 11:54:56 +00:00
if napd.Host, err = getHost(); nil != err {
return nil, err
}
if napd.Network, err = getNetwork(); nil != err {
return nil, err
}
return napd, nil
}
2018-06-01 09:10:33 +00:00
func getHost() (*ocmn.NoAuthProbeDescriptionHost, error) {
2018-04-12 11:54:56 +00:00
if i, err := host.Info(); nil == err {
2018-06-01 09:10:33 +00:00
h := &ocmn.NoAuthProbeDescriptionHost{}
2018-04-12 11:54:56 +00:00
h.Name = i.Hostname
h.OS = i.OS
h.Platform = i.Platform
h.PlatformFamily = i.PlatformFamily
h.KernelVersion = i.KernelVersion
h.HostID = i.HostID
return h, nil
} else {
return nil, err
}
}
2018-06-01 09:10:33 +00:00
func getNetwork() (*ocmn.NoAuthProbeDescriptionNetwork, error) {
2018-04-12 11:54:56 +00:00
var ip net.IP
var iface string
var err error
if ip, iface, err = gateway.DiscoverGateway(); nil != err {
return nil, err
}
interfaces, err := net.Interfaces()
if err != nil {
return nil, err
}
idx := -1
for _idx, i := range interfaces {
if i.Name == iface {
idx = _idx
break
}
}
if -1 == idx {
return nil, errors.New("Interface of gateway is not exist")
}
2018-06-01 09:10:33 +00:00
n := &ocmn.NoAuthProbeDescriptionNetwork{}
2018-04-12 11:54:56 +00:00
i := interfaces[idx]
n.Name = i.Name
n.MacAddress = i.HardwareAddr.String()
n.Gateway = ip.String()
if addrs, err := i.Addrs(); nil == err {
var buffer bytes.Buffer
for _idx, a := range addrs {
if 0 < _idx {
buffer.WriteString("|")
}
buffer.WriteString(a.String())
}
n.Address = buffer.String()
} else {
return nil, err
}
return n, nil
}