Skip to content

Commit 6a70c6f

Browse files
committed
Version 2
1 parent 4a66dbe commit 6a70c6f

13 files changed

+661
-22
lines changed

.gitignore

+11
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,14 @@ src/*
77
!src/.cobra.yml
88
!src/serverauth.go
99
serverauth
10+
dist/*
11+
*.exe
12+
*.exe~
13+
*.dll
14+
*.so
15+
*.dylib
16+
*.test
17+
*.out
18+
vendor/
19+
*.tar.gz
20+
build.sh

.gitmodules

+45
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
[submodule "github.com/fsnotify/fsnotify"]
2+
path = github.com/fsnotify/fsnotify
3+
url = https://github.com/fsnotify/fsnotify
4+
[submodule "github.com/hashicorp/hcl"]
5+
path = github.com/hashicorp/hcl
6+
url = https://github.com/hashicorp/hcl
7+
[submodule "github.com/magiconair/properties"]
8+
path = github.com/magiconair/properties
9+
url = https://github.com/magiconair/properties
10+
[submodule "github.com/mitchellh/mapstructure"]
11+
path = github.com/mitchellh/mapstructure
12+
url = https://github.com/mitchellh/mapstructure
13+
[submodule "github.com/pelletier/go-toml"]
14+
path = github.com/pelletier/go-toml
15+
url = https://github.com/pelletier/go-toml
16+
[submodule "github.com/spf13/afero"]
17+
path = github.com/spf13/afero
18+
url = https://github.com/spf13/afero
19+
[submodule "github.com/spf13/cast"]
20+
path = github.com/spf13/cast
21+
url = https://github.com/spf13/cast
22+
[submodule "github.com/spf13/cobra"]
23+
path = github.com/spf13/cobra
24+
url = https://github.com/spf13/cobra
25+
[submodule "github.com/spf13/jwalterweatherman"]
26+
path = github.com/spf13/jwalterweatherman
27+
url = https://github.com/spf13/jwalterweatherman
28+
[submodule "github.com/spf13/viper"]
29+
path = github.com/spf13/viper
30+
url = https://github.com/spf13/viper
31+
[submodule "github.com/subosito/gotenv"]
32+
path = github.com/subosito/gotenv
33+
url = https://github.com/subosito/gotenv
34+
[submodule "golang.org/x/sys"]
35+
path = golang.org/x/sys
36+
url = https://golang.org/x/sys
37+
[submodule "golang.org/x/text"]
38+
path = golang.org/x/text
39+
url = https://golang.org/x/text
40+
[submodule "gopkg.in/yaml.v2"]
41+
path = gopkg.in/yaml.v2
42+
url = https://gopkg.in/yaml.v2
43+
[submodule "github.com/spf13/pflag"]
44+
path = github.com/spf13/pflag
45+
url = https://github.com/spf13/pflag

.goreleaser.yml

+65
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,65 @@
1+
builds:
2+
# List of builds
3+
- # First Build
4+
env:
5+
- CGO_ENABLED=0
6+
main: main.go
7+
# Set the binary output location to bin/ so archive will comply with Sensu Go Asset structure
8+
binary: bin/{{ .ProjectName }}
9+
goos:
10+
- freebsd
11+
- linux
12+
- darwin
13+
goarch:
14+
- amd64
15+
- 386
16+
- arm
17+
goarm:
18+
- 5
19+
- 6
20+
- 7
21+
ignore:
22+
# TODO: add freebsd/arm support to gopsutil
23+
- goos: freebsd
24+
goarch: arm
25+
targets:
26+
- linux_386
27+
- linux_amd64
28+
- linux_arm_5
29+
- linux_arm_6
30+
- linux_arm_7
31+
- linux_arm64
32+
# - freebsd_amd64
33+
# - freebsd_386
34+
- darwin_amd64
35+
checksum:
36+
name_template: "{{ .ProjectName }}_{{ .Version }}_sha512-checksums.txt"
37+
algorithm: sha512
38+
39+
archives:
40+
- id: tar
41+
format: tar.gz
42+
files:
43+
- LICENSE
44+
- README.md
45+
- CHANGELOG.md
46+
nfpms:
47+
-
48+
id: serverauth
49+
package_name: serverauth
50+
file_name_template: "{{ .ProjectName }}_{{ .Version }}_{{ .Os }}_{{ .Arch }}"
51+
builds:
52+
- serverauth-agent-dev
53+
vendor: ServerAuth.com
54+
homepage: https://serverauth.com
55+
maintainer: ServerAuth <[email protected]>
56+
description: ServerAuth management agent.
57+
formats:
58+
- deb
59+
- rpm
60+
dependencies:
61+
- git
62+
epoch: 1
63+
release: 2
64+
empty_folders:
65+
- /etc/serverauth

CHANGELOG.md

+8
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
# Changelog
2+
3+
## [2.0.0] - 2020-07-20
4+
### Added
5+
- New release system using Go Releaser
6+
- Support for Server Monitoring Added
7+
- Reworked the codebase to move to using Go Modules
8+

src/cmd/add.go renamed to cmd/add.go

+7
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,13 @@ var addCmd = &cobra.Command{
6262
panic("There was a problem setting up the user account. Please try again or contact ServerAuth for assistance")
6363
}
6464

65+
for _, data := range accounts {
66+
if data.Username == username {
67+
color.Green("The user %s is already configured - no changes needed.", data.Username)
68+
os.Exit(1)
69+
}
70+
}
71+
6572
// Append the new account and update the config
6673
accounts = append(accounts, Account{username, apikey})
6774
viper.Set("accounts", accounts)

cmd/monitor.go

+177
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,177 @@
1+
/*
2+
Copyright © 2019 ServerAuth.com <[email protected]>
3+
4+
Permission is hereby granted, free of charge, to any person obtaining a copy
5+
of this software and associated documentation files (the "Software"), to deal
6+
in the Software without restriction, including without limitation the rights
7+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
8+
copies of the Software, and to permit persons to whom the Software is
9+
furnished to do so, subject to the following conditions:
10+
11+
The above copyright notice and this permission notice shall be included in
12+
all copies or substantial portions of the Software.
13+
14+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
15+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
16+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
17+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
18+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
19+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
20+
THE SOFTWARE.
21+
*/
22+
package cmd
23+
24+
import (
25+
"fmt"
26+
"log"
27+
"net/http"
28+
"net/url"
29+
"os"
30+
"runtime"
31+
"strconv"
32+
"strings"
33+
"time"
34+
35+
"github.com/fatih/color"
36+
"github.com/shirou/gopsutil/cpu"
37+
"github.com/shirou/gopsutil/disk"
38+
"github.com/shirou/gopsutil/host"
39+
"github.com/shirou/gopsutil/load"
40+
41+
"github.com/shirou/gopsutil/mem"
42+
"github.com/spf13/cobra"
43+
"github.com/spf13/viper"
44+
)
45+
46+
var actionCmd = &cobra.Command{
47+
Use: "monitor",
48+
Short: "Collect server metrics",
49+
Long: `Collects the latest server monitoring metrics and sends them to your ServerAuth account.`,
50+
Run: func(cmd *cobra.Command, args []string) {
51+
// Read in the existing accounts and get ready for adding another user
52+
viper.ReadInConfig()
53+
54+
var accounts []Account
55+
configErr := viper.UnmarshalKey("accounts", &accounts)
56+
57+
if configErr != nil {
58+
color.Red("There was a problem setting up the user account.\nPlease try again or contact ServerAuth for assistance.")
59+
os.Exit(1)
60+
}
61+
62+
// Get the organisation id
63+
var orgId string
64+
viper.UnmarshalKey("orgid", &orgId)
65+
66+
if len(orgId) <= 0 {
67+
color.Red("The organisation id is missing from your ServerAuth configuration.\nPlease check you've correctly configured ServerAuth on this server and try again.")
68+
os.Exit(1)
69+
}
70+
71+
// Get the server api key
72+
var serverAPIKey string
73+
viper.UnmarshalKey("apikey", &serverAPIKey)
74+
75+
if len(serverAPIKey) <= 0 {
76+
color.Red("The server API key is missing.\nPlease check you've correctly configured ServerAuth on this server and try again.")
77+
os.Exit(1)
78+
}
79+
80+
// Get the team api key
81+
var teamAPIKey string
82+
viper.UnmarshalKey("teamkey", &teamAPIKey)
83+
84+
if len(teamAPIKey) <= 0 {
85+
color.Red("The team API key is missing.\nPlease check you've correctly configured ServerAuth on this server and try again.")
86+
os.Exit(1)
87+
}
88+
89+
// Get the base domain, which can optionally be overridden
90+
var baseDomain string
91+
viper.UnmarshalKey("basedomain", &baseDomain)
92+
93+
if len(baseDomain) <= 0 {
94+
// No overridden base domain, fall back to the default
95+
baseDomain = "https://api.serverauth.com/"
96+
}
97+
98+
// Build the base url
99+
baseURL := baseDomain + "monitoring"
100+
101+
// Get current system stats
102+
memory, _ := mem.VirtualMemory()
103+
loadAvg, _ := load.Avg()
104+
cpuHw, _ := cpu.Info()
105+
//percent, _ := cpu.Percent(time.Second, true)
106+
uptime, _ := host.Uptime()
107+
misc, _ := load.Misc()
108+
platform, family, version, _ := host.PlatformInformation()
109+
diskStat, err := disk.Usage("/")
110+
currentTime := time.Now()
111+
timeZone, timeOffset := currentTime.Zone()
112+
113+
// Create http client
114+
httpClient := http.Client{
115+
Timeout: time.Second * 10, // Maximum of 10 secs
116+
}
117+
118+
form := url.Values{}
119+
120+
// Mem
121+
form.Add("mem[total]", fmt.Sprint(memory.Total))
122+
form.Add("mem[free]", fmt.Sprint(memory.Free))
123+
form.Add("mem[used]", fmt.Sprint(memory.Used))
124+
form.Add("mem[used_percent]", fmt.Sprint(memory.UsedPercent))
125+
126+
// Loadavg
127+
form.Add("load[1]", fmt.Sprint(loadAvg.Load1))
128+
form.Add("load[5]", fmt.Sprint(loadAvg.Load5))
129+
form.Add("load[15]", fmt.Sprint(loadAvg.Load15))
130+
131+
// Processes
132+
form.Add("procs[running]", fmt.Sprint(misc.ProcsRunning))
133+
form.Add("procs[blocked]", fmt.Sprint(misc.ProcsBlocked))
134+
form.Add("procs[total]", fmt.Sprint(misc.ProcsTotal))
135+
136+
// Generic CPU HW
137+
form.Add("cpu", fmt.Sprint(cpuHw))
138+
139+
// Uptime
140+
form.Add("uptime_seconds", fmt.Sprint(uptime))
141+
142+
// Platform info
143+
form.Add("platform[name]", fmt.Sprint(platform))
144+
form.Add("platform[family]", fmt.Sprint(family))
145+
form.Add("platform[version]", fmt.Sprint(version))
146+
147+
// Disk info
148+
form.Add("disk[total]", strconv.FormatUint(diskStat.Total, 10))
149+
form.Add("disk[used]", strconv.FormatUint(diskStat.Used, 10))
150+
form.Add("disk[free]", strconv.FormatUint(diskStat.Free, 10))
151+
form.Add("disk[percent_free]", strconv.FormatFloat(diskStat.UsedPercent, 'f', 2, 64))
152+
form.Add("disk[inodes_total]", strconv.FormatUint(diskStat.InodesTotal, 10))
153+
form.Add("disk[inodes_used]", strconv.FormatUint(diskStat.InodesUsed, 10))
154+
form.Add("disk[inodes_free]", strconv.FormatUint(diskStat.InodesFree, 10))
155+
156+
// Time info
157+
form.Add("time[zone]", fmt.Sprint(timeZone))
158+
form.Add("time[offset]", fmt.Sprint(timeOffset))
159+
form.Add("time[now]", fmt.Sprint(currentTime.Unix()))
160+
161+
// Create a request
162+
req, err := http.NewRequest(http.MethodPost, baseURL, strings.NewReader(form.Encode()))
163+
if err != nil {
164+
log.Fatal(err)
165+
}
166+
167+
req.Header.Set("User-Agent", "ServerAuthAgent-v2.0.0;"+runtime.GOOS)
168+
req.Header.Set("TeamApiKey", teamAPIKey)
169+
req.Header.Set("ServerApiKey", serverAPIKey)
170+
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
171+
httpClient.Do(req)
172+
},
173+
}
174+
175+
func init() {
176+
rootCmd.AddCommand(actionCmd)
177+
}
File renamed without changes.

src/cmd/root.go renamed to cmd/root.go

+4-14
Original file line numberDiff line numberDiff line change
@@ -25,7 +25,6 @@ import (
2525
"fmt"
2626
"os"
2727

28-
"github.com/fatih/color"
2928
"github.com/spf13/cobra"
3029

3130
"github.com/spf13/viper"
@@ -47,9 +46,6 @@ var rootCmd = &cobra.Command{
4746
Use: "serverauth",
4847
Short: "ServerAuth Server Agent",
4948
Long: `The ServerAuth Server Agent is an easy to use command line application, allowing your server to automatically sync your teams SSH keys.`,
50-
// Uncomment the following line if your bare application
51-
// has an action associated with it:
52-
// Run: func(cmd *cobra.Command, args []string) { },
5349
}
5450

5551
// Execute adds all child commands to the root command and sets flags appropriately.
@@ -63,12 +59,6 @@ func Execute() {
6359

6460
func init() {
6561
cobra.OnInitialize(initConfig)
66-
67-
// Here you will define your flags and configuration settings.
68-
// Cobra supports persistent flags, which, if defined here,
69-
// will be global for your application.
70-
71-
//rootCmd.PersistentFlags().StringVar(&cfgFile, "config", "", "config file (default is $HOME/.serverauth.yaml)")
7262
}
7363

7464
// initConfig reads in config file and ENV variables if set.
@@ -80,8 +70,8 @@ func initConfig() {
8070
viper.AutomaticEnv() // read in environment variables that match
8171

8272
// If a config file is found, read it in.
83-
if err := viper.ReadInConfig(); err != nil {
84-
color.Red("Your server is not configured to use ServerAuth!")
85-
fmt.Println("Please follow the instructions on your server details page inside your ServerAuth account, or contact us for assistance.", viper.ConfigFileUsed())
86-
}
73+
// if err := viper.ReadInConfig(); err != nil {
74+
// color.Red("Your server is not configured to use ServerAuth!")
75+
// fmt.Println("Please follow the instructions on your server details page inside your ServerAuth account, or contact us for assistance.", viper.ConfigFileUsed())
76+
// }
8777
}

src/cmd/sync.go renamed to cmd/sync.go

+2-2
Original file line numberDiff line numberDiff line change
@@ -78,7 +78,7 @@ var syncCmd = &cobra.Command{
7878

7979
if len(baseDomain) <= 0 {
8080
// No overridden base domain, fall back to the default
81-
baseDomain = "https://api.serverauth.com/v1/"
81+
baseDomain = "https://api.serverauth.com/"
8282
}
8383

8484
// Build the base url
@@ -109,7 +109,7 @@ var syncCmd = &cobra.Command{
109109
}
110110

111111
// Set our custom useragent
112-
req.Header.Set("User-Agent", "ServerAuthAgent-v1.0.0;"+runtime.GOOS)
112+
req.Header.Set("User-Agent", "ServerAuthAgent-v2.0.0;"+runtime.GOOS)
113113

114114
// Run the request
115115
res, getErr := httpClient.Do(req)

0 commit comments

Comments
 (0)