Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Show status of machine #13

Open
wants to merge 5 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ RUN apk update && apk upgrade && \
apk add --no-cache git && \
go get -d github.com/gorilla/handlers && \
go get -d github.com/gorilla/mux && \
go get -d github.com/gocarina/gocsv
go get -d github.com/gocarina/gocsv && \
go get -d github.com/tatsushid/go-fastping

# Build Source Files
RUN go build -o main .
Expand Down
8 changes: 4 additions & 4 deletions computer.csv
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
name,mac,ip
Computer1,64-07-2D-BB-BB-BF,192.168.10.254:9
Computer2,2D-F2-3D-06-17-00,192.168.10.254:9
Computer3,FF-B3-95-62-1C-DD,192.168.10.254:9
name,mac,ip,broadcast
Computer1,64-07-2D-BB-BB-BF,192.168.10.4,192.168.10.254:9
Computer2,2D-F2-3D-06-17-00,192.168.10.5,192.168.10.254:9
Computer3,FF-B3-95-62-1C-DD,192.168.10.6,192.168.10.254:9
Binary file added go-rest-wol
Binary file not shown.
11 changes: 11 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
module github.com/alfonsocatanzaro/go-rest-wol

go 1.14

require (
github.com/gocarina/gocsv v0.0.0-20200330101823-46266ca37bd3
github.com/gorilla/handlers v1.4.2
github.com/gorilla/mux v1.7.4
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e
golang.org/x/net v0.0.0-20200513185701-a91f0712d120 // indirect
)
15 changes: 15 additions & 0 deletions go.sum
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
github.com/gocarina/gocsv v0.0.0-20200330101823-46266ca37bd3 h1:B7k6N+JlLM/u1xrIkpifUfE7GRJsZIYHoHbiAa5cSP4=
github.com/gocarina/gocsv v0.0.0-20200330101823-46266ca37bd3/go.mod h1:5YoVOkjYAQumqlV356Hj3xeYh4BdZuLE0/nRkf2NKkI=
github.com/gorilla/handlers v1.4.2 h1:0QniY0USkHQ1RGCLfKxeNHK9bkDHGRYGNDFBCS+YARg=
github.com/gorilla/handlers v1.4.2/go.mod h1:Qkdc/uu4tH4g6mTK6auzZ766c4CA0Ng8+o/OAirnOIQ=
github.com/gorilla/mux v1.7.4 h1:VuZ8uybHlWmqV03+zRzdwKL4tUnIp1MAQtp1mIFE1bc=
github.com/gorilla/mux v1.7.4/go.mod h1:DVbg23sWSpFRCP0SfiEN6jmj59UnW/n46BH5rLB71So=
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e h1:nt2877sKfojlHCTOBXbpWjBkuWKritFaGIfgQwbQUls=
github.com/tatsushid/go-fastping v0.0.0-20160109021039-d7bb493dee3e/go.mod h1:B4+Kq1u5FlULTjFSM707Q6e/cOHFv0z/6QRoxubDIQ8=
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
golang.org/x/net v0.0.0-20200513185701-a91f0712d120 h1:EZ3cVSzKOlJxAd8e8YAJ7no8nNypTxexh/YE/xW3ZEY=
golang.org/x/net v0.0.0-20200513185701-a91f0712d120/go.mod h1:qpuaurCH72eLCgpAm/N6yyVIVM9cpaDIP3A8BGJEC5A=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd h1:xhmwyvizuTgC2qz7ZlMluP20uW+C3Rm0FD/WLDX8884=
golang.org/x/sys v0.0.0-20200323222414-85ca7c5b95cd/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
6 changes: 6 additions & 0 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ var ComputerList []Computer

func main() {



httpPort := DefaultHTTPPort
computerFilePath := DefaultComputerFilePath

Expand All @@ -39,6 +41,10 @@ func main() {
router.HandleFunc("/api/wakeup/computer/{computerName}", restWakeUpWithComputerName).Methods("GET")
router.HandleFunc("/api/wakeup/computer/{computerName}/", restWakeUpWithComputerName).Methods("GET")

// Define Wakeup Api functions with a Computer Name
router.HandleFunc("/api/ping/computer/{computerName}", pingWithComputerName).Methods("GET")
router.HandleFunc("/api/ping/computer/{computerName}/", pingWithComputerName).Methods("GET")

// Setup Webserver
httpListen := fmt.Sprint(":", httpPort)
log.Printf("Startup Webserver on \"%s\"", httpListen)
Expand Down
75 changes: 64 additions & 11 deletions pages/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta/css/bootstrap.min.css" integrity="sha384-/Y6pD6FV/Vv2HJnA6t+vslU6fwYXjCFtcEpHbNJ0lyAFsXTsjBbfaDjzALeQsN6M" crossorigin="anonymous">
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
<style>
.hideMe {
Expand Down Expand Up @@ -32,17 +32,30 @@ <h1><span class="fa fa-qq"></span> GO-REST-WOL <small>Your little Monster to Wak
</thead>
<tbody>
{{range .}}
<tr>
<td class="align-middle"><b><button id="bn_{{.Name}}" name="wolbutton" value="{{.Name}}" class="btn btn-success btn-sm" onclick="$.wakeUpComputerByName('{{.Name}}')">WakeUp</button></b></td>
<td class="align-middle">{{.Name}}</td>
<tr id="computer_{{.Name}}">
<td class="align-middle"><b><button
id="bn_{{.Name}}"
name="wolbutton"
value="{{.Name}}"
class="btn btn-success btn-sm"
onclick="$.wakeUpComputerByName('{{.Name}}')">WakeUp</button>
<button
id="online_{{.Name}}"
name="onlineIndicator"
class="btn btn-success btn-sm disabled"
style="display: none;"
>OnLine</button>
</b>
</td>
<td class="align-middle computername">{{.Name}}</td>
<td class="align-middle">{{.Mac}}</td>
<td class="align-middle">{{.BroadcastIPAddress}}</td>
<td class="align-middle">{{.IPAddress}}</td>
<td class="align-middle">/api/wakeup/computer/{{.Name}}</td>
</tr>
{{end}}
</tbody>
</table>
<hr>
<hr>
<p>
<h3>REST API Usage</h3>
<b>/api/wakeup/computer/<span class="text-info">&lt;ComputerName&gt;</span></b>
Expand Down Expand Up @@ -84,6 +97,51 @@ <h3>REST API Usage</h3>

<script>
$(document).ready(function() {

pingComputers()
setInterval(pingComputers, 5000);

function pingComputers() {
const computerArray = $(".computername").toArray().map(a=> a.innerText);
computerArray.forEach(computer => {
pingComputer(computer);
});
}

function pingComputer(computer){
$.ajax({
type: "GET",
url: "/api/ping/computer/" + computer,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data) {
setComputerStatus(computer,data.isonline)
},
error: function(data,err)
{
$.showSnackBar(data);
console.error(data);
}
});
}

function setComputerStatus(computer,isOnLine)
{
const offLineClass="";
const onLineClass="table-success";
const classToAdd = isOnLine ? onLineClass: offLineClass;
const classToRemove = !isOnLine? onLineClass: offLineClass;
if (isOnLine) {
$(`#bn_${computer}`).hide();
$(`#online_${computer}`).show();
} else {
$(`#bn_${computer}`).show();
$(`#online_${computer}`).hide();
}
$(`#computer_${computer}`)
.removeClass(classToRemove)
.addClass(classToAdd);
}

jQuery.showSnackBar = function(data){

Expand Down Expand Up @@ -119,12 +177,7 @@ <h3>REST API Usage</h3>
}
})
};


});



</script>
</body>
</html>
31 changes: 31 additions & 0 deletions ping.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
package main

import (
"net"
"time"

"github.com/tatsushid/go-fastping"
)

// Ping make a ping to an address and retun true of false
func Ping(ipAddress string) (bool, error) {
ret := false

p := fastping.NewPinger()
ra, err := net.ResolveIPAddr("ip4:icmp", ipAddress)
if err != nil {
return false, err
}
p.AddIPAddr(ra)
p.OnRecv = func(addr *net.IPAddr, rtt time.Duration) {
ret = true
}
// p.OnIdle = func() {
// fmt.Println("finish")
// }
err = p.Run()
if err != nil {
return false, err
}
return ret, nil
}
37 changes: 35 additions & 2 deletions rest.go
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
// Rest API Implementations

package main

import (
Expand Down Expand Up @@ -43,7 +42,7 @@ func restWakeUpWithComputerName(w http.ResponseWriter, r *http.Request) {
} else {
// Horray we send the WOL Packet succesfully
result.Success = true
result.Message = fmt.Sprintf("Succesfully Wakeup Computer %s with Mac %s on Broadcast IP %s", c.Name, c.Mac, c.BroadcastIPAddress)
result.Message = fmt.Sprintf("Succesfully Wakeup Computer %s with Mac %s on Broadcast IP %s", c.Name, c.Mac, c.IPAddress)
result.ErrorObject = nil
}
}
Expand All @@ -57,3 +56,37 @@ func restWakeUpWithComputerName(w http.ResponseWriter, r *http.Request) {
}
json.NewEncoder(w).Encode(result)
}

func pingWithComputerName(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")

vars := mux.Vars(r)
computerName := vars["computerName"]
var result PingResponseObject
result.IsOnLine=false

var computer Computer
for _,c := range ComputerList{
if c.Name == computerName{
computer= c
break
}
}

if computer.Name == "" {
result.Message = fmt.Sprintf("Computername %s could not be found", computerName)
}else {
result.IsOnLine, result.ErrorObject = Ping(computer.IPAddress)
if result.ErrorObject != nil{
w.WriteHeader(http.StatusNotFound)
result.Message ="Internal error on Pinging the computer"
} else {
if result.IsOnLine{
result.Message = fmt.Sprintf("Computer %s is online!", computerName)
} else{
result.Message = fmt.Sprintf("Computer %s is offline!", computerName)
}
}
}
json.NewEncoder(w).Encode(result)
}
10 changes: 9 additions & 1 deletion types.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,9 +7,17 @@ type WakeUpResponseObject struct {
ErrorObject error `json:"error"`
}

//PingResponseObject Datastructure for holding information for the PingResult
type PingResponseObject struct {
IsOnLine bool `json:"isonline"`
Message string `json:"message"`
ErrorObject error `json:"error"`
}

// Computer represents a Computer Object
type Computer struct {
Name string `csv:"name"`
Mac string `csv:"mac"`
BroadcastIPAddress string `csv:"ip"`
IPAddress string `csv:"ip"`
BroadcastIPAddress string `csv:"broadcast"`
}
10 changes: 5 additions & 5 deletions wol.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ type MagicPacket struct {
payload [16]MACAddress
}

// This function accepts a MAC Address string, and returns a pointer to
// NewMagicPacket accepts a MAC Address string, and returns a pointer to
// a MagicPacket object. A Magic Packet is a broadcast frame which
// contains 6 bytes of 0xFF followed by 16 repetitions of a given mac address.
func NewMagicPacket(mac string) (*MagicPacket, error) {
Expand Down Expand Up @@ -64,8 +64,8 @@ func NewMagicPacket(mac string) (*MagicPacket, error) {
return &packet, nil
}

// This function gets the address associated with an interface
func GetIpFromInterface(iface string) (*net.UDPAddr, error) {
// GetIPFromInterface This function gets the address associated with an interface
func GetIPFromInterface(iface string) (*net.UDPAddr, error) {
ief, err := net.InterfaceByName(iface)
if err != nil {
return nil, err
Expand Down Expand Up @@ -93,7 +93,7 @@ func GetIpFromInterface(iface string) (*net.UDPAddr, error) {
return nil, errors.New("Unable to find valid IP addr for interface " + iface)
}

// Function to send a magic packet to a given mac address, and optionally
// SendMagicPacket Function to send a magic packet to a given mac address, and optionally
// receives an iface to broadcast on. An iface of "" implies a nil net.UDPAddr
func SendMagicPacket(macAddr, bcastAddr, iface string) error {
// Construct a MagicPacket for the given MAC Address
Expand All @@ -119,7 +119,7 @@ func SendMagicPacket(macAddr, bcastAddr, iface string) error {
var localAddr *net.UDPAddr
if iface != "" {
var err error
localAddr, err = GetIpFromInterface(iface)
localAddr, err = GetIPFromInterface(iface)
if err != nil {
log.Printf("ERROR: %s\n", err.Error())
return errors.New("Unable to get address for interface " + iface)
Expand Down