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

V2 rewrite #2

Draft
wants to merge 13 commits into
base: main
Choose a base branch
from
Draft
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
1 change: 0 additions & 1 deletion .dockerignore

This file was deleted.

8 changes: 0 additions & 8 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,12 +1,4 @@
# NPM
node_modules/
npm-debug.log*

# Build output
build/

# IDEs
*.iml
.idea/

# Misc
Expand Down
31 changes: 7 additions & 24 deletions Dockerfile
Original file line number Diff line number Diff line change
@@ -1,27 +1,10 @@
FROM node:14-alpine
FROM golang:1.19-alpine AS build

# Use tini to handle signal forwarding.
RUN apk add --no-cache tini
ENTRYPOINT ["/sbin/tini", "--"]
CMD ["node", "index.js"]
EXPOSE 5000
USER node
WORKDIR /usr/src/local-dicovery
COPY . .
RUN CGO_ENABLED=0 go build -o /app/local-discovery ./main.go

# Create the app and build dir first, otherwise WORKDIR will create them as root.
RUN mkdir /home/node/local-discovery
RUN mkdir /tmp/build
FROM scratch

# Build the app, move the build result to the app dir.
WORKDIR /tmp/build
COPY --chown=node *.json ./
COPY --chown=node src src
RUN npm i
RUN npm run build
RUN mv build/* /home/node/local-discovery
RUN rm -rf /tmp/build

# Install the production dependencies.
WORKDIR /home/node/local-discovery
ENV NODE_ENV production
COPY package*.json ./
RUN npm ci
COPY --from=build /app/local-discovery /app/local-discovery
CMD ["/app/local-discovery"]
20 changes: 16 additions & 4 deletions LICENSE.txt
Original file line number Diff line number Diff line change
@@ -1,9 +1,21 @@
The MIT License (MIT)

Copyright © 2020 Luca Scalzotto
Copyright © 2022 Luca Scalzotto

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
65 changes: 32 additions & 33 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,68 +4,67 @@
[![Docker Image Size](https://img.shields.io/docker/image-size/lucascorpion/local-discovery?sort=semver)](https://hub.docker.com/r/lucascorpion/local-discovery)
[![Docker Pulls](https://img.shields.io/docker/pulls/lucascorpion/local-discovery)](https://hub.docker.com/r/lucascorpion/local-discovery)

A simple API which can be used to discover agents in a local network.
A simple service with a JSON API which can be used to discover agents in a local network.

## Using the API
![Screenshot of the Local Discovery frontend](screenshot.png)

## How Does it Work?

All endpoints only expose agents in the same network as the request origin, based on the remote client IP address.
That way you can never see or manipulate other agents than your own.

## API

### Agent Schema

| Attribute | Description |
|------------|-------------|
| `name` | The name of the agent application. This will likely be the same for all agents.
| `version` | The version of the agent application.
| `address` | The local address (IP and port) at which the agent is running.
| `platform` | The platform the agent is running on, e.g. `windows`, `linux` or `mac`.
| `hostname` | The name of the host the agent is running on.
| Attribute | Description |
|----------------|-------------|
| `name` | The name of the agent application.
| `localAddress` | The local address at which the agent is running.
| `info` | A freeform object containing application-specific info about the agent.

### List the Agents

Send a `GET` request to `/api/agents`. This will return a JSON list of known agent information:
Send a `GET` request to `/api/agents`.
This returns a list of known agent information:

```json
[
{
"name": "agent",
"version": "1.0.0",
"address": "192.168.0.110:4000",
"platform": "windows",
"hostname": "my-pc"
"localAddress": "192.168.0.110:4000",
"info": {}
}
]
```

### Register an Agent

Send a `POST` request to `/api/agents`, with the agent information as JSON in the request body:
Send a `POST` request to `/api/agents`, with the agent information in the request body:

```json
{
"name": "agent",
"version": "1.0.0",
"address": "192.168.0.110:4000",
"platform": "windows",
"hostname": "my-pc"
"localAddress": "192.168.0.110:4000",
"info": {}
}
```

This will return the list of known agents in the local network (see "List the Agents" above).

If the agent address is the same as the address of a known agent, the known agent will be replaced with the new one.
This returns the newly created agent.

### Remove an agent
**Note:** if the agent `name` and `localAddress` are the same as a known agent, the known agent will be replaced with the new one.

Send a `DELETE` request to `/api/agents/:address`, where `:address` is the local address of the agent. If no agent with that address is registered, nothing happens.
### Remove an Agent

This will return the list of known agents in the local network (see "List the Agents" above).
Send a `DELETE` request to `/api/agents`, with the agent information in the request body:

## Configuration

The discovery server can be configured through environment variables.
```json
{
"name": "agent",
"localAddress": "192.168.0.110:4000"
}
```

| Variable | Default | Description |
|-------------------|---------|-------------|
| `LOG_LEVEL` | `INFO` | The log level (`DEBUG`, `INFO`, `WARN`, `ERROR` or `OFF`).
| `PORT` | 5000 | The port the server listens on.
| `KEEP_AGENT_TIME` | 600 | The time (in seconds) to keep agents in the registry.
This deletes the agent whose `name` and `localAddress` match this info.
If no such agent is found, nothing happens.
This returns an empty response.
3 changes: 3 additions & 0 deletions go.mod
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
module local-discovery

go 1.19
14 changes: 14 additions & 0 deletions internal/discovery/agent.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
package discovery

import "time"

type Agent struct {
Name string `json:"name"`
LocalAddress string `json:"localAddress"`
Info map[string]any `json:"info"`
registered time.Time
}

func IsSameAgent(a Agent, b Agent) bool {
return a.Name == b.Name && a.LocalAddress == b.LocalAddress
}
68 changes: 68 additions & 0 deletions internal/discovery/registry.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package discovery

import (
"errors"
"sync"
"time"
)

type Registry struct {
agents map[string][]*Agent
agentsLock sync.Mutex
}

func NewRegistry() *Registry {
return &Registry{
agents: map[string][]*Agent{},
}
}

func (reg *Registry) GetAgents(publicIp string) []*Agent {
reg.agentsLock.Lock()
defer reg.agentsLock.Unlock()

return reg.agents[publicIp]
}

func (reg *Registry) RegisterAgent(publicIp string, agent Agent) (*Agent, error) {
// Validate the agent info.
if len(agent.Name) == 0 {
return nil, errors.New("name should not be empty")
}
if len(agent.LocalAddress) == 0 {
return nil, errors.New("local address should not be empty")
}

if agent.Info == nil {
agent.Info = map[string]any{}
}

reg.agentsLock.Lock()
defer reg.agentsLock.Unlock()

// Remove agents where the name and local address are the same as the new agent.
reg.doRemoveAgent(publicIp, agent)

agent.registered = time.Now()
reg.agents[publicIp] = append(reg.agents[publicIp], &agent)
return &agent, nil
}

func (reg *Registry) RemoveAgent(publicIp string, agent Agent) {
reg.agentsLock.Lock()
defer reg.agentsLock.Unlock()

reg.doRemoveAgent(publicIp, agent)
}

func (reg *Registry) doRemoveAgent(publicIp string, agent Agent) {
// Here we already have a lock.

newAgents := make([]*Agent, 0)
for _, check := range reg.agents[publicIp] {
if !IsSameAgent(agent, *check) {
newAgents = append(newAgents, check)
}
}
reg.agents[publicIp] = newAgents
}
53 changes: 53 additions & 0 deletions internal/server/agents.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
package server

import (
"encoding/json"
"fmt"
"local-discovery/internal/discovery"
"net/http"
)

func agents(reg *discovery.Registry) handlerWithErrorFunc {
return func(writer http.ResponseWriter, request *http.Request) error {
writer.Header().Set("Content-Type", "application/json")

switch request.Method {
case http.MethodGet:
return getAgents(reg, writer, request)
case http.MethodPost:
return postAgent(reg, writer, request)
default:
return newHttpError(http.StatusMethodNotAllowed, "")
}
}
}

func getAgents(reg *discovery.Registry, writer http.ResponseWriter, request *http.Request) error {
list := reg.GetAgents(getRemoteIp(request))

// Make sure the list is always a list, not nil.
if list == nil {
list = []*discovery.Agent{}
}

json.NewEncoder(writer).Encode(list)
return nil
}

func postAgent(reg *discovery.Registry, writer http.ResponseWriter, request *http.Request) error {
agentDto := &discovery.Agent{}
enc := json.NewEncoder(writer)

if err := json.NewDecoder(request.Body).Decode(agentDto); err != nil {
return newHttpError(http.StatusBadRequest, fmt.Sprintf("Invalid JSON: %v", err))
}

agent, err := reg.RegisterAgent(getRemoteIp(request), *agentDto)
if err != nil {
return newHttpError(http.StatusBadRequest, fmt.Sprintf("Invalid agent: %v", err))
}

writer.WriteHeader(http.StatusCreated)
enc.Encode(agent)
return nil
}
17 changes: 17 additions & 0 deletions internal/server/httpError.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package server

type httpError struct {
Status int `json:"status"`
Message string `json:"error"`
}

func newHttpError(status int, message string) httpError {
return httpError{
Status: status,
Message: message,
}
}

func (err httpError) Error() string {
return err.Message
}
28 changes: 28 additions & 0 deletions internal/server/remoteIp.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
package server

import (
"net/http"
"strings"
)

func getRemoteIp(request *http.Request) string {
remoteIp := request.RemoteAddr

// Check if the address is an IPv6 address with port, e.g.: "[::1]:4000"
if remoteIp[0] == '[' {
endIpIndex := strings.IndexRune(remoteIp, ']')
remoteIp = remoteIp[1:endIpIndex]
}

// Check if the address is an IPv4 address with port, e.g.: "127.0.0.1:4000"
if parts := strings.SplitN(remoteIp, ":", 3); len(parts) == 2 {
remoteIp = parts[0]
}

// Consolidate localhost addresses.
if remoteIp == "::1" {
remoteIp = "127.0.0.1"
}

return remoteIp
}
Loading