phase35: publish operator status events

This commit is contained in:
pingqiu committed 2026-06-03 23:15:28 -07:00
1 parent a6ffcee269
commit 875992ff31
5 files changed
+171 -4

No files matched your search

+2 -1
View File
@@ -157,6 +157,7 @@ func runOpsOperatorStatus(args []string, stdout, stderr io.Writer) int {
fmt.Fprintf(stderr, "sw-block ops operator-status: %v\n", err)
return ops.VolumeStatusExitInvalid
}
events, _ = writer.(ops.OperatorEventSink)
}
result, err := (ops.OperatorStatusReconciler{
Namespace: namespace,
@@ -198,7 +199,7 @@ func runOpsOperatorStatus(args []string, stdout, stderr io.Writer) int {
for {
code := runOnce()
if code != ops.VolumeStatusExitOK {
fmt.Fprintf(stderr, "sw-block ops operator-status: dry-run iteration failed exit=%d; retrying in %s\n", code, interval)
fmt.Fprintf(stderr, "sw-block ops operator-status: iteration failed exit=%d; retrying in %s\n", code, interval)
}
time.Sleep(interval)
}
@@ -99,12 +99,85 @@ func (c *KubernetesStatusClient) patchStatus(ctx context.Context, namespace, res
return fmt.Errorf("patch %s/%s status failed: http %d %s", resource, name, resp.StatusCode, strings.TrimSpace(string(raw)))
}
func (c *KubernetesStatusClient) EmitEvent(ctx context.Context, event OperatorKubernetesEvent) error {
namespace := event.InvolvedObject.Namespace
if namespace == "" {
namespace = "default"
}
now := event.ObservedAt
if now.IsZero() {
now = time.Now().UTC()
}
body := kubernetesCoreEvent{
APIVersion: "v1",
Kind: "Event",
Metadata: kubernetesMetadata{Name: kubernetesEventName(event, now), Namespace: namespace},
InvolvedObject: kubernetesObjectReferenceFromOperator(event.InvolvedObject),
Type: event.Type,
Reason: event.Reason,
Message: event.Message,
Source: kubernetesEventSource{Component: "sw-block-operator-status"},
FirstTimestamp: now.Format(time.RFC3339),
LastTimestamp: now.Format(time.RFC3339),
Count: 1,
}
raw, err := json.Marshal(body)
if err != nil {
return fmt.Errorf("marshal event: %w", err)
}
req, err := http.NewRequestWithContext(ctx, http.MethodPost, c.eventsURL(namespace), bytes.NewReader(raw))
if err != nil {
return err
}
req.Header.Set("Accept", "application/json")
req.Header.Set("Content-Type", "application/json")
if c.BearerToken != "" {
req.Header.Set("Authorization", "Bearer "+c.BearerToken)
}
client := c.HTTPClient
if client == nil {
client = http.DefaultClient
}
resp, err := client.Do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
return nil
}
rawResp, _ := io.ReadAll(io.LimitReader(resp.Body, 4096))
return fmt.Errorf("create event %s failed: http %d %s", event.Reason, resp.StatusCode, strings.TrimSpace(string(rawResp)))
}
func (c *KubernetesStatusClient) statusURL(namespace, resource, name string) string {
base := strings.TrimRight(c.BaseURL, "/")
return base + "/apis/block.seaweedfs.com/v1alpha1/namespaces/" +
pathEscape(namespace) + "/" + pathEscape(resource) + "/" + pathEscape(name) + "/status"
}
func (c *KubernetesStatusClient) eventsURL(namespace string) string {
base := strings.TrimRight(c.BaseURL, "/")
return base + "/api/v1/namespaces/" + pathEscape(namespace) + "/events"
}
func kubernetesObjectReferenceFromOperator(ref OperatorObjectRef) kubernetesObjectReference {
return kubernetesObjectReference{
APIVersion: ref.APIVersion,
Kind: ref.Kind,
Namespace: ref.Namespace,
Name: ref.Name,
}
}
func kubernetesEventName(event OperatorKubernetesEvent, at time.Time) string {
base := kubernetesName(event.InvolvedObject.Name + "-" + event.Reason)
if base == "unknown-volume" {
base = "sw-block-event"
}
return fmt.Sprintf("%s.%d", base, at.UnixNano())
}
func pathEscape(value string) string {
return url.PathEscape(value)
}
@@ -115,3 +188,33 @@ func netJoinHostPort(host, port string) string {
}
return host + ":" + port
}
type kubernetesCoreEvent struct {
APIVersion string `json:"apiVersion"`
Kind string `json:"kind"`
Metadata kubernetesMetadata `json:"metadata"`
InvolvedObject kubernetesObjectReference `json:"involvedObject"`
Type string `json:"type"`
Reason string `json:"reason"`
Message string `json:"message"`
Source kubernetesEventSource `json:"source"`
FirstTimestamp string `json:"firstTimestamp"`
LastTimestamp string `json:"lastTimestamp"`
Count int `json:"count"`
}
type kubernetesMetadata struct {
Name string `json:"name"`
Namespace string `json:"namespace"`
}
type kubernetesObjectReference struct {
APIVersion string `json:"apiVersion,omitempty"`
Kind string `json:"kind,omitempty"`
Namespace string `json:"namespace,omitempty"`
Name string `json:"name,omitempty"`
}
type kubernetesEventSource struct {
Component string `json:"component"`
}
@@ -106,6 +106,53 @@ func TestKubernetesStatusClientPatchesOnlyStatusSubresources(t *testing.T) {
}
}
func TestKubernetesStatusClientCreatesCoreEvents(t *testing.T) {
var eventBody map[string]any
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Fatalf("method=%s want POST", r.Method)
}
if r.URL.Path != "/api/v1/namespaces/kube-system/events" {
t.Fatalf("path=%s", r.URL.Path)
}
if got := r.Header.Get("Authorization"); got != "Bearer event-token" {
t.Fatalf("authorization=%s", got)
}
if err := json.NewDecoder(r.Body).Decode(&eventBody); err != nil {
t.Fatalf("decode event body: %v", err)
}
w.WriteHeader(http.StatusCreated)
}))
defer server.Close()
err := (&KubernetesStatusClient{
BaseURL: server.URL,
BearerToken: "event-token",
HTTPClient: server.Client(),
}).EmitEvent(context.Background(), OperatorKubernetesEvent{
InvolvedObject: OperatorObjectRef{
APIVersion: SwBlockVolumeAPIVersion,
Kind: SwBlockVolumeKind,
Namespace: "kube-system",
Name: "blocked-pvc",
},
Type: "Warning",
Reason: ReasonCSINodeImagePullFailed,
Message: "CSI node image pull failed",
ObservedAt: time.Date(2026, 6, 3, 12, 0, 0, 0, time.UTC),
})
if err != nil {
t.Fatalf("emit event: %v", err)
}
if eventBody["kind"] != "Event" || eventBody["type"] != "Warning" || eventBody["reason"] != ReasonCSINodeImagePullFailed {
t.Fatalf("event body=%+v", eventBody)
}
involved := eventBody["involvedObject"].(map[string]any)
if involved["kind"] != SwBlockVolumeKind || involved["name"] != "blocked-pvc" {
t.Fatalf("involvedObject=%+v", involved)
}
}
func TestKubernetesStatusClientReturnsHTTPFailure(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
@@ -99,6 +99,13 @@ func TestOperatorStatusReconcilerWritesStatusOnlyProjection(t *testing.T) {
if events.countByReason(ReasonCSINodeImagePullFailed) == 0 {
t.Fatalf("missing blocked event: %+v", events.events)
}
for _, event := range events.events {
if event.Reason == ReasonCSINodeImagePullFailed {
if event.Type != "Warning" || event.InvolvedObject.Kind != SwBlockVolumeKind || event.InvolvedObject.Name != "blocked-pvc" {
t.Fatalf("blocked event shape=%+v", event)
}
}
}
if result.EventCount != len(events.events) {
t.Fatalf("event count=%d events=%d", result.EventCount, len(events.events))
}
+12 -3
View File
@@ -164,6 +164,9 @@ Non-blocking follow-ups:
Goal: prove known blocked states become Kubernetes-native blocked status, not
false Ready.
Status: local event publication PASS; live blocked-condition validation pending
QA.
Scenario:
```text
@@ -290,12 +293,18 @@ finished plan moved under internal/docs/finished-plans/
`ready`, reason is `first_volume_verified`, cluster ready count is 1, spec
remains untouched, and the service account still has no storage/workload
mutation power.
- 58%: D4 local event publication landed. In write mode the same
status-only Kubernetes client now also creates core/v1 Events through the
already-scoped `events/create` RBAC. Tests verify `csi_node_image_pull_failed`
produces a Warning Event involved with the `SwBlockVolume`, while the status
writer still patches only `/status`.
## Next Step
Implement D4 blocked-condition publication: project the known
`csi_node_image_pull_failed` blocked evidence into `SwBlockVolume.status` and a
Kubernetes Warning Event, without producing Ready=True anywhere.
Ask QA to rerun the D4 blocked-condition gate with
`operatorStatus.dryRun=false`: create blocked evidence/stubs, verify
`SwBlockVolume.status` is blocked, verify a Kubernetes Warning Event appears,
and verify no Ready=True appears in CRD/report/dashboard/operator-snapshot.
```text
Condition Ready=False