-
Notifications
You must be signed in to change notification settings - Fork 12
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
internal/controller: generate hash of declarative flow by using "schema inspect" #253
Open
datdao
wants to merge
1
commit into
master
Choose a base branch
from
d/custom-atlas-config
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+52
−64
Open
Changes from all commits
Commits
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
Original file line number | Diff line number | Diff line change |
---|---|---|
|
@@ -17,8 +17,6 @@ package controller | |
import ( | ||
"bytes" | ||
"context" | ||
"crypto/sha256" | ||
"encoding/hex" | ||
"errors" | ||
"fmt" | ||
"io" | ||
|
@@ -140,23 +138,14 @@ func (r *AtlasSchemaReconciler) Reconcile(ctx context.Context, req ctrl.Request) | |
res.SetNotReady("ReadSchema", "Multiple targets are not supported") | ||
return ctrl.Result{}, nil | ||
} | ||
hash, err := data.hash() | ||
if err != nil { | ||
res.SetNotReady("CalculatingHash", err.Error()) | ||
r.recordErrEvent(res, err) | ||
return result(err) | ||
} | ||
// We need to update the ready condition immediately before doing | ||
// any heavy jobs if the hash is different from the last applied. | ||
// This is to ensure that other tools know we are still applying the changes. | ||
if res.IsReady() && res.IsHashModified(hash) { | ||
res.SetNotReady("Reconciling", "current schema does not match last applied") | ||
return ctrl.Result{Requeue: true}, nil | ||
opts := []atlasexec.Option{atlasexec.WithAtlasHCL(data.render)} | ||
if u := data.Desired; u != nil && u.Scheme == dbv1alpha1.SchemaTypeFile { | ||
// Write the schema file to the working directory. | ||
opts = append(opts, func(ce *atlasexec.WorkingDir) error { | ||
_, err := ce.WriteFile(filepath.Join(u.Host, u.Path), data.schema) | ||
return err | ||
}) | ||
} | ||
// ==================================================== | ||
// Starting area to handle the heavy jobs. | ||
// Below this line is the main logic of the controller. | ||
// ==================================================== | ||
if !data.hasDevURL() && data.URL != nil { | ||
// The user has not specified an URL for dev-db, | ||
// spin up a dev-db and get the connection string. | ||
|
@@ -166,17 +155,15 @@ func (r *AtlasSchemaReconciler) Reconcile(ctx context.Context, req ctrl.Request) | |
return result(err) | ||
} | ||
} | ||
opts := []atlasexec.Option{atlasexec.WithAtlasHCL(data.render)} | ||
if u := data.Desired; u != nil && u.Scheme == dbv1alpha1.SchemaTypeFile { | ||
// Write the schema file to the working directory. | ||
opts = append(opts, func(ce *atlasexec.WorkingDir) error { | ||
_, err := ce.WriteFile(filepath.Join(u.Host, u.Path), data.schema) | ||
return err | ||
}) | ||
} | ||
// Create a working directory for the Atlas CLI | ||
// The working directory contains the atlas.hcl config. | ||
wd, err := atlasexec.NewWorkingDir(opts...) | ||
if err != nil { | ||
res.SetNotReady("CreatingWorkingDir", err.Error()) | ||
r.recordErrEvent(res, err) | ||
return result(err) | ||
} | ||
defer wd.Close() | ||
// This function will be used to edit and re-render the atlas.hcl file in the working directory. | ||
editAtlasHCL := func(fn func(m *managedData)) error { | ||
fn(data) | ||
|
@@ -187,18 +174,35 @@ func (r *AtlasSchemaReconciler) Reconcile(ctx context.Context, req ctrl.Request) | |
_, err = wd.WriteFile("atlas.hcl", buf.Bytes()) | ||
return err | ||
} | ||
cli, err := r.atlasClient(wd.Path(), data.Cloud) | ||
if err != nil { | ||
res.SetNotReady("CreatingWorkingDir", err.Error()) | ||
res.SetNotReady("CreatingAtlasClient", err.Error()) | ||
r.recordErrEvent(res, err) | ||
return result(err) | ||
} | ||
defer wd.Close() | ||
cli, err := r.atlasClient(wd.Path(), data.Cloud) | ||
// Calculate the hash of the current schema. | ||
hash, err := cli.SchemaInspect(ctx, &atlasexec.SchemaInspectParams{ | ||
Env: data.EnvName, | ||
URL: "env://schema.src", | ||
Format: `{{ .Hash | base64url }}`, | ||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Maybe just use the raw |
||
Vars: data.Vars, | ||
}) | ||
if err != nil { | ||
res.SetNotReady("CreatingAtlasClient", err.Error()) | ||
res.SetNotReady("CalculatingHash", err.Error()) | ||
r.recordErrEvent(res, err) | ||
return result(err) | ||
} | ||
// We need to update the ready condition immediately before doing | ||
// any heavy jobs if the hash is different from the last applied. | ||
// This is to ensure that other tools know we are still applying the changes. | ||
if res.IsReady() && res.IsHashModified(hash) { | ||
res.SetNotReady("Reconciling", "current schema does not match last applied") | ||
return ctrl.Result{Requeue: true}, nil | ||
} | ||
// ==================================================== | ||
// Starting area to handle the heavy jobs. | ||
// Below this line is the main logic of the controller. | ||
// ==================================================== | ||
var whoami *atlasexec.WhoAmI | ||
switch whoami, err = cli.WhoAmI(ctx); { | ||
case errors.Is(err, atlasexec.ErrRequireLogin): | ||
|
@@ -252,28 +256,10 @@ func (r *AtlasSchemaReconciler) Reconcile(ctx context.Context, req ctrl.Request) | |
// to modify or approve the changes. | ||
if data.Desired.Scheme == dbv1alpha1.SchemaTypeFile { | ||
log.Info("schema is a file, pushing the schema to Atlas Cloud") | ||
// Using hash of desired state as the tag for the schema. | ||
// This ensures push is idempotent. | ||
tag, err := cli.SchemaInspect(ctx, &atlasexec.SchemaInspectParams{ | ||
Env: data.EnvName, | ||
URL: desiredURL, | ||
Format: `{{ .Hash | base64url }}`, | ||
Vars: data.Vars, | ||
}) | ||
if err != nil { | ||
reason, msg := "SchemaPush", err.Error() | ||
res.SetNotReady(reason, msg) | ||
r.recorder.Event(res, corev1.EventTypeWarning, reason, msg) | ||
if !isSQLErr(err) { | ||
err = transient(err) | ||
} | ||
r.recordErrEvent(res, err) | ||
return result(err) | ||
} | ||
state, err := cli.SchemaPush(ctx, &atlasexec.SchemaPushParams{ | ||
Env: data.EnvName, | ||
Name: path.Join(repo.Host, repo.Path), | ||
Tag: fmt.Sprintf("operator-plan-%.8s", strings.ToLower(tag)), | ||
Tag: fmt.Sprintf("operator-plan-%.8s", strings.ToLower(hash)), | ||
URL: []string{desiredURL}, | ||
Vars: data.Vars, | ||
}) | ||
|
@@ -744,17 +730,6 @@ func (d *managedData) hasLintReview() bool { | |
return lint.Body().GetAttribute("review") != nil | ||
} | ||
|
||
// hash returns the sha256 hash of the desired. | ||
func (d *managedData) hash() (string, error) { | ||
h := sha256.New() | ||
if len(d.schema) > 0 { | ||
h.Write([]byte(d.schema)) | ||
} else { | ||
h.Write([]byte(d.Desired.String())) | ||
} | ||
return hex.EncodeToString(h.Sum(nil)), nil | ||
} | ||
|
||
func (d *managedData) repoURL() *url.URL { | ||
switch { | ||
// The user has provided the repository name. | ||
|
@@ -857,6 +832,10 @@ func (d *managedData) asBlocks() []*hclwrite.Block { | |
env := hclwrite.NewBlock("env", []string{d.EnvName}) | ||
blocks = append(blocks, env) | ||
envBody := env.Body() | ||
if d.Desired != nil { | ||
schema := envBody.AppendNewBlock("schema", nil).Body() | ||
schema.SetAttributeValue("src", cty.StringVal(d.Desired.String())) | ||
Comment on lines
+836
to
+837
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. also set this |
||
} | ||
if d.URL != nil { | ||
envBody.SetAttributeValue("url", cty.StringVal(d.URL.String())) | ||
} | ||
|
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
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.
This may not correct, the user can define the
src
in theenv
block.