Skip to content
Merged
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
6 changes: 6 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,11 @@
# Changelog

## [0.0.18] - Agenda por cliques e partições
- **Agenda por cliques:** Todo dia, Dias da semana, Todo mês ou Várias vezes ao dia, com dias e intervalo escolhidos em botões e o horário digitado (hh:mm, 24 h). A expressão cron não aparece mais; agendas antigas que a tela não consegue representar são avisadas e trocadas só ao salvar.
- **Partições na escolha da pasta local:** o seletor mostra cada partição montada na máquina do agente (/, /boot, /mnt/...) com a barra de uso (o mesmo percentual do `df`), o espaço livre e o tipo; clicar abre a partição. O espaço mostrado junto da pasta diz de qual partição ele é. **Exige agente 0.0.18.**
- **Retenção mais clara:** "Manter as últimas N cópias no agente" ou "apagar depois de enviar"; no storage, "as últimas N cópias", "tudo dos últimos N dias" ou os dois juntos, com um resumo em frase.
- **Destinos agora se chamam Storages.**

## [0.0.17] - O Server conecta nos agentes
- **O Server conecta nos agentes:** o agente é cadastrado na interface com **nome, IP e porta** (assistente Novo agente), e a stack dele fica só com a porta publicada e o token. O Server disca cada agente, tenta de novo sozinho com espera crescente e mostra na tela por que não conectou (tempo esgotado, conexão recusada, autenticação recusada).
- **Segurança:** o agente só aceita a conexão de quem prova ser o seu Server (TLS 1.3 com o certificado fixado no token); o Server autentica o agente pelo token e depois pela credencial, como antes. A porta do agente deve ficar liberada só para o IP do Server.
Expand Down
6 changes: 3 additions & 3 deletions Dockerfile
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ RUN mkdir -p /src/internal/webui && npm run build
# Os estágios web e gobuild rodam na plataforma nativa do runner (sem emulação); só o binário é cruzado.
# --- binários Go -----------------------------------------------------------------------------------------------------
FROM --platform=$BUILDPLATFORM golang:1.26-alpine AS gobuild
ARG VERSION=0.0.17
ARG VERSION=0.0.18
ARG TARGETOS
ARG TARGETARCH
WORKDIR /src
Expand All @@ -32,7 +32,7 @@ RUN --mount=type=secret,id=google_client_secret --mount=type=secret,id=google_we

# --- Server ------------------------------------------------------------------------------------------------------------
FROM alpine:3.21 AS server
ARG VERSION=0.0.17
ARG VERSION=0.0.18
LABEL org.opencontainers.image.title="Coruja Backup Server" \
org.opencontainers.image.description="Backup centralizado: orquestração, agendamentos, nuvem e interface web" \
org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \
Expand All @@ -48,7 +48,7 @@ ENTRYPOINT ["/usr/local/bin/coruja-server"]

# --- Agente ------------------------------------------------------------------------------------------------------------
FROM alpine:3.21 AS agent
ARG VERSION=0.0.17
ARG VERSION=0.0.18
LABEL org.opencontainers.image.title="Coruja Backup Agent" \
org.opencontainers.image.description="Agente leve do Coruja Backup (conecta ao Server por IP:porta)" \
org.opencontainers.image.source="https://github.com/AprendendoLinux/corujabackup" \
Expand Down
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
Sistema de backup **centralizado**, em Docker, gerenciado por **interface web**. Um **Server** orquestra tudo; **Agentes** leves rodam
nos servidores de destino e se conectam a ele informando só **IP:porta + token**.

> **Versão 0.0.17** · [Changelog](CHANGELOG.md) · [Instalação](docs/INSTALACAO.md) · [Operação](docs/OPERACAO.md) · [Segurança](docs/SEGURANCA.md) · [FAQ](docs/FAQ.md)
> **Versão 0.0.18** · [Changelog](CHANGELOG.md) · [Instalação](docs/INSTALACAO.md) · [Operação](docs/OPERACAO.md) · [Segurança](docs/SEGURANCA.md) · [FAQ](docs/FAQ.md)

## O que faz

Expand Down Expand Up @@ -69,4 +69,4 @@ docker run --rm --network SUA_REDE -e CORUJA_TEST_DSN='usuario:senha@tcp(db:3306
```

---
Coruja Backup - Versão 0.0.17 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT
Coruja Backup - Versão 0.0.18 - Desenvolvido por [Henrique Fagundes](https://henrique.tec.br) · Licença MIT
2 changes: 1 addition & 1 deletion VERSION
Original file line number Diff line number Diff line change
@@ -1 +1 @@
0.0.17
0.0.18
2 changes: 1 addition & 1 deletion deploy/docker-compose.agent.yml
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
# O Server conecta no agente pela porta publicada abaixo: libere-a só para o IP do Server.
services:
agent:
image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.17
image: ghcr.io/aprendendolinux/corujabackup-agent:0.0.18
container_name: corujabackup-agent
restart: always
ports:
Expand Down
2 changes: 1 addition & 1 deletion deploy/docker-compose.server.yml
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@ services:
networks: [echelon]

server:
image: ghcr.io/aprendendolinux/corujabackup-server:0.0.17
image: ghcr.io/aprendendolinux/corujabackup-server:0.0.18
container_name: corujabackup-server
restart: always
depends_on:
Expand Down
2 changes: 1 addition & 1 deletion docker-compose.dev.example.yml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
# docker compose -f docker-compose.dev.yml up -d --build -> http://187.110.161.52:8081
services:
server:
build: { context: ., target: server, args: { VERSION: "0.0.17" } }
build: { context: ., target: server, args: { VERSION: "0.0.18" } }
container_name: corujabackup-dev-server
restart: unless-stopped
ports: ["8081:8080"] # interface web (o Server é quem conecta nos agentes)
Expand Down
1 change: 1 addition & 0 deletions docs/ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
- [x] **Clareza da interface (0.0.15):** a máquina do backup é sempre chamada de agente; pastas, arquivos, atalhos e padrões identificados nas listas.
- [x] **Interface nova (0.0.16):** menu lateral, ícones, modais próprios, assistentes de job e agente, execução ao vivo, temas só por pacote com modo claro e escuro, créditos configuráveis e foto do usuário.
- [x] **Conexão invertida (0.0.17):** o Server conecta nos agentes (cadastro com IP e porta; porta padrão 23847); a stack do agente só publica a porta e leva o token.
- [x] **Agenda por cliques e partições (0.0.18):** agenda sem cron, partições com uso na escolha da pasta local, retenção em opções e Storages.
- [ ] **Fase 9, parte 3:** vários destinos por job; compatíveis com S3; SharePoint.
- [ ] **Fase 10 – Full/Incremental e MikroTik (versão seguinte):** motor `tar.gz` em blocos com índice e catálogo; agenda full + incrementais; retenção por cadeia; jobs de MikroTik (SSH: `.rsc` e `.backup`).
- [ ] **Fase 11 – Restauração inteligente (versão posterior):** árvore de arquivos, linha do tempo de versões, restauração de arquivos selecionados e de bancos pela interface.
Expand Down
14 changes: 14 additions & 0 deletions internal/agentcore/browse.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,8 +47,22 @@ type BrowseResult struct {
// só na área "disk"
Free int64 `json:"free,omitempty"`
Total int64 `json:"total,omitempty"`
Used int64 `json:"used,omitempty"`
Exists bool `json:"exists,omitempty"`
Blocked string `json:"blocked,omitempty"` // por que esta pasta não pode ser escolhida
Disks []Disk `json:"disks,omitempty"` // partições montadas na máquina, com o uso de cada uma
Mount string `json:"mount,omitempty"` // partição (ponto de montagem) onde a pasta fica: é dela o espaço informado
FS string `json:"fs,omitempty"`
}

// Disk é uma partição (sistema de arquivos real) montada na máquina do agente.
type Disk struct {
Path string `json:"path"` // ponto de montagem, como o usuário o conhece (ex.: /, /boot, /mnt/hd2)
FS string `json:"fs"`
Total int64 `json:"total"`
Free int64 `json:"free"`
Used int64 `json:"used"`
RO bool `json:"read_only,omitempty"`
}

// pastas que o job pode usar como destino local (mesma regra que o Server aplica ao salvar o job)
Expand Down
111 changes: 106 additions & 5 deletions internal/agentcore/localdir.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,15 @@ package agentcore
// - um nome relativo (jobs antigos), dentro da pasta de backups do agente (/backups).

import (
"bufio"
"errors"
"fmt"
"io"
"io/fs"
"os"
"path"
"path/filepath"
"sort"
"strings"
"syscall"
)
Expand Down Expand Up @@ -107,13 +110,15 @@ func (c *Core) localDir(dir string) (string, error) {
}

// diskSpace devolve o espaço livre (para usuários) e total do sistema de arquivos de p, e se ele está somente leitura.
func diskSpace(p string) (free, total int64, readOnly bool, err error) {
// used é o ocupado de fato (sem o espaço reservado ao root), como o df: o percentual em uso é used/(used+free).
func diskSpace(p string) (free, total, used int64, readOnly bool, err error) {
var st syscall.Statfs_t
if err := syscall.Statfs(p, &st); err != nil {
return 0, 0, false, err
return 0, 0, 0, false, err
}
const stReadOnly = 0x1
return int64(st.Bavail) * int64(st.Bsize), int64(st.Blocks) * int64(st.Bsize), st.Flags&stReadOnly != 0, nil
bs := int64(st.Bsize)
return int64(st.Bavail) * bs, int64(st.Blocks) * bs, int64(st.Blocks-st.Bfree) * bs, st.Flags&stReadOnly != 0, nil
}

// BrowseDisk lista as pastas do servidor para a escolha da pasta do backup local, com o espaço disponível. Uma pasta que
Expand Down Expand Up @@ -142,11 +147,11 @@ func BrowseDisk(root, p string, allowed []string) (BrowseResult, error) {
}
existing, res.Exists = path.Dir(existing), false
}
free, total, readOnly, err := diskSpace(filepath.Join(root, existing))
free, total, used, readOnly, err := diskSpace(filepath.Join(root, existing))
if err != nil {
return res, fmt.Errorf("não foi possível medir o espaço em %s", existing)
}
res.Free, res.Total = free, total
res.Free, res.Total, res.Used = free, total, used
switch {
case logical == "/":
res.Blocked = "Entre numa pasta: o backup não é gravado direto na raiz."
Expand All @@ -155,6 +160,9 @@ func BrowseDisk(root, p string, allowed []string) (BrowseResult, error) {
case readOnly:
res.Blocked = "Este disco está montado somente leitura."
}
mounts := readMountInfo()
res.Disks = listDisks(root, mounts)
res.Mount, res.FS = mountOf(root, existing, mounts)
if !res.Exists {
return res, nil
}
Expand All @@ -165,3 +173,96 @@ func BrowseDisk(root, p string, allowed []string) (BrowseResult, error) {
res.Entries, res.Truncated = list.Entries, list.Truncated
return res, nil
}

// sistemas de arquivos que guardam dados de verdade (discos, partições e compartilhamentos de rede)
var realFS = map[string]bool{"ext2": true, "ext3": true, "ext4": true, "xfs": true, "btrfs": true, "zfs": true, "vfat": true, "exfat": true,
"ntfs": true, "ntfs3": true, "fuseblk": true, "f2fs": true, "reiserfs": true, "jfs": true, "bcachefs": true, "nfs": true, "nfs4": true,
"cifs": true, "smb3": true, "smbfs": true, "ceph": true, "glusterfs": true, "lustre": true}

type mountEntry struct {
Dev, Point, FS string
}

func readMountInfo() []mountEntry {
f, err := os.Open("/proc/self/mountinfo")
if err != nil {
return nil
}
defer f.Close()
return parseMountInfo(f)
}

// parseMountInfo lê o formato de /proc/self/mountinfo: dispositivo (3º campo), ponto de montagem (5º) e tipo (após " - ").
func parseMountInfo(r io.Reader) []mountEntry {
var out []mountEntry
sc := bufio.NewScanner(r)
sc.Buffer(make([]byte, 64<<10), 1<<20)
for sc.Scan() {
before, after, ok := strings.Cut(sc.Text(), " - ")
f, t := strings.Fields(before), strings.Fields(after)
if !ok || len(f) < 5 || len(t) < 1 {
continue
}
out = append(out, mountEntry{Dev: f[2], Point: unescapeMount(f[4]), FS: t[0]})
}
return out
}

// listDisks devolve as partições montadas dentro de root (a máquina, como o agente a enxerga), uma por dispositivo
// (o ponto de montagem mais curto), com o espaço de cada uma.
func listDisks(root string, mounts []mountEntry) []Disk {
root = strings.TrimSuffix(filepath.Clean(root), "/")
best := map[string]mountEntry{}
for _, m := range mounts {
if !realFS[m.FS] {
continue
}
if m.Point != root && !strings.HasPrefix(m.Point, root+"/") && root != "" {
continue
}
if cur, ok := best[m.Dev]; !ok || len(m.Point) < len(cur.Point) {
best[m.Dev] = m
}
}
out := make([]Disk, 0, len(best))
for _, m := range best {
free, total, used, ro, err := diskSpace(m.Point)
if err != nil || total == 0 {
continue
}
p := strings.TrimPrefix(m.Point, root)
if p == "" {
p = "/"
}
out = append(out, Disk{Path: p, FS: m.FS, Total: total, Free: free, Used: used, RO: ro})
}
sort.Slice(out, func(i, j int) bool { return out[i].Path < out[j].Path })
return out
}

// mountOf devolve o ponto de montagem (como o usuário o conhece) e o tipo da partição onde fica logical: o ponto de
// montagem mais longo, dentro de root, que contém o caminho.
func mountOf(root, logical string, mounts []mountEntry) (string, string) {
root = strings.TrimSuffix(filepath.Clean(root), "/")
full := root + logical
if logical == "/" {
full = root
}
best, fs := "", ""
for _, m := range mounts {
if m.Point != root && !strings.HasPrefix(m.Point, root+"/") && root != "" {
continue
}
if (full == m.Point || strings.HasPrefix(full, strings.TrimSuffix(m.Point, "/")+"/")) && len(m.Point) >= len(best) {
best, fs = m.Point, m.FS
}
}
if best == "" {
return "", ""
}
p := strings.TrimPrefix(best, root)
if p == "" {
p = "/"
}
return p, fs
}
35 changes: 35 additions & 0 deletions internal/agentcore/localdir_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,3 +159,38 @@ func TestSistemasVirtuaisFicamDeFora(t *testing.T) {
}
}
}

func TestParticoesMontadasComUso(t *testing.T) {
root := t.TempDir()
mk(t, root, "boot/", "mnt/hd2/", "var/lib/docker/overlay2/x/merged/")
info := strings.Join([]string{
"20 1 8:1 / / rw - overlay overlay rw", // a raiz do próprio contêiner do agente: fora de root
"30 20 8:1 / " + root + " rw - ext4 /dev/sda1 rw",
"31 30 8:2 / " + root + "/boot rw - vfat /dev/sda2 rw",
"32 30 8:17 / " + root + "/mnt/hd2 rw - xfs /dev/sdb1 rw",
"33 30 8:1 /var/lib/docker " + root + "/var/lib/docker rw - ext4 /dev/sda1 rw", // mesmo disco da raiz: não repete
"34 30 0:50 / " + root + "/var/lib/docker/overlay2/x/merged rw - overlay overlay rw",
"35 30 0:22 / " + root + "/proc rw - proc proc rw",
"36 30 0:23 / " + root + "/run rw - tmpfs tmpfs rw",
}, "\n")
got := listDisks(root, parseMountInfo(strings.NewReader(info)))
var paths []string
for _, d := range got {
paths = append(paths, d.Path+" "+d.FS)
if d.Total <= 0 || d.Free <= 0 || d.Free > d.Total {
t.Fatalf("espaço inválido: %+v", d)
}
}
if !slices.Equal(paths, []string{"/ ext4", "/boot vfat", "/mnt/hd2 xfs"}) {
t.Fatalf("partições: %v", paths)
}
}

func TestParticaoDaPasta(t *testing.T) {
m := parseMountInfo(strings.NewReader("30 20 8:1 / /host-rw rw - ext4 /dev/sda1 rw\n32 30 8:17 / /host-rw/mnt/hd2 rw - xfs /dev/sdb1 rw\n33 30 8:18 / /host-rw/mnt/hd22 rw - xfs /dev/sdc1 rw\n"))
for in, want := range map[string]string{"/home/bkp": "/ ext4", "/": "/ ext4", "/mnt/hd2": "/mnt/hd2 xfs", "/mnt/hd2/copias": "/mnt/hd2 xfs", "/mnt/hd22x": "/ ext4"} {
if p, fs := mountOf("/host-rw", in, m); p+" "+fs != want {
t.Errorf("%s: %s %s, esperado %s", in, p, fs, want)
}
}
}
2 changes: 1 addition & 1 deletion internal/version/version.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,6 @@
package version

// Version é sobrescrita no build: -ldflags "-X github.com/AprendendoLinux/corujabackup/internal/version.Version=1.2.3".
var Version = "0.0.17"
var Version = "0.0.18"

const Name = "Coruja Backup"
4 changes: 2 additions & 2 deletions scripts/release.sh
Original file line number Diff line number Diff line change
@@ -1,8 +1,8 @@
#!/bin/sh
# Publicação manual das imagens multi-arquitetura (o fluxo normal é o workflow "Release", disparado pela tag vX.Y.Z).
# Uso: ./scripts/release.sh 0.0.17 (precisa de "docker login ghcr.io" e do buildx)
# Uso: ./scripts/release.sh 0.0.18 (precisa de "docker login ghcr.io" e do buildx)
set -e
V="${1:?informe a versão, ex.: 0.0.17}"
V="${1:?informe a versão, ex.: 0.0.18}"
OWNER="${OWNER:-aprendendolinux}"
cd "$(dirname "$0")/.."
# Segredo do app OAuth padrão do Google (opcional): GOOGLE_CLIENT_SECRET_FILE=/caminho/arquivo ./scripts/release.sh X.Y.Z
Expand Down
2 changes: 1 addition & 1 deletion web/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "coruja-backup-web",
"private": true,
"version": "0.0.17",
"version": "0.0.18",
"type": "module",
"scripts": {
"dev": "vite",
Expand Down
6 changes: 3 additions & 3 deletions web/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -33,7 +33,7 @@ type NavItem = { to: string; label: string; icon: IconName; admin?: boolean }
const NAV: { title: string; items: NavItem[] }[] = [
{ title: 'Operação', items: [
{ to: 'painel', label: 'Painel', icon: 'painel' }, { to: 'agentes', label: 'Agentes', icon: 'agentes' },
{ to: 'jobs', label: 'Jobs', icon: 'jobs' }, { to: 'nuvem', label: 'Destinos', icon: 'destinos' }, { to: 'historico', label: 'Histórico', icon: 'historico' },
{ to: 'jobs', label: 'Jobs', icon: 'jobs' }, { to: 'nuvem', label: 'Storages', icon: 'destinos' }, { to: 'historico', label: 'Histórico', icon: 'historico' },
] },
{ title: 'Administração', items: [
{ to: 'usuarios', label: 'Usuários', icon: 'usuarios', admin: true }, { to: 'notificacoes', label: 'Notificações', icon: 'notificacoes', admin: true },
Expand All @@ -48,7 +48,7 @@ export default function App() {
const [brand, setBrand] = useState<Branding>({ name: 'Coruja Backup', theme: 'coruja', themes: [], has_logo: false })
const [phase, setPhase] = useState<Phase>('loading')
const [me, setMe] = useState<Me | null>(null)
const [version, setVersion] = useState('0.0.17')
const [version, setVersion] = useState('0.0.18')
const [drawer, setDrawer] = useState(false)
const [collapsed, setCollapsed] = useState(readCollapsed)
const route = useRoute()
Expand Down Expand Up @@ -184,7 +184,7 @@ export default function App() {
<main className="mx-auto w-full max-w-6xl flex-1 px-4 py-8 sm:px-8">
{page === 'agentes' ? <Agents me={me.user} />
: page === 'jobs' ? <Jobs me={me.user} />
: page === 'nuvem' ? <Clouds me={me.user} />
: page === 'nuvem' || page === 'storages' ? <Clouds me={me.user} />
: page === 'historico' ? <Runs me={me.user} jobFilter={Number(new URLSearchParams(route.split('?')[1] ?? '').get('job') ?? 0)} />
: page === 'usuarios' && isAdmin ? <Users me={me.user} />
: page === 'auditoria' && isAdmin ? <Audit />
Expand Down
8 changes: 4 additions & 4 deletions web/src/LocalDir.tsx
Original file line number Diff line number Diff line change
@@ -1,9 +1,9 @@
// Pasta do backup local: escolhida no disco do agente, com o espaço disponível.
import { useEffect, useRef, useState } from 'react'
import { api, ApiError } from './api'
import { FolderField, FolderList, SpaceBar } from './Picker'
import { DiskInfo, FolderField, FolderList, SpaceBar } from './Picker'

type Disk = { entries: { name: string }[]; free?: number; total?: number; blocked?: string; exists?: boolean }
type Disk = { entries: { name: string }[]; free?: number; total?: number; used?: number; blocked?: string; exists?: boolean; disks?: DiskInfo[]; mount?: string; fs?: string }

const browse = (agentId: number, path: string) => api<Disk>('GET', `/api/agents/${agentId}/browse?area=disk&path=${encodeURIComponent(path)}`)

Expand Down Expand Up @@ -40,7 +40,7 @@ export function LocalDirField({ agentId, agentName, agentVersion, value, onChang

async function load(path: string): Promise<FolderList> {
const r = await browse(agentId, '/' + path)
return { folders: r.entries.map((e) => e.name), free: r.free, total: r.total, blocked: r.blocked }
return { folders: r.entries.map((e) => e.name), free: r.free, total: r.total, used: r.used, mount: r.mount, fs: r.fs, blocked: r.blocked, disks: r.disks }
}
const legacy = value && !chosen ? `pasta padrão do agente › ${value}` : ''
return (
Expand All @@ -51,7 +51,7 @@ export function LocalDirField({ agentId, agentName, agentVersion, value, onChang
hint="Onde o arquivo do backup é gerado e onde ficam as cópias locais. A retenção só apaga os arquivos deste job."
onChange={(v) => onChange(v ? '/' + v.replace(/^\/+/, '') : '')}
picker={{ title: `Pasta do backup local em ${agentName}`, intro: 'Discos e pastas do agente. O espaço mostrado é o do disco onde a pasta fica.', rootLabel: 'Raiz', load: (p) => load(p) }} />
{space?.total ? <SpaceBar free={space.free ?? 0} total={space.total} /> : null}
{space?.total ? <SpaceBar free={space.free ?? 0} total={space.total} usedBytes={space.used} mount={space.mount} fs={space.fs} /> : null}
{space && !space.exists && <p className="text-xs text-muted">Esta pasta será criada no primeiro backup.</p>}
{space?.blocked && <p className="text-xs text-danger">{space.blocked}</p>}
{err && <p className="text-xs text-danger">{err}</p>}
Expand Down
Loading
Loading