-
Notifications
You must be signed in to change notification settings - Fork 21
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
Prepare delayed downscale #131
Merged
Merged
Changes from 9 commits
Commits
Show all changes
10 commits
Select commit
Hold shift + click to select a range
dc5b3f6
Support for delayed downscaling.
pstibrany 8924258
Cancel possible delayed downscale.
pstibrany 8228f7f
Fix panic if no response is received.
pstibrany 5529893
Add test.
pstibrany 93cc9ba
Simplify messages.
pstibrany dd342e3
Simplify code.
pstibrany c1213ac
Make sure to cancel delayed scaledown if replicas are not stopped aft…
pstibrany 4c90467
Add log message when downscale delay is reached.
pstibrany f269d10
Add unit tests for delayed downscale.
pstibrany e459026
Address review feedback.
pstibrany File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Large diffs are not rendered by default.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,252 @@ | ||
package controller | ||
|
||
import ( | ||
"context" | ||
"encoding/json" | ||
"errors" | ||
"fmt" | ||
"io" | ||
"net/http" | ||
"net/url" | ||
"sync" | ||
"time" | ||
|
||
"github.com/go-kit/log" | ||
"github.com/go-kit/log/level" | ||
"github.com/prometheus/common/model" | ||
"golang.org/x/sync/errgroup" | ||
v1 "k8s.io/api/apps/v1" | ||
|
||
"github.com/grafana/rollout-operator/pkg/config" | ||
) | ||
|
||
func cancelDelayedDownscaleIfConfigured(ctx context.Context, logger log.Logger, sts *v1.StatefulSet, httpClient httpClient, replicas int32) { | ||
delay, prepareURL, err := parseDelayedDownscaleAnnotations(sts.GetAnnotations()) | ||
if delay == 0 || prepareURL == nil { | ||
return | ||
} | ||
|
||
if err != nil { | ||
level.Warn(logger).Log("msg", "failed to cancel possible downscale due to error", "name", sts.GetName(), "err", err) | ||
return | ||
} | ||
|
||
endpoints := createEndpoints(sts.Namespace, sts.GetName(), 0, int(replicas), prepareURL) | ||
|
||
callCancelDelayedDownscale(ctx, logger, httpClient, endpoints) | ||
} | ||
|
||
func checkScalingDelay(ctx context.Context, logger log.Logger, sts *v1.StatefulSet, httpClient httpClient, currentReplicas, desiredReplicas int32) error { | ||
if currentReplicas == desiredReplicas { | ||
// should not happen | ||
return nil | ||
} | ||
|
||
delay, prepareURL, err := parseDelayedDownscaleAnnotations(sts.GetAnnotations()) | ||
if delay == 0 || prepareURL == nil || err != nil { | ||
return err | ||
} | ||
|
||
if desiredReplicas > currentReplicas { | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
callCancelDelayedDownscale(ctx, logger, httpClient, createEndpoints(sts.Namespace, sts.GetName(), 0, int(currentReplicas), prepareURL)) | ||
// Proceed even if calling cancel of delayed downscale fails. We call cancellation repeatedly, so it will happen during next reconcile. | ||
return nil | ||
} | ||
|
||
{ | ||
// Replicas in [0, desired) interval should cancel any delayed downscale, if they have any. | ||
cancelEndpoints := createEndpoints(sts.Namespace, sts.GetName(), 0, int(desiredReplicas), prepareURL) | ||
callCancelDelayedDownscale(ctx, logger, httpClient, cancelEndpoints) | ||
} | ||
|
||
// Replicas in [desired, current) interval are going to be stopped. | ||
downscaleEndpoints := createEndpoints(sts.Namespace, sts.GetName(), int(desiredReplicas), int(currentReplicas), prepareURL) | ||
maxPrepareTime, err := callPrepareDownscaleAndReturnMaxPrepareTimestamp(ctx, logger, httpClient, downscaleEndpoints) | ||
if err != nil { | ||
return fmt.Errorf("failed prepare pods for delayed downscale: %v", err) | ||
} | ||
|
||
elapsedSinceMaxTime := time.Since(maxPrepareTime) | ||
if elapsedSinceMaxTime < delay { | ||
return fmt.Errorf("configured downscale delay %v has not been reached for all pods. elapsed time: %v", delay, elapsedSinceMaxTime) | ||
} | ||
|
||
// We can proceed with downscale! | ||
level.Info(logger).Log("msg", "downscale delay has been reached on all downscaled pods, proceeding with downscale", "name", sts.GetName(), "delay", delay, "elapsed", elapsedSinceMaxTime) | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return nil | ||
} | ||
|
||
func parseDelayedDownscaleAnnotations(annotations map[string]string) (time.Duration, *url.URL, error) { | ||
delayStr := annotations[config.RolloutDelayedDownscaleAnnotationKey] | ||
urlStr := annotations[config.RolloutDelayedDownscalePrepareUrlAnnotationKey] | ||
|
||
if delayStr == "" || urlStr == "" { | ||
return 0, nil, nil | ||
} | ||
|
||
d, err := model.ParseDuration(delayStr) | ||
if err != nil { | ||
return 0, nil, fmt.Errorf("failed to parse %s annotation value as duration: %v", config.RolloutDelayedDownscaleAnnotationKey, err) | ||
} | ||
if d < 0 { | ||
return 0, nil, fmt.Errorf("negative value of %s annotation: %v", config.RolloutDelayedDownscaleAnnotationKey, delayStr) | ||
} | ||
|
||
delay := time.Duration(d) | ||
|
||
u, err := url.Parse(urlStr) | ||
if err != nil { | ||
return 0, nil, fmt.Errorf("failed to parse %s annotation value as URL: %v", config.RolloutDelayedDownscalePrepareUrlAnnotationKey, err) | ||
} | ||
|
||
return delay, u, nil | ||
} | ||
|
||
type endpoint struct { | ||
namespace string | ||
podName string | ||
url url.URL | ||
index int | ||
} | ||
|
||
// Create prepare-downscale endpoints for pods with index in [from, to) range. | ||
func createEndpoints(namespace, serviceName string, from, to int, url *url.URL) []endpoint { | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
eps := make([]endpoint, 0, to-from) | ||
|
||
// The DNS entry for a pod of a stateful set is | ||
// ingester-zone-a-0.$(servicename).$(namespace).svc.cluster.local | ||
// The service in this case is ingester-zone-a as well. | ||
// https://kubernetes.io/docs/concepts/workloads/controllers/statefulset/#stable-network-id | ||
|
||
for index := from; index < to; index++ { | ||
ep := endpoint{ | ||
namespace: namespace, | ||
podName: fmt.Sprintf("%v-%v", serviceName, index), | ||
index: index, | ||
} | ||
|
||
ep.url = *url | ||
ep.url.Host = fmt.Sprintf("%s.%v.%v.svc.cluster.local", ep.podName, serviceName, ep.namespace) | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
|
||
eps = append(eps, ep) | ||
} | ||
|
||
return eps | ||
} | ||
|
||
func callPrepareDownscaleAndReturnMaxPrepareTimestamp(ctx context.Context, logger log.Logger, client httpClient, endpoints []endpoint) (time.Time, error) { | ||
if len(endpoints) == 0 { | ||
return time.Now(), nil | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
var ( | ||
maxTimeMu sync.Mutex | ||
maxTime time.Time | ||
) | ||
|
||
type expectedResponse struct { | ||
Timestamp int64 `json:"timestamp"` | ||
} | ||
|
||
g, ctx := errgroup.WithContext(ctx) | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for ix := range endpoints { | ||
ep := endpoints[ix] | ||
g.Go(func() error { | ||
target := ep.url.String() | ||
|
||
epLogger := log.With(logger, "pod", ep.podName, "url", target) | ||
|
||
// POST -- prepare for delayed downscale, if not yet prepared, and return timestamp when prepare was called. | ||
req, err := http.NewRequestWithContext(ctx, http.MethodPost, target, nil) | ||
if err != nil { | ||
level.Error(epLogger).Log("msg", "error creating HTTP POST request to endpoint", "err", err) | ||
return err | ||
} | ||
|
||
resp, err := client.Do(req) | ||
if err != nil { | ||
level.Error(epLogger).Log("error sending HTTP POST request to endpoint", "err", err) | ||
return err | ||
} | ||
|
||
defer resp.Body.Close() | ||
|
||
body, readError := io.ReadAll(resp.Body) | ||
if readError != nil { | ||
level.Error(epLogger).Log("msg", "error reading response from HTTP POST request to endpoint", "err", err) | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return err | ||
} | ||
|
||
if resp.StatusCode/100 != 2 { | ||
err := errors.New("HTTP DELETE request returned non-2xx status code") | ||
level.Error(epLogger).Log("msg", "unexpected status code returned when calling DELETE on endpoint", "status", resp.StatusCode, "response_body", string(body)) | ||
return errors.Join(err, readError) | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
} | ||
|
||
r := expectedResponse{} | ||
if err := json.Unmarshal(body, &r); err != nil { | ||
level.Error(epLogger).Log("msg", "error decoding response from HTTP POST request to endpoint", "err", err) | ||
return err | ||
} | ||
|
||
if r.Timestamp == 0 { | ||
level.Error(epLogger).Log("msg", "invalid response from HTTP POST request to endpoint: no timestamp") | ||
return fmt.Errorf("no timestamp in response") | ||
} | ||
|
||
t := time.Unix(r.Timestamp, 0) | ||
|
||
maxTimeMu.Lock() | ||
if t.After(maxTime) { | ||
maxTime = t | ||
} | ||
maxTimeMu.Unlock() | ||
|
||
level.Debug(epLogger).Log("msg", "HTTP POST request to endpoint succeded", "timestamp", t.UTC().Format(time.RFC3339)) | ||
return nil | ||
}) | ||
} | ||
err := g.Wait() | ||
return maxTime, err | ||
} | ||
|
||
func callCancelDelayedDownscale(ctx context.Context, logger log.Logger, client httpClient, endpoints []endpoint) { | ||
if len(endpoints) == 0 { | ||
return | ||
} | ||
|
||
g, _ := errgroup.WithContext(ctx) | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
for ix := range endpoints { | ||
ep := endpoints[ix] | ||
g.Go(func() error { | ||
target := ep.url.String() | ||
|
||
epLogger := log.With(logger, "pod", ep.podName, "url", target) | ||
|
||
req, err := http.NewRequestWithContext(ctx, http.MethodDelete, target, nil) | ||
if err != nil { | ||
level.Error(epLogger).Log("msg", "error creating HTTP DELETE request to endpoint", "err", err) | ||
return err | ||
} | ||
|
||
resp, err := client.Do(req) | ||
if err != nil { | ||
level.Error(epLogger).Log("msg", "error sending HTTP DELETE request to endpoint", "err", err) | ||
return err | ||
} | ||
|
||
defer resp.Body.Close() | ||
|
||
if resp.StatusCode/100 != 2 { | ||
err := errors.New("HTTP DELETE request returned non-2xx status code") | ||
body, readError := io.ReadAll(resp.Body) | ||
level.Error(epLogger).Log("msg", "unexpected status code returned when calling DELETE on endpoint", "status", resp.StatusCode, "response_body", string(body)) | ||
return errors.Join(err, readError) | ||
} | ||
level.Debug(epLogger).Log("msg", "HTTP DELETE request to endpoint succeeded") | ||
return nil | ||
}) | ||
} | ||
// We ignore errors, since all errors are already logged, and callers don't need i | ||
pstibrany marked this conversation as resolved.
Show resolved
Hide resolved
|
||
_ = g.Wait() | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
We can end up in a situation where different zone statefulsets are scaled down at different times. When this happens, what's the impact on the INACTIVE partitions? We're going to lose some replicas for a partition which is still INACTIVE in the ring and potentially queried 🤔
Maybe the solution is to simply configure a scale down delay > than the ring lookback, so that when replicas being to scale down their partitions aren't queried anymore since "some time".
Makes sense?
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
For project sigyn I imagined that we would configure delayed-scaledown on zone-a, and then configure other zones to follow replicas from zone-a. That way only zone-a would control the state of partitions (marking them inactive, or deleting).
Yes, this was my plan too.