cwtch/app/bots/servermon/main.go

83 lines
2.1 KiB
Go

package main
import (
"cwtch.im/cwtch/event"
"cwtch.im/cwtch/peer"
"cwtch.im/cwtch/protocol/connections"
"errors"
"fmt"
"git.openprivacy.ca/openprivacy/libricochet-go/connectivity"
"os"
"time"
)
func waitForPeerGroupConnection(peer peer.CwtchPeer, groupID string) error {
for {
_, ok := peer.GetProfile().Groups[groupID]
if ok {
state := peer.GetGroupState(groupID)
if state == connections.FAILED {
return errors.New("Connection to group " + groupID + " failed!")
}
if state != connections.AUTHENTICATED {
fmt.Printf("peer %v waiting to authenticate with group %v 's server, current state: %v\n", peer.GetProfile().Onion, groupID, connections.ConnectionStateName[state])
time.Sleep(time.Second * 10)
continue
}
} else {
return errors.New("peer server connections should have entry for server but do not")
}
break
}
return nil
}
func main() {
if len(os.Args) != 2 {
fmt.Printf("Usage: ./servermon SERVER_ADDRESS\n")
os.Exit(1)
}
serverAddr := os.Args[1]
acn, err := connectivity.StartTor(".", "")
if err != nil {
fmt.Printf("Could not start tor: %v\n", err)
os.Exit(1)
}
botPeer := peer.NewCwtchPeer("servermon")
botPeer.Init(acn, event.NewEventManager())
fmt.Printf("Connecting to %v...\n", serverAddr)
botPeer.JoinServer(serverAddr)
groupID, _, err := botPeer.StartGroup(serverAddr)
if err != nil {
fmt.Printf("Error creating group on server %v: %v\n", serverAddr, err)
os.Exit(1)
}
err = waitForPeerGroupConnection(botPeer, groupID)
if err != nil {
fmt.Printf("Could not connect to server %v: %v\n", serverAddr, err)
os.Exit(1)
}
timeout := 1 * time.Second
timeElapsed := 0 * time.Second
for {
err := botPeer.SendMessageToGroup(groupID, timeout.String())
if err != nil {
fmt.Printf("Sent to group on server %v failed at interval %v of total %v with: %v\n", serverAddr, timeout, timeElapsed, err)
os.Exit(1)
} else {
fmt.Printf("Successfully sent message to %v at interval %v of total %v\n", serverAddr, timeout, timeElapsed)
}
time.Sleep(timeout)
timeElapsed += timeout
if timeout < 2*time.Minute {
timeout = timeout * 2
}
}
}