Compare commits
4
Commits
399c64e801
...
6117c044b5
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
6117c044b5 | ||
|
|
c7710145a1 | ||
|
|
792b7fbb84 | ||
|
|
95f8066eed |
No files matched your search
@@ -6,3 +6,10 @@
|
||||
!/deploy/docker/.env.prod.example
|
||||
/deploy/docker/control-api/control-api.docker.yaml
|
||||
/rxprod-compose/.env
|
||||
|
||||
# Live runtime database for the rxprod-compose control-api container.
|
||||
/rxprod-compose/capi-db/
|
||||
|
||||
# Generated /graphify knowledge-graph output (viz, JSON, report, cache) —
|
||||
# regenerate anytime with /graphify, never hand-edited.
|
||||
/graphify-out/
|
||||
+4
-4
@@ -1,4 +1,4 @@
|
||||
8f2ad37b7819131a9b25eee9d35a57880c7aa233bbb741f4fd8dc0af33f6241c control-api
|
||||
3288930ce4e09e6793048103e25991f025f71dbedced39dee9bccf821eb72a3d validator-agent
|
||||
586cb533631dfcef2246cdb69e20777f882506755d15afe475399356c1ed2d02 prober
|
||||
4729c33a2bce584cba29a8833b0701c0a1cd98bb17bf331aabffc27c4cde940c admin-dashboard
|
||||
dcb137ae6a3f6a59465f2772215d48f98fd303dd1c266645b20ec70194ab7915 control-api
|
||||
b7a6068db1d095ae7b73cbd9b7273d6a1629ae017e9c3c9601e103432894a247 validator-agent
|
||||
be8e9576c6fbe5e5798b5d4b758a5617b63bea6abe80e326998d10583edbbf5c prober
|
||||
579253ac22d6b9537870cf45aaa85437a4a9dba0c87eab9ba8c49c28e50ee438 admin-dashboard
|
||||
Binary file not shown.
Binary file not shown.
BIN
Binary file not shown.
Binary file not shown.
@@ -30,6 +30,13 @@ type Agent struct {
|
||||
log *slog.Logger
|
||||
|
||||
lastHandledIPID int64
|
||||
|
||||
// registerRetryInitial/Max govern the backoff used while waiting for a
|
||||
// successful registration (see registerWithRetry): control-api may not
|
||||
// be up yet at agent boot, or may come and go across a redeploy, and the
|
||||
// agent should keep waiting rather than exit.
|
||||
registerRetryInitial time.Duration
|
||||
registerRetryMax time.Duration
|
||||
}
|
||||
|
||||
func New(cfg *config.ValidatorAgent, log *slog.Logger) *Agent {
|
||||
@@ -41,14 +48,16 @@ func New(cfg *config.ValidatorAgent, log *slog.Logger) *Agent {
|
||||
cfg: cfg,
|
||||
client: apiclient.New(cfg.ControlAPIURL, timeout+5*time.Second),
|
||||
log: log,
|
||||
registerRetryInitial: 3 * time.Second,
|
||||
registerRetryMax: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
// Run registers with the Control API and polls forever until ctx is
|
||||
// cancelled.
|
||||
func (a *Agent) Run(ctx context.Context) error {
|
||||
if err := a.register(ctx); err != nil {
|
||||
return fmt.Errorf("register: %w", err)
|
||||
if err := a.registerWithRetry(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
interval := time.Duration(a.cfg.PollIntervalSeconds) * time.Second
|
||||
@@ -88,6 +97,32 @@ func (a *Agent) register(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// registerWithRetry retries register with capped exponential backoff until
|
||||
// it succeeds or ctx is cancelled. Control-api may not be reachable yet at
|
||||
// agent boot (started before control-api, or a network blip), or may reject
|
||||
// the request until an admin adds this validator_id to its config — either
|
||||
// way the agent should keep waiting rather than exit, since both conditions
|
||||
// can resolve on their own after the agent has already started.
|
||||
func (a *Agent) registerWithRetry(ctx context.Context) error {
|
||||
delay := a.registerRetryInitial
|
||||
for {
|
||||
err := a.register(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
a.log.Warn("registration failed, will retry", "err", err, "retry_in", delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(delay):
|
||||
}
|
||||
delay *= 2
|
||||
if delay > a.registerRetryMax {
|
||||
delay = a.registerRetryMax
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type heartbeatReq struct {
|
||||
LocalState string `json:"local_state"`
|
||||
}
|
||||
|
||||
@@ -0,0 +1,100 @@
|
||||
package agentcore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"cloudipvalidator/internal/apiclient"
|
||||
"cloudipvalidator/internal/config"
|
||||
)
|
||||
|
||||
func testLogger() *slog.Logger {
|
||||
return slog.New(slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{Level: slog.LevelError}))
|
||||
}
|
||||
|
||||
// TestRegisterWithRetrySucceedsAfterControlAPIComesUp mirrors starting the
|
||||
// validator-agent before control-api is up (or before an admin has
|
||||
// configured this validator_id): the first attempts fail, and the agent
|
||||
// must keep retrying — not give up — until registration succeeds.
|
||||
func TestRegisterWithRetrySucceedsAfterControlAPIComesUp(t *testing.T) {
|
||||
var attempts int32
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/agents/register", func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&attempts, 1)
|
||||
if n < 3 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
w.Write([]byte(`{"ok":true,"poll_interval_seconds":5}`))
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
a := &Agent{
|
||||
cfg: &config.ValidatorAgent{ValidatorID: "val-1", ControlAPIURL: ts.URL},
|
||||
client: apiclient.New(ts.URL, 5*time.Second),
|
||||
log: testLogger(),
|
||||
registerRetryInitial: time.Millisecond,
|
||||
registerRetryMax: 5 * time.Millisecond,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := a.registerWithRetry(ctx); err != nil {
|
||||
t.Fatalf("expected eventual success, got err: %v", err)
|
||||
}
|
||||
if got := atomic.LoadInt32(&attempts); got != 3 {
|
||||
t.Fatalf("expected exactly 3 attempts, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterWithRetryStopsOnCancel confirms a validator-agent waiting on
|
||||
// an unreachable/unconfigured control-api can still be shut down promptly
|
||||
// (e.g. via SIGTERM) instead of retrying forever with no way out.
|
||||
func TestRegisterWithRetryStopsOnCancel(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/agents/register", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
a := &Agent{
|
||||
cfg: &config.ValidatorAgent{ValidatorID: "val-1", ControlAPIURL: ts.URL},
|
||||
client: apiclient.New(ts.URL, 5*time.Second),
|
||||
log: testLogger(),
|
||||
registerRetryInitial: 10 * time.Millisecond,
|
||||
registerRetryMax: 10 * time.Millisecond,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
var err error
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
err = a.registerWithRetry(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("registerWithRetry did not return after ctx cancellation")
|
||||
}
|
||||
if err != context.Canceled {
|
||||
t.Fatalf("expected context.Canceled, got %v", err)
|
||||
}
|
||||
}
|
||||
@@ -98,8 +98,10 @@ type clearQueueResponse struct {
|
||||
|
||||
type validatorDTO struct {
|
||||
ValidatorID string `json:"validator_id"`
|
||||
Hostname string `json:"hostname"`
|
||||
OSPortID string `json:"os_port_id"`
|
||||
State string `json:"state"`
|
||||
LastHeartbeatAt *time.Time `json:"last_heartbeat_at"`
|
||||
}
|
||||
|
||||
type siteDTO struct {
|
||||
|
||||
@@ -5,25 +5,110 @@ import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
// usedByTag names one check type that references a target group, and
|
||||
// whether that check type is currently enabled — rendered as a status pill
|
||||
// next to the group so the relationship (invisible before this page had
|
||||
// this column) is visible without cross-referencing /check-types by hand.
|
||||
type usedByTag struct {
|
||||
Name string
|
||||
Enabled bool
|
||||
}
|
||||
|
||||
// targetGroupView is targetGroupDTO plus the check types that reference it,
|
||||
// resolved server-side from ListCheckTypes so the template stays a plain
|
||||
// range with no cross-referencing logic of its own.
|
||||
type targetGroupView struct {
|
||||
targetGroupDTO
|
||||
UsedBy []usedByTag
|
||||
}
|
||||
|
||||
type targetsStats struct {
|
||||
Groups int
|
||||
TotalTargets int
|
||||
CheckTypesUsing int
|
||||
Unused int
|
||||
}
|
||||
|
||||
type targetsPageData struct {
|
||||
PageData
|
||||
Items []targetGroupDTO
|
||||
Items []targetGroupView
|
||||
Stats targetsStats
|
||||
}
|
||||
|
||||
// loadTargetsPage fetches target groups and check types together and
|
||||
// resolves the group -> referencing-check-types relationship server-side.
|
||||
// A ListCheckTypes failure degrades to "no usage info" rather than hiding
|
||||
// the group list — the error still surfaces via the banner.
|
||||
func (s *Server) loadTargetsPage(r *http.Request) (targetsPageData, error) {
|
||||
groups, err := s.CA.ListTargetGroups(r.Context())
|
||||
if err != nil {
|
||||
return targetsPageData{}, err
|
||||
}
|
||||
checkTypes, ctErr := s.CA.ListCheckTypes(r.Context())
|
||||
|
||||
usedBy := make(map[string][]usedByTag)
|
||||
checkTypesUsing := 0
|
||||
for _, ct := range checkTypes {
|
||||
if len(ct.Targets) > 0 {
|
||||
checkTypesUsing++
|
||||
}
|
||||
for _, g := range ct.Targets {
|
||||
usedBy[g] = append(usedBy[g], usedByTag{Name: ct.Name, Enabled: ct.Enabled})
|
||||
}
|
||||
}
|
||||
|
||||
items := make([]targetGroupView, len(groups))
|
||||
totalTargets := 0
|
||||
unused := 0
|
||||
for i, g := range groups {
|
||||
items[i] = targetGroupView{targetGroupDTO: g, UsedBy: usedBy[g.Name]}
|
||||
totalTargets += len(g.Targets)
|
||||
if len(usedBy[g.Name]) == 0 {
|
||||
unused++
|
||||
}
|
||||
}
|
||||
|
||||
return targetsPageData{
|
||||
Items: items,
|
||||
Stats: targetsStats{
|
||||
Groups: len(groups),
|
||||
TotalTargets: totalTargets,
|
||||
CheckTypesUsing: checkTypesUsing,
|
||||
Unused: unused,
|
||||
},
|
||||
}, ctErr
|
||||
}
|
||||
|
||||
func (s *Server) handleTargetsPage(w http.ResponseWriter, r *http.Request) {
|
||||
items, err := s.CA.ListTargetGroups(r.Context())
|
||||
data := targetsPageData{Items: items}
|
||||
data, err := s.loadTargetsPage(r)
|
||||
data.ActiveNav = "targets"
|
||||
data.Banner = bannerFor(err)
|
||||
s.renderPage(w, "targets_page", data)
|
||||
}
|
||||
|
||||
// renderTargetsTable renders the #targets-table-wrap swap target plus,
|
||||
// appended to the same response, an out-of-band update of #targets-stats-wrap
|
||||
// (see targets_stats_oob in targets.html) — that block sits above the create
|
||||
// form, outside the swap target, so it needs its own refresh to stay live
|
||||
// after a create/update/delete. Can't use the shared renderFragment helper
|
||||
// here because of that second OOB block; otherwise mirrors it exactly,
|
||||
// including always appending error_banner last.
|
||||
func (s *Server) renderTargetsTable(w http.ResponseWriter, r *http.Request, actionErr error) {
|
||||
items, listErr := s.CA.ListTargetGroups(r.Context())
|
||||
data, listErr := s.loadTargetsPage(r)
|
||||
if actionErr == nil {
|
||||
actionErr = listErr
|
||||
}
|
||||
s.renderFragment(w, "targets_table", targetsPageData{Items: items}, actionErr)
|
||||
w.Header().Set("Content-Type", "text/html; charset=utf-8")
|
||||
if err := s.tmpl.ExecuteTemplate(w, "targets_table", data); err != nil {
|
||||
s.Log.Error("render fragment", "template", "targets_table", "err", err)
|
||||
return
|
||||
}
|
||||
if err := s.tmpl.ExecuteTemplate(w, "targets_stats_oob", data); err != nil {
|
||||
s.Log.Error("render targets stats oob", "err", err)
|
||||
}
|
||||
if err := s.tmpl.ExecuteTemplate(w, "error_banner", bannerFor(actionErr)); err != nil {
|
||||
s.Log.Error("render error banner", "err", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *Server) handleTargetCreate(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
@@ -376,6 +376,17 @@ func TestSitesPageShowsProberBadge(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidatorsPageShowsHostname(t *testing.T) {
|
||||
fake, caURL := newFakeControlAPI(t)
|
||||
fake.validators = append(fake.validators, validatorDTO{ValidatorID: "val-1", Hostname: "validator-host-1", OSPortID: "port-1", State: "idle"})
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
page := get(t, ts, "/validators")
|
||||
if !strings.Contains(page, "validator-host-1") {
|
||||
t.Fatalf("expected hostname shown, got:\n%s", page)
|
||||
}
|
||||
}
|
||||
|
||||
func TestTargetsAndCheckTypesRoundTrip(t *testing.T) {
|
||||
_, caURL := newFakeControlAPI(t)
|
||||
ts := newTestServer(t, caURL)
|
||||
|
||||
@@ -114,6 +114,24 @@ var funcMap = template.FuncMap{
|
||||
"deref": derefStr,
|
||||
"join": strings.Join,
|
||||
"joinInts": joinInts,
|
||||
"pluralAddr": pluralAddr,
|
||||
}
|
||||
|
||||
// pluralAddr returns the correctly declined Russian word for "address"
|
||||
// (адрес/адреса/адресов) for the given count — standard count%10/count%100
|
||||
// rule, with the usual 11-14 exception.
|
||||
func pluralAddr(n int) string {
|
||||
if n%100 >= 11 && n%100 <= 14 {
|
||||
return "адресов"
|
||||
}
|
||||
switch n % 10 {
|
||||
case 1:
|
||||
return "адрес"
|
||||
case 2, 3, 4:
|
||||
return "адреса"
|
||||
default:
|
||||
return "адресов"
|
||||
}
|
||||
}
|
||||
|
||||
func parseTemplates() (*template.Template, error) {
|
||||
|
||||
@@ -264,7 +264,7 @@ nav.nav-groups { display: flex; flex-direction: column; gap: 1px; }
|
||||
:root[data-theme="dark"] .theme-toggle .icon-sun { display: none; }
|
||||
:root[data-theme="dark"] .theme-toggle .icon-moon { display: block; }
|
||||
|
||||
.main { padding: 22px 26px 60px; max-width: 1180px; }
|
||||
.main { padding: 22px 26px 60px; max-width: 1180px; margin-inline: auto; }
|
||||
.topbar {
|
||||
display: flex; align-items: baseline; justify-content: space-between;
|
||||
margin-bottom: 18px; flex-wrap: wrap; gap: 10px;
|
||||
@@ -273,7 +273,13 @@ nav.nav-groups { display: flex; flex-direction: column; gap: 1px; }
|
||||
|
||||
/* ---------- stat cards ---------- */
|
||||
.stat-grid {
|
||||
display: grid; grid-template-columns: repeat(6, 1fr);
|
||||
/* auto-fit instead of a fixed repeat(6, ...): the state histogram this
|
||||
drives is a variable-length map (whichever ip_queue states are
|
||||
actually present), so a fixed column count left visible empty
|
||||
background showing through the unused grid tracks whenever fewer
|
||||
than 6 cards exist. auto-fit collapses empty tracks and lets the
|
||||
real cards stretch to fill the row instead. */
|
||||
display: grid; grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
|
||||
gap: 1px; background: var(--border);
|
||||
border: 1px solid var(--border);
|
||||
border-radius: var(--radius-sm);
|
||||
@@ -475,7 +481,6 @@ code.inline { font-family: var(--font-mono); background: var(--surface-alt); bor
|
||||
display: grid; place-items: center; cursor: pointer; flex-shrink: 0;
|
||||
}
|
||||
.main { padding: 16px 14px 50px; }
|
||||
.stat-grid { grid-template-columns: repeat(2, 1fr); }
|
||||
}
|
||||
|
||||
@media (max-width: 640px) {
|
||||
@@ -496,3 +501,46 @@ code.inline { font-family: var(--font-mono); background: var(--surface-alt); bor
|
||||
}
|
||||
.actions { justify-content: flex-start; margin-top: 6px; }
|
||||
}
|
||||
|
||||
/* ---------- targets page: group summary + usage ---------- */
|
||||
|
||||
/* 4-card variant of .stat-grid for pages whose summary row isn't the
|
||||
dynamic ips_by_state histogram (which wants 6 columns). */
|
||||
.stat-grid.cols-4 { grid-template-columns: repeat(4, 1fr); }
|
||||
@media (max-width: 900px) { .stat-grid.cols-4 { grid-template-columns: repeat(2, 1fr); } }
|
||||
|
||||
/* Neutral data token for listing individual targets inline — distinct
|
||||
from .pill (which always carries a status meaning via its color + dot):
|
||||
a chip is just a value, not a state. */
|
||||
.chip-list { display: flex; flex-wrap: wrap; gap: 5px; max-width: 460px; }
|
||||
.chip {
|
||||
font-family: var(--font-mono);
|
||||
font-size: 11.5px;
|
||||
padding: 2px 7px;
|
||||
border-radius: var(--radius-xs);
|
||||
background: var(--surface-alt);
|
||||
border: 1px solid var(--border-soft);
|
||||
color: var(--text-muted);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
/* Row group name + target count, stacked. */
|
||||
.group-name { display: flex; flex-direction: column; gap: 2px; }
|
||||
.group-name .count { font-size: 11px; color: var(--text-faint); font-weight: 400; text-transform: none; letter-spacing: 0; font-family: var(--font-ui); }
|
||||
|
||||
/* "Used by" cell — wraps its pills with a small gap, same idiom as
|
||||
chip-list, kept separate since these ARE status-colored .pill elements. */
|
||||
.used-by { display: flex; flex-wrap: wrap; gap: 4px; }
|
||||
|
||||
/* Inline edit row, toggled open by the "Изменить" button — collapses by
|
||||
default so the table stays scannable instead of showing N always-open
|
||||
textareas at once. */
|
||||
tr.edit-row td { background: var(--surface-alt); padding: 14px 16px; }
|
||||
tr.edit-row textarea { flex: 1 1 auto; }
|
||||
|
||||
/* Auto-growing textarea (new-group form + per-row edit forms above) —
|
||||
stretches with content instead of showing an internal scrollbar
|
||||
immediately; only caps out (and starts scrolling) past ~20 lines.
|
||||
Height is set by JS (see templates/targets.html), computed from the
|
||||
field's own line-height, so it stays correct if font-size ever changes. */
|
||||
textarea.autosize { overflow-y: hidden; resize: none; }
|
||||
@@ -15,6 +15,49 @@
|
||||
</main>
|
||||
</div>
|
||||
</div>
|
||||
<script>
|
||||
(function () {
|
||||
var maxLines = 20;
|
||||
function resize(el) {
|
||||
var cs = getComputedStyle(el);
|
||||
var lineHeight = parseFloat(cs.lineHeight) || parseFloat(cs.fontSize) * 1.5;
|
||||
var paddingV = parseFloat(cs.paddingTop) + parseFloat(cs.paddingBottom);
|
||||
var borderV = parseFloat(cs.borderTopWidth) + parseFloat(cs.borderBottomWidth);
|
||||
var maxHeight = Math.round(lineHeight * maxLines + paddingV + borderV);
|
||||
el.style.height = 'auto';
|
||||
var next = Math.min(el.scrollHeight, maxHeight);
|
||||
el.style.height = next + 'px';
|
||||
el.style.overflowY = el.scrollHeight > maxHeight ? 'auto' : 'hidden';
|
||||
}
|
||||
function bind(el) {
|
||||
if (el.dataset.autosizeBound) return;
|
||||
el.dataset.autosizeBound = '1';
|
||||
el.addEventListener('input', function () { resize(el); });
|
||||
// An element inside a hidden (display:none) edit row reports
|
||||
// scrollHeight 0 — sizing it now would wrongly collapse it to ~0px
|
||||
// and that inline height sticks around after the row is later shown.
|
||||
// Skip the initial measurement here; toggleEditRow re-measures once
|
||||
// the row is actually visible.
|
||||
if (el.offsetParent !== null) resize(el);
|
||||
}
|
||||
function bindAll() {
|
||||
document.querySelectorAll('textarea.autosize').forEach(bind);
|
||||
}
|
||||
document.addEventListener('DOMContentLoaded', bindAll);
|
||||
document.body.addEventListener('htmx:afterSwap', bindAll);
|
||||
|
||||
// Shared by every row's "Изменить"/"Отмена" buttons (see targets_table).
|
||||
window.toggleEditRow = function (name) {
|
||||
var row = document.getElementById('edit-' + name);
|
||||
if (!row) return;
|
||||
row.hidden = !row.hidden;
|
||||
if (!row.hidden) {
|
||||
var ta = row.querySelector('textarea.autosize');
|
||||
if (ta) { bind(ta); resize(ta); }
|
||||
}
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
{{end}}
|
||||
@@ -23,18 +66,20 @@
|
||||
<div class="topbar"><h1>Цели проверки</h1></div>
|
||||
<p class="muted" style="margin-bottom:16px">Группа целей — именованный список URL/адресов, на который затем ссылаются типы проверок.</p>
|
||||
|
||||
<div id="targets-stats-wrap">{{template "targets_stats_inner" .}}</div>
|
||||
|
||||
<div class="panel">
|
||||
<div class="panel-head"><h2>Новая группа целей</h2></div>
|
||||
<div class="panel-body">
|
||||
<form hx-post="/targets" hx-target="#targets-table-wrap" hx-swap="innerHTML" hx-on::after-request="this.reset()">
|
||||
<div class="field-row">
|
||||
<div class="field" style="flex: 0 1 200px;">
|
||||
<label>Имя новой группы</label>
|
||||
<input type="text" name="name" placeholder="web" required>
|
||||
<label for="new-group-name">Имя новой группы</label>
|
||||
<input type="text" id="new-group-name" name="name" placeholder="web" required>
|
||||
</div>
|
||||
<div class="field" style="flex: 1 1 380px;">
|
||||
<label>Цели (по одной на строку или через запятую)</label>
|
||||
<textarea name="targets" rows="2" placeholder="https://hub.docker.com https://github.com" required></textarea>
|
||||
<label for="new-group-targets">Цели (по одной на строку или через запятую)</label>
|
||||
<textarea id="new-group-targets" name="targets" rows="2" class="autosize" placeholder="https://hub.docker.com https://github.com" required></textarea>
|
||||
</div>
|
||||
<button type="submit" class="btn btn-primary">Создать</button>
|
||||
</div>
|
||||
@@ -47,31 +92,61 @@
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{/* Stat-grid content only, shared by the initial page render (plain,
|
||||
inside #targets-stats-wrap above) and the OOB update below (targets
|
||||
mutations only swap #targets-table-wrap, so the stats need their own
|
||||
out-of-band refresh to stay live — same pattern as layout.html's
|
||||
banner_inner/error_banner split). */}}
|
||||
{{define "targets_stats_inner"}}
|
||||
<div class="stat-grid cols-4">
|
||||
<div class="stat-card accented"><span class="value">{{.Stats.Groups}}</span><span class="label">групп целей</span></div>
|
||||
<div class="stat-card"><span class="value">{{.Stats.TotalTargets}}</span><span class="label">адресов всего</span></div>
|
||||
<div class="stat-card"><span class="value">{{.Stats.CheckTypesUsing}}</span><span class="label">типа проверок ссылаются</span></div>
|
||||
<div class="stat-card{{if gt .Stats.Unused 0}} warn{{end}}"><span class="value">{{.Stats.Unused}}</span><span class="label">без типа проверки</span></div>
|
||||
</div>
|
||||
{{end}}
|
||||
|
||||
{{define "targets_stats_oob"}}<div id="targets-stats-wrap" hx-swap-oob="true">{{template "targets_stats_inner" .}}</div>{{end}}
|
||||
|
||||
{{define "targets_table"}}
|
||||
<div class="panel">
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th>Группа</th><th>Цели</th><th></th></tr></thead>
|
||||
<thead><tr><th>Группа</th><th>Цели</th><th>Используется в</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Items}}
|
||||
<tr>
|
||||
<td class="mono" data-label="Группа">{{.Name}}</td>
|
||||
<td data-label="Группа">
|
||||
<span class="group-name"><span class="mono" style="font-weight:600">{{.Name}}</span><span class="count">{{len .Targets}} {{pluralAddr (len .Targets)}}</span></span>
|
||||
</td>
|
||||
<td data-label="Цели">
|
||||
<form class="inline-form" hx-put="/targets/{{.Name}}" hx-target="#targets-table-wrap" hx-swap="innerHTML">
|
||||
<textarea name="targets" rows="2">{{join .Targets "\n"}}</textarea>
|
||||
<button type="submit" class="btn btn-ghost btn-sm">Сохранить</button>
|
||||
</form>
|
||||
<div class="chip-list">{{range .Targets}}<span class="chip">{{.}}</span>{{end}}</div>
|
||||
</td>
|
||||
<td data-label="Используется в">
|
||||
{{if .UsedBy}}<div class="used-by">{{range .UsedBy}}<span class="pill {{if .Enabled}}pill-success{{else}}pill-neutral{{end}}">{{.Name}}{{if not .Enabled}} (выкл.){{end}}</span>{{end}}</div>
|
||||
{{else}}<span class="muted">не используется ни одним типом проверки</span>{{end}}
|
||||
</td>
|
||||
<td data-label="">
|
||||
<div class="actions">
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="toggleEditRow('{{.Name}}')">Изменить</button>
|
||||
<button class="btn btn-danger-ghost btn-sm" hx-delete="/targets/{{.Name}}" hx-target="#targets-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить группу {{.Name}}?">Удалить</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
<tr class="edit-row" id="edit-{{.Name}}" hidden>
|
||||
<td colspan="4">
|
||||
<form class="inline-form" hx-put="/targets/{{.Name}}" hx-target="#targets-table-wrap" hx-swap="innerHTML">
|
||||
<textarea name="targets" rows="2" class="autosize">{{join .Targets "\n"}}</textarea>
|
||||
<button type="submit" class="btn btn-primary btn-sm">Сохранить</button>
|
||||
<button type="button" class="btn btn-ghost btn-sm" onclick="toggleEditRow('{{.Name}}')">Отмена</button>
|
||||
</form>
|
||||
</td>
|
||||
</tr>
|
||||
{{end}}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
{{if .Items}}<div class="section-note">Колонка «Используется в» показывает типы проверок (<a href="/check-types" style="color:var(--accent)">/check-types</a>), которые ссылаются на группу; пусто — группа ничем не используется. «Изменить» разворачивает поле для редактирования только для этой группы.</div>{{end}}
|
||||
</div>
|
||||
{{if not .Items}}<p class="muted">Групп целей нет.</p>{{end}}
|
||||
{{end}}
|
||||
@@ -50,12 +50,13 @@
|
||||
<div class="panel">
|
||||
<div class="table-scroll">
|
||||
<table>
|
||||
<thead><tr><th>ID</th><th>OS Port ID</th><th>Состояние</th><th></th></tr></thead>
|
||||
<thead><tr><th>ID</th><th>Хост</th><th>OS Port ID</th><th>Состояние</th><th>Heartbeat</th><th></th></tr></thead>
|
||||
<tbody>
|
||||
{{range .Items}}
|
||||
{{$b := validatorBadge .State}}
|
||||
<tr>
|
||||
<td class="mono" data-label="ID">{{.ValidatorID}}</td>
|
||||
<td class="mono" data-label="Хост">{{if .Hostname}}{{.Hostname}}{{else}}—{{end}}</td>
|
||||
<td data-label="OS Port ID">
|
||||
<form class="inline-form" hx-put="/validators/{{.ValidatorID}}" hx-target="#validators-table-wrap" hx-swap="innerHTML">
|
||||
<input type="text" name="os_port_id" value="{{.OSPortID}}">
|
||||
@@ -63,6 +64,7 @@
|
||||
</form>
|
||||
</td>
|
||||
<td data-label="Состояние"><span class="pill {{$b.Class}}">{{$b.Label}}</span></td>
|
||||
<td data-label="Heartbeat">{{fmtTime .LastHeartbeatAt}}</td>
|
||||
<td data-label="">
|
||||
<div class="actions">
|
||||
<button class="btn btn-danger-ghost btn-sm" hx-delete="/validators/{{.ValidatorID}}" hx-target="#validators-table-wrap" hx-swap="innerHTML" hx-confirm="Удалить валидатор {{.ValidatorID}}?">Удалить</button>
|
||||
|
||||
@@ -34,8 +34,10 @@ type clearQueueResponse struct {
|
||||
|
||||
type validatorDTO struct {
|
||||
ValidatorID string `json:"validator_id"`
|
||||
Hostname string `json:"hostname"`
|
||||
OSPortID string `json:"os_port_id"`
|
||||
State string `json:"state"`
|
||||
LastHeartbeatAt *time.Time `json:"last_heartbeat_at"`
|
||||
}
|
||||
|
||||
type createValidatorRequest struct {
|
||||
|
||||
@@ -17,7 +17,10 @@ func (s *Server) handleConfigListValidators(w http.ResponseWriter, r *http.Reque
|
||||
}
|
||||
out := make([]validatorDTO, len(validators))
|
||||
for i, v := range validators {
|
||||
out[i] = validatorDTO{ValidatorID: v.ValidatorID, OSPortID: v.OSPortID, State: v.State}
|
||||
out[i] = validatorDTO{
|
||||
ValidatorID: v.ValidatorID, Hostname: v.Hostname, OSPortID: v.OSPortID,
|
||||
State: v.State, LastHeartbeatAt: v.LastHeartbeatAt,
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, out)
|
||||
}
|
||||
|
||||
@@ -666,6 +666,35 @@ func TestProberRegisterSetsHostnameAndIdleState(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestValidatorRegisterSetsHostname proves the admin config listing surfaces
|
||||
// a validator's hostname (and heartbeat time) once its agent registers,
|
||||
// mirroring TestProberRegisterSetsHostnameAndIdleState for sites.
|
||||
func TestValidatorRegisterSetsHostname(t *testing.T) {
|
||||
fc, _, _, _ := newConfigTestHarness(t)
|
||||
|
||||
fc.do(http.MethodPost, "/api/v1/admin/config/validators", createValidatorRequest{ValidatorID: "val-1", OSPortID: "port-1"})
|
||||
|
||||
resp, body := fc.do(http.MethodPost, "/api/v1/agents/register", registerAgentRequest{ValidatorID: "val-1", Hostname: "validator-host-1", AgentVersion: "test"})
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("register agent: status=%d body=%s", resp.StatusCode, body)
|
||||
}
|
||||
|
||||
resp, body = fc.do(http.MethodGet, "/api/v1/admin/config/validators", nil)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
t.Fatalf("get validators: status=%d body=%s", resp.StatusCode, body)
|
||||
}
|
||||
var validators []validatorDTO
|
||||
if err := json.Unmarshal(body, &validators); err != nil {
|
||||
t.Fatalf("unmarshal validators: %v", err)
|
||||
}
|
||||
if len(validators) != 1 || validators[0].Hostname != "validator-host-1" {
|
||||
t.Fatalf("expected hostname validator-host-1, got %+v", validators)
|
||||
}
|
||||
if validators[0].LastHeartbeatAt != nil {
|
||||
t.Fatalf("expected no heartbeat yet (only register was called), got %+v", validators[0].LastHeartbeatAt)
|
||||
}
|
||||
}
|
||||
|
||||
// TestProberHeartbeat404UnknownSite proves the heartbeat endpoint rejects
|
||||
// an unconfigured site_id, mirroring the validator heartbeat's 404.
|
||||
func TestProberHeartbeat404UnknownSite(t *testing.T) {
|
||||
|
||||
@@ -8,7 +8,6 @@ package probercore
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"log/slog"
|
||||
"os"
|
||||
"time"
|
||||
@@ -22,6 +21,13 @@ type Prober struct {
|
||||
cfg *config.Prober
|
||||
client *apiclient.Client
|
||||
log *slog.Logger
|
||||
|
||||
// registerRetryInitial/Max govern the backoff used while waiting for a
|
||||
// successful registration (see registerWithRetry): control-api may not
|
||||
// be up yet at prober boot, or may reject an unconfigured site_id until
|
||||
// an admin adds it — the prober should keep waiting rather than exit.
|
||||
registerRetryInitial time.Duration
|
||||
registerRetryMax time.Duration
|
||||
}
|
||||
|
||||
func New(cfg *config.Prober, log *slog.Logger) *Prober {
|
||||
@@ -33,12 +39,14 @@ func New(cfg *config.Prober, log *slog.Logger) *Prober {
|
||||
cfg: cfg,
|
||||
client: apiclient.New(cfg.ControlAPIURL, timeout+5*time.Second),
|
||||
log: log,
|
||||
registerRetryInitial: 3 * time.Second,
|
||||
registerRetryMax: 30 * time.Second,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Prober) Run(ctx context.Context) error {
|
||||
if err := p.register(ctx); err != nil {
|
||||
return fmt.Errorf("register: %w", err)
|
||||
if err := p.registerWithRetry(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
interval := time.Duration(p.cfg.PollIntervalSeconds) * time.Second
|
||||
@@ -70,6 +78,30 @@ func (p *Prober) register(ctx context.Context) error {
|
||||
return nil
|
||||
}
|
||||
|
||||
// registerWithRetry retries register with capped exponential backoff until
|
||||
// it succeeds or ctx is cancelled — see agentcore.Agent.registerWithRetry
|
||||
// for the identical rationale (control-api may start later, or an admin may
|
||||
// add this site_id to its config later).
|
||||
func (p *Prober) registerWithRetry(ctx context.Context) error {
|
||||
delay := p.registerRetryInitial
|
||||
for {
|
||||
err := p.register(ctx)
|
||||
if err == nil {
|
||||
return nil
|
||||
}
|
||||
p.log.Warn("registration failed, will retry", "err", err, "retry_in", delay)
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return ctx.Err()
|
||||
case <-time.After(delay):
|
||||
}
|
||||
delay *= 2
|
||||
if delay > p.registerRetryMax {
|
||||
delay = p.registerRetryMax
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
type assignment struct {
|
||||
IPID int64 `json:"ip_id"`
|
||||
IPAddress string `json:"ip_address"`
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -95,6 +96,86 @@ func TestPollOnceSkipsAssignmentsWhenHeartbeatFails(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterWithRetrySucceedsAfterSiteConfigured mirrors an admin adding
|
||||
// this prober's site_id to control-api's config after the prober has
|
||||
// already started: registration is rejected with 400 until then, and the
|
||||
// prober must keep retrying rather than give up.
|
||||
func TestRegisterWithRetrySucceedsAfterSiteConfigured(t *testing.T) {
|
||||
var attempts int32
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/probers/register", func(w http.ResponseWriter, r *http.Request) {
|
||||
n := atomic.AddInt32(&attempts, 1)
|
||||
if n < 3 {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
w.Write([]byte(`{"error":"unknown site_id: site-1"}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
p := &Prober{
|
||||
cfg: &config.Prober{SiteID: "site-1", ControlAPIURL: ts.URL},
|
||||
client: apiclient.New(ts.URL, 5*time.Second),
|
||||
log: testLogger(),
|
||||
registerRetryInitial: time.Millisecond,
|
||||
registerRetryMax: 5 * time.Millisecond,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if err := p.registerWithRetry(ctx); err != nil {
|
||||
t.Fatalf("expected eventual success, got err: %v", err)
|
||||
}
|
||||
if got := atomic.LoadInt32(&attempts); got != 3 {
|
||||
t.Fatalf("expected exactly 3 attempts, got %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestRegisterWithRetryStopsOnCancel confirms a prober waiting on an
|
||||
// unreachable/unconfigured control-api can still be shut down promptly.
|
||||
func TestRegisterWithRetryStopsOnCancel(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/probers/register", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
})
|
||||
ts := httptest.NewServer(mux)
|
||||
defer ts.Close()
|
||||
|
||||
p := &Prober{
|
||||
cfg: &config.Prober{SiteID: "site-1", ControlAPIURL: ts.URL},
|
||||
client: apiclient.New(ts.URL, 5*time.Second),
|
||||
log: testLogger(),
|
||||
registerRetryInitial: 10 * time.Millisecond,
|
||||
registerRetryMax: 10 * time.Millisecond,
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
go func() {
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
cancel()
|
||||
}()
|
||||
|
||||
var err error
|
||||
done := make(chan struct{})
|
||||
go func() {
|
||||
defer close(done)
|
||||
err = p.registerWithRetry(ctx)
|
||||
}()
|
||||
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(2 * time.Second):
|
||||
t.Fatal("registerWithRetry did not return after ctx cancellation")
|
||||
}
|
||||
if err != context.Canceled {
|
||||
t.Fatalf("expected context.Canceled, got %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
// TestExtraChecksForPort confirms only ports 443 (TLS) and 22 (SSH) get an
|
||||
// extra protocol check beyond the baseline TCPConnect every port gets.
|
||||
func TestExtraChecksForPort(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
# Control API configuration.
|
||||
#
|
||||
# OpenStack credentials are never set here — only the *names* of the
|
||||
# environment variables to read them from. The actual values must be
|
||||
# supplied by the process environment (see deploy/systemd/control-api.service
|
||||
# and its EnvironmentFile=).
|
||||
|
||||
server:
|
||||
listen_addr: ":8081"
|
||||
|
||||
database:
|
||||
path: "/var/lib/cloud-ip-validator/control-api.db"
|
||||
|
||||
openstack:
|
||||
mode: "real" # "mock" | "real" — mock uses an in-memory
|
||||
# OpenStack stand-in for local dev/testing
|
||||
auth_method: "password" # "token" (default) | "password" — see below
|
||||
|
||||
auth_url_env: "OS_AUTH_URL"
|
||||
project_id_env: "OS_PROJECT_ID"
|
||||
region_env: "OS_REGION_NAME"
|
||||
interface_env: "OS_INTERFACE" # optional; empty env value defaults to "public"
|
||||
|
||||
# auth_method: "token" — an admin supplies an already project-scoped
|
||||
# token directly; it's used as-is for every call, never exchanged for a
|
||||
# new one. Simplest option, but it can't renew itself: when the token
|
||||
# expires, control-api starts failing OpenStack calls until the operator
|
||||
# reissues OS_TOKEN and restarts the process.
|
||||
token_env: "OS_TOKEN"
|
||||
|
||||
# auth_method: "password" — the client authenticates with a normal
|
||||
# Keystone username/password and automatically re-authenticates
|
||||
# (mints a fresh token) whenever the current one is rejected, for as
|
||||
# long as the process runs. Trade-off: a long-lived password credential
|
||||
# sits in the environment file instead of a token.
|
||||
username_env: "OS_USERNAME"
|
||||
user_domain_name_env: "OS_USER_DOMAIN_NAME"
|
||||
password_env: "OS_PASSWORD"
|
||||
|
||||
orchestrator:
|
||||
poll_interval_seconds: 5
|
||||
self_check_timeout_seconds: 60
|
||||
max_self_check_retries: 3
|
||||
checking_window_seconds: 120
|
||||
max_retries: 3
|
||||
lease_ttl_seconds: 180
|
||||
heartbeat_timeout_seconds: 30
|
||||
# Pause (seconds) between FIP association and the start of self-check —
|
||||
# gives the OpenStack data plane time to start forwarding traffic
|
||||
# through the newly attached floating IP. 0 = no pause (default).
|
||||
# This is only the one-time seed value used the first time control-api
|
||||
# starts against an empty database; after that it's managed at runtime
|
||||
# via PUT /api/v1/admin/config/orchestrator (or the dashboard's
|
||||
# /settings page) and this field is ignored. Must satisfy
|
||||
# fip_settle_seconds + self_check_timeout_seconds < lease_ttl_seconds.
|
||||
fip_settle_seconds: 30
|
||||
|
||||
aggregation:
|
||||
missing_counts_as_fail: true
|
||||
|
||||
# Validators are VMs in the service project; os_port_id is the Neutron port
|
||||
# ID of each validator's primary NIC, used when associating a floating IP.
|
||||
validators:
|
||||
|
||||
# Inbound (prober) checks are OPTIONAL: list here only the external sites
|
||||
# you actually run a `prober` on — index is any integer >= 1, no cap on
|
||||
# how many slots you configure. Leave this list empty to disable inbound
|
||||
# checks entirely — the overall result is then based on egress checks
|
||||
# alone, and aggregation doesn't wait on any prober. A partial list (e.g.
|
||||
# just index 1) only waits on that one site.
|
||||
sites:
|
||||
|
||||
# Outbound/egress check types the validator-agent runs, and which target
|
||||
# group (below) each runs against.
|
||||
check_types:
|
||||
- name: "https"
|
||||
enabled: true
|
||||
targets: ["default-targets"]
|
||||
- name: "icmp"
|
||||
enabled: true
|
||||
targets: ["default-targets"]
|
||||
|
||||
targets:
|
||||
default-targets:
|
||||
- "https://hub.docker.com"
|
||||
- "https://github.com"
|
||||
- "https://packages.ubuntu.com"
|
||||
|
||||
# Inbound checks the 3 external-site probers run directly against each
|
||||
# validator's currently-assigned floating IP. Like validators/sites/targets/
|
||||
# check_types above, this is only a bootstrap seed for a fresh, empty
|
||||
# database; after that it's managed at runtime via PUT
|
||||
# /api/v1/admin/config/inbound-checks (or the dashboard's /settings page)
|
||||
# and this field is ignored.
|
||||
inbound_checks:
|
||||
ports: [22]
|
||||
icmp: true
|
||||
|
||||
# The pool of public IPv4 addresses to validate, in the order they'll be
|
||||
# processed (ip_queue.sequence). Every address here is checked through to
|
||||
# the end of the list.
|
||||
ip_addresses:
|
||||
@@ -1,18 +1,3 @@
|
||||
# Простой (без profiles/override/prod) docker-compose для сервера с ролями
|
||||
# control-api + admin-dashboard + prober. Реальный OpenStack (mode: real) —
|
||||
# validator-agent сюда не входит, он работает отдельно на реальных
|
||||
# ВМ-валидаторах в облаке и обращается к control-api по адресу этого хоста.
|
||||
#
|
||||
# Запуск:
|
||||
# cp .env.example .env # заполнить реальными OS_*-креденшлами и PROBER_SITE_ID
|
||||
# # поправить путь к control-api.yaml ниже, если реальный файл лежит не в
|
||||
# # /etc/cloud-ip-validator/control-api.yaml
|
||||
# docker compose up -d --build
|
||||
# curl -s http://localhost:8080/healthz
|
||||
#
|
||||
# (из корня репозитория тот же стек можно поднять гибче, с profiles и
|
||||
# dev/prod-разделением — см. deploy/docker/docker-compose.yml)
|
||||
|
||||
name: cloud-ip-validator
|
||||
|
||||
networks:
|
||||
@@ -25,20 +10,15 @@ volumes:
|
||||
|
||||
services:
|
||||
control-api:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/docker/control-api/Dockerfile
|
||||
image: cloud-ip-validator-control-api
|
||||
image: civ-capi
|
||||
platform: linux/amd64
|
||||
restart: unless-stopped
|
||||
networks: [backend]
|
||||
ports:
|
||||
- "8080:8080"
|
||||
- "8081:8081"
|
||||
volumes:
|
||||
# Поправьте путь слева, если реальный control-api.yaml (mode: real,
|
||||
# с настоящими validators/sites/targets/ip_addresses) лежит не здесь.
|
||||
- /etc/cloud-ip-validator/control-api.yaml:/etc/cloud-ip-validator/control-api.yaml:ro
|
||||
- control-api-db:/var/lib/cloud-ip-validator
|
||||
- /opt/lvraid/claude/cloud_ip_validator/rxprod-compose/control-api.yaml:/etc/cloud-ip-validator/control-api.yaml:ro
|
||||
- /opt/lvraid/claude/cloud_ip_validator/rxprod-compose/capi-db:/var/lib/cloud-ip-validator
|
||||
environment:
|
||||
OS_AUTH_URL: "${OS_AUTH_URL}"
|
||||
OS_PROJECT_ID: "${OS_PROJECT_ID}"
|
||||
@@ -49,40 +29,34 @@ services:
|
||||
OS_USER_DOMAIN_NAME: "${OS_USER_DOMAIN_NAME:-}"
|
||||
OS_PASSWORD: "${OS_PASSWORD:-}"
|
||||
healthcheck:
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://127.0.0.1:8080/healthz"]
|
||||
test: ["CMD", "wget", "--quiet", "--tries=1", "--spider", "http://127.0.0.1:8081/healthz"]
|
||||
interval: 5s
|
||||
timeout: 3s
|
||||
retries: 10
|
||||
start_period: 5s
|
||||
|
||||
admin-dashboard:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/docker/admin-dashboard/Dockerfile
|
||||
image: cloud-ip-validator-admin-dashboard
|
||||
image: civ-adash
|
||||
platform: linux/amd64
|
||||
restart: unless-stopped
|
||||
networks: [backend]
|
||||
ports:
|
||||
- "8090:8090"
|
||||
environment:
|
||||
ADMIN_DASHBOARD_CONTROL_API_URL: http://control-api:8080
|
||||
ADMIN_DASHBOARD_CONTROL_API_URL: http://control-api:8081
|
||||
depends_on:
|
||||
control-api:
|
||||
condition: service_healthy
|
||||
|
||||
prober:
|
||||
build:
|
||||
context: ..
|
||||
dockerfile: deploy/docker/prober/Dockerfile
|
||||
image: cloud-ip-validator-prober
|
||||
image: civ-prober
|
||||
platform: linux/amd64
|
||||
restart: unless-stopped
|
||||
networks: [backend]
|
||||
cap_add: [NET_RAW]
|
||||
environment:
|
||||
PROBER_SITE_ID: "${PROBER_SITE_ID}"
|
||||
PROBER_CONTROL_API_URL: http://control-api:8080
|
||||
PROBER_CONTROL_API_URL: http://control-api:8081
|
||||
depends_on:
|
||||
control-api:
|
||||
condition: service_healthy
|
||||
File renamed without changes.
@@ -0,0 +1,18 @@
|
||||
server:
|
||||
listen_addr: ":8090"
|
||||
|
||||
control_api:
|
||||
base_url: "http://control-api.internal:8080"
|
||||
timeout_seconds: 10
|
||||
|
||||
# Настройки сводки на странице "Обзор" — см. docs/DASHBOARD.md. Оба поля
|
||||
# влияют только на то, как дашборд группирует уже существующие данные
|
||||
# control-api (GET /admin/status, GET /admin/ips); никакого нового
|
||||
# состояния control-api не заводит.
|
||||
overview:
|
||||
# Сколько последних завершённых (done/failed) адресов показывать в
|
||||
# сводке "последняя завершённая проверка" и учитывать в разбивке
|
||||
# pass/partial/fail/cancelled.
|
||||
last_completed_count: 20
|
||||
# Как часто браузер опрашивает /overview/fragment для live-обновления.
|
||||
poll_interval_seconds: 5
|
||||
@@ -0,0 +1,118 @@
|
||||
# Control API configuration.
|
||||
#
|
||||
# OpenStack credentials are never set here — only the *names* of the
|
||||
# environment variables to read them from. The actual values must be
|
||||
# supplied by the process environment (see deploy/systemd/control-api.service
|
||||
# and its EnvironmentFile=).
|
||||
|
||||
server:
|
||||
listen_addr: ":8080"
|
||||
|
||||
database:
|
||||
path: "/var/lib/cloud-ip-validator/control-api.db"
|
||||
|
||||
openstack:
|
||||
mode: "real" # "mock" | "real" — mock uses an in-memory
|
||||
# OpenStack stand-in for local dev/testing
|
||||
auth_method: "token" # "token" (default) | "password" — see below
|
||||
|
||||
auth_url_env: "OS_AUTH_URL"
|
||||
project_id_env: "OS_PROJECT_ID"
|
||||
region_env: "OS_REGION_NAME"
|
||||
interface_env: "OS_INTERFACE" # optional; empty env value defaults to "public"
|
||||
|
||||
# auth_method: "token" — an admin supplies an already project-scoped
|
||||
# token directly; it's used as-is for every call, never exchanged for a
|
||||
# new one. Simplest option, but it can't renew itself: when the token
|
||||
# expires, control-api starts failing OpenStack calls until the operator
|
||||
# reissues OS_TOKEN and restarts the process.
|
||||
token_env: "OS_TOKEN"
|
||||
|
||||
# auth_method: "password" — the client authenticates with a normal
|
||||
# Keystone username/password and automatically re-authenticates
|
||||
# (mints a fresh token) whenever the current one is rejected, for as
|
||||
# long as the process runs. Trade-off: a long-lived password credential
|
||||
# sits in the environment file instead of a token.
|
||||
username_env: "OS_USERNAME"
|
||||
user_domain_name_env: "OS_USER_DOMAIN_NAME"
|
||||
password_env: "OS_PASSWORD"
|
||||
|
||||
orchestrator:
|
||||
poll_interval_seconds: 5
|
||||
self_check_timeout_seconds: 60
|
||||
max_self_check_retries: 3
|
||||
checking_window_seconds: 120
|
||||
max_retries: 3
|
||||
lease_ttl_seconds: 180
|
||||
heartbeat_timeout_seconds: 30
|
||||
# Pause (seconds) between FIP association and the start of self-check —
|
||||
# gives the OpenStack data plane time to start forwarding traffic
|
||||
# through the newly attached floating IP. 0 = no pause (default).
|
||||
# This is only the one-time seed value used the first time control-api
|
||||
# starts against an empty database; after that it's managed at runtime
|
||||
# via PUT /api/v1/admin/config/orchestrator (or the dashboard's
|
||||
# /settings page) and this field is ignored. Must satisfy
|
||||
# fip_settle_seconds + self_check_timeout_seconds < lease_ttl_seconds.
|
||||
fip_settle_seconds: 0
|
||||
|
||||
aggregation:
|
||||
missing_counts_as_fail: true
|
||||
|
||||
# Validators are VMs in the service project; os_port_id is the Neutron port
|
||||
# ID of each validator's primary NIC, used when associating a floating IP.
|
||||
validators:
|
||||
- validator_id: "validator_01"
|
||||
os_port_id: "REPLACE_WITH_NEUTRON_PORT_ID_1"
|
||||
- validator_id: "validator_02"
|
||||
os_port_id: "REPLACE_WITH_NEUTRON_PORT_ID_2"
|
||||
|
||||
# Inbound (prober) checks are OPTIONAL: list here only the external sites
|
||||
# you actually run a `prober` on — index is any integer >= 1, no cap on
|
||||
# how many slots you configure. Leave this list empty to disable inbound
|
||||
# checks entirely — the overall result is then based on egress checks
|
||||
# alone, and aggregation doesn't wait on any prober. A partial list (e.g.
|
||||
# just index 1) only waits on that one site.
|
||||
sites:
|
||||
- site_id: "site-1"
|
||||
index: 1
|
||||
- site_id: "site-2"
|
||||
index: 2
|
||||
- site_id: "site-3"
|
||||
index: 3
|
||||
|
||||
# Outbound/egress check types the validator-agent runs, and which target
|
||||
# group (below) each runs against.
|
||||
check_types:
|
||||
- name: "https"
|
||||
enabled: true
|
||||
targets: ["default-targets"]
|
||||
- name: "icmp"
|
||||
enabled: true
|
||||
targets: ["default-targets"]
|
||||
- name: "ssh"
|
||||
enabled: false
|
||||
targets: []
|
||||
|
||||
targets:
|
||||
default-targets:
|
||||
- "https://hub.docker.com"
|
||||
- "https://github.com"
|
||||
- "https://packages.ubuntu.com"
|
||||
|
||||
# Inbound checks the 3 external-site probers run directly against each
|
||||
# validator's currently-assigned floating IP. Like validators/sites/targets/
|
||||
# check_types above, this is only a bootstrap seed for a fresh, empty
|
||||
# database; after that it's managed at runtime via PUT
|
||||
# /api/v1/admin/config/inbound-checks (or the dashboard's /settings page)
|
||||
# and this field is ignored.
|
||||
inbound_checks:
|
||||
ports: [22, 80, 443, 8080]
|
||||
icmp: true
|
||||
|
||||
# The pool of public IPv4 addresses to validate, in the order they'll be
|
||||
# processed (ip_queue.sequence). Every address here is checked through to
|
||||
# the end of the list.
|
||||
ip_addresses:
|
||||
- "203.0.113.10"
|
||||
- "203.0.113.11"
|
||||
- "203.0.113.12"
|
||||
@@ -0,0 +1,11 @@
|
||||
# Prober configuration. Runs on one of the 3 external test sites. site_id
|
||||
# must match one of the control-api config's `sites[].site_id`.
|
||||
|
||||
site_id: "site-1"
|
||||
control_api_url: "http://control-api.internal:8080"
|
||||
poll_interval_seconds: 5
|
||||
|
||||
checks:
|
||||
tcp_timeout_seconds: 5
|
||||
icmp_timeout_seconds: 5
|
||||
icmp_count: 3
|
||||
@@ -0,0 +1,28 @@
|
||||
# Validator-agent configuration. Runs on each validator VM. validator_id
|
||||
# must match one of the control-api config's `validators[].validator_id`.
|
||||
|
||||
validator_id: "validator_01"
|
||||
control_api_url: "http://control-api.internal:8080"
|
||||
poll_interval_seconds: 5
|
||||
|
||||
self_check:
|
||||
timeout_seconds: 10
|
||||
# Must be a resource genuinely outside the cloud project — OpenStack only
|
||||
# applies floating-IP SNAT to traffic leaving via the external network,
|
||||
# so anything reachable over the project's internal network (including
|
||||
# control-api itself, if it's on the same internal network) would report
|
||||
# this validator's private address instead, regardless of whether the
|
||||
# floating IP is correctly attached. Tried in order; falls through to the
|
||||
# next URL only on error/timeout, never on a genuine mismatch. Defaults
|
||||
# to these two public services if omitted.
|
||||
ip_echo_urls:
|
||||
- "https://api.ipify.org"
|
||||
- "https://ifconfig.me/ip"
|
||||
|
||||
checks:
|
||||
https_timeout_seconds: 10
|
||||
icmp_timeout_seconds: 5
|
||||
icmp_count: 3
|
||||
ssh:
|
||||
enabled: false
|
||||
timeout_seconds: 5
|
||||
Reference in new issue
Block a user