Skip to content

Commit

Permalink
CLOUDP-81282: support for Atlas Domain configuration (#64)
Browse files Browse the repository at this point in the history
  • Loading branch information
crew-helper authored Jan 27, 2021
1 parent 60e9775 commit 822a61a
Show file tree
Hide file tree
Showing 12 changed files with 79 additions and 35 deletions.
2 changes: 1 addition & 1 deletion .github/actions/deploy/entrypoint.sh
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ controller-gen crd:crdVersions=v1 rbac:roleName=manager-role webhook paths="./..
ns=mongodb-atlas-kubernetes-system
kubectl delete deployment mongodb-atlas-kubernetes-controller-manager -n "${ns}" || true # temporary
cd config/manager && kustomize edit set image controller="${INPUT_IMAGE_URL}"
cd - && kustomize build config/default | kubectl apply -f -
cd - && kustomize build config/dev | kubectl apply -f -

# Ensuring the Atlas credentials Secret
kubectl delete secrets my-atlas-key --ignore-not-found -n "${ns}"
Expand Down
1 change: 1 addition & 0 deletions config/default/manager_auth_proxy_patch.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ spec:
args:
- "--metrics-addr=127.0.0.1:8080"
- "--enable-leader-election"
- --atlas-domain=https://cloud.mongodb.com
7 changes: 7 additions & 0 deletions config/dev/kustomization.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@


resources:
- ../default

patchesStrategicMerge:
- manager_configuration.yaml
15 changes: 15 additions & 0 deletions config/dev/manager_configuration.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# This patch configures the container with production configuration values
apiVersion: apps/v1
kind: Deployment
metadata:
name: controller-manager
namespace: system
spec:
template:
spec:
containers:
- name: manager
args:
- --atlas-domain=https://cloud-qa.mongodb.com
- --metrics-addr=127.0.0.1:8080 # is there any way to reuse the properties that are set by /default overlay?
- --enable-leader-election
3 changes: 3 additions & 0 deletions config/manager/manager.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,9 @@ spec:
labels:
control-plane: controller-manager
spec:
securityContext:
runAsNonRoot: true
runAsUser: 2000
containers:
- command:
- /manager
Expand Down
45 changes: 30 additions & 15 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -47,13 +47,7 @@ func init() {
}

func main() {
var metricsAddr string
var enableLeaderElection bool
flag.StringVar(&metricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&enableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")
flag.Parse()
config := parseConfiguration()

// controller-runtime/pkg/log/zap is a wrapper over zap that implements logr
// logr looks quite limited in functionality so we better use Zap directly.
Expand All @@ -65,9 +59,9 @@ func main() {

mgr, err := ctrl.NewManager(ctrl.GetConfigOrDie(), ctrl.Options{
Scheme: scheme,
MetricsBindAddress: metricsAddr,
MetricsBindAddress: config.MetricsAddr,
Port: 9443,
LeaderElection: enableLeaderElection,
LeaderElection: config.EnableLeaderElection,
LeaderElectionID: "06d035fb.mongodb.com",
})
if err != nil {
Expand All @@ -76,18 +70,20 @@ func main() {
}

if err = (&atlascluster.AtlasClusterReconciler{
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasCluster").Sugar(),
Scheme: mgr.GetScheme(),
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasCluster").Sugar(),
Scheme: mgr.GetScheme(),
AtlasDomain: config.AtlasDomain,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "AtlasCluster")
os.Exit(1)
}

if err = (&atlasproject.AtlasProjectReconciler{
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasProject").Sugar(),
Scheme: mgr.GetScheme(),
Client: mgr.GetClient(),
Log: logger.Named("controllers").Named("AtlasProject").Sugar(),
Scheme: mgr.GetScheme(),
AtlasDomain: config.AtlasDomain,
}).SetupWithManager(mgr); err != nil {
setupLog.Error(err, "unable to create controller", "controller", "AtlasProject")
os.Exit(1)
Expand All @@ -100,3 +96,22 @@ func main() {
os.Exit(1)
}
}

type Config struct {
AtlasDomain string
EnableLeaderElection bool
MetricsAddr string
}

// ParseConfiguration fills the 'OperatorConfig' from the flags passed to the program
func parseConfiguration() Config {
config := Config{}
flag.StringVar(&config.AtlasDomain, "atlas-domain", "https://cloud.mongodb.com", "the Atlas URL domain name (no slash in the end).")
flag.StringVar(&config.MetricsAddr, "metrics-addr", ":8080", "The address the metric endpoint binds to.")
flag.BoolVar(&config.EnableLeaderElection, "enable-leader-election", false,
"Enable leader election for controller manager. "+
"Enabling this will ensure there is only one active controller manager.")

flag.Parse()
return config
}
5 changes: 2 additions & 3 deletions pkg/controller/atlas/client.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,16 +15,15 @@ var userAgent = fmt.Sprintf("%s/%s (%s;%s)", "MongoDBAtlasKubernetesOperator", "

// Client is the central place to create a client for Atlas using specified API keys and a server URL.
// Note, that the default HTTP transport is reused globally by Go so all caching, keep-alive etc will be in action.
func Client(connection Connection, log *zap.SugaredLogger) (*mongodbatlas.Client, error) {
func Client(atlasDomain string, connection Connection, log *zap.SugaredLogger) (*mongodbatlas.Client, error) {
withDigest := httputil.Digest(connection.PublicKey, connection.PrivateKey)
withLogging := httputil.LoggingTransport(log)

httpClient, err := httputil.DecorateClient(basicClient(), withDigest, withLogging)
if err != nil {
return nil, err
}
// TODO configuration for base URL (as a global Operator config?)
client, err := mongodbatlas.New(httpClient, mongodbatlas.SetBaseURL("https://cloud-qa.mongodb.com/api/atlas/v1.0/"))
client, err := mongodbatlas.New(httpClient, mongodbatlas.SetBaseURL(atlasDomain+"/api/atlas/v1.0/"))
if err != nil {
return nil, err
}
Expand Down
11 changes: 6 additions & 5 deletions pkg/controller/atlascluster/atlascluster_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,10 @@ import (

// AtlasClusterReconciler reconciles an AtlasCluster object
type AtlasClusterReconciler struct {
Client client.Client
Log *zap.SugaredLogger
Scheme *runtime.Scheme
Client client.Client
Log *zap.SugaredLogger
Scheme *runtime.Scheme
AtlasDomain string
}

// +kubebuilder:rbac:groups=atlas.mongodb.com,resources=atlasclusters,verbs=get;list;watch;create;update;patch;delete
Expand Down Expand Up @@ -74,7 +75,7 @@ func (r *AtlasClusterReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error
return result.ReconcileResult(), nil
}

c, result := ensureClusterState(log, connection, project, cluster)
c, result := r.ensureClusterState(log, connection, project, cluster)
if c != nil && c.StateName != "" {
ctx.EnsureStatusOption(status.AtlasClusterStateNameOption(c.StateName))
}
Expand Down Expand Up @@ -135,7 +136,7 @@ func (r *AtlasClusterReconciler) Delete(obj runtime.Object) error {
return errors.New("cannot read Atlas connection")
}

atlasClient, err := atlas.Client(connection, log)
atlasClient, err := atlas.Client(r.AtlasDomain, connection, log)
if err != nil {
return fmt.Errorf("cannot build Atlas client: %w", err)
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/controller/atlascluster/cluster.go
Original file line number Diff line number Diff line change
Expand Up @@ -15,10 +15,10 @@ import (
"go.uber.org/zap"
)

func ensureClusterState(log *zap.SugaredLogger, connection atlas.Connection, project *mdbv1.AtlasProject, cluster *mdbv1.AtlasCluster) (c *mongodbatlas.Cluster, _ workflow.Result) {
func (r *AtlasClusterReconciler) ensureClusterState(log *zap.SugaredLogger, connection atlas.Connection, project *mdbv1.AtlasProject, cluster *mdbv1.AtlasCluster) (c *mongodbatlas.Cluster, _ workflow.Result) {
ctx := context.Background()

client, err := atlas.Client(connection, log)
client, err := atlas.Client(r.AtlasDomain, connection, log)
if err != nil {
return c, workflow.Terminate(workflow.Internal, err.Error())
}
Expand Down
7 changes: 4 additions & 3 deletions pkg/controller/atlasproject/atlasproject_controller.go
Original file line number Diff line number Diff line change
Expand Up @@ -33,8 +33,9 @@ import (
// AtlasProjectReconciler reconciles a AtlasProject object
type AtlasProjectReconciler struct {
client.Client
Log *zap.SugaredLogger
Scheme *runtime.Scheme
Log *zap.SugaredLogger
Scheme *runtime.Scheme
AtlasDomain string
}

// +kubebuilder:rbac:groups=atlas.mongodb.com,resources=atlasprojects,verbs=get;list;watch;create;update;patch;delete
Expand Down Expand Up @@ -68,7 +69,7 @@ func (r *AtlasProjectReconciler) Reconcile(req ctrl.Request) (ctrl.Result, error
}

var projectID string
if projectID, result = ensureProjectExists(ctx, connection, project); !result.IsOk() {
if projectID, result = r.ensureProjectExists(ctx, connection, project); !result.IsOk() {
ctx.SetConditionFromResult(status.ProjectReadyType, result)
return result.ReconcileResult(), nil
}
Expand Down
4 changes: 2 additions & 2 deletions pkg/controller/atlasproject/project.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@ import (
)

// ensureProjectExists creates the project if it doesn't exist yet. Returns the project ID
func ensureProjectExists(ctx *workflow.Context, connection atlas.Connection, project *mdbv1.AtlasProject) (string, workflow.Result) {
client, err := atlas.Client(connection, ctx.Log)
func (r *AtlasProjectReconciler) ensureProjectExists(ctx *workflow.Context, connection atlas.Connection, project *mdbv1.AtlasProject) (string, workflow.Result) {
client, err := atlas.Client(r.AtlasDomain, connection, ctx.Log)
if err != nil {
return "", workflow.Terminate(workflow.Internal, err.Error())
}
Expand Down
10 changes: 6 additions & 4 deletions test/int/integration_suite_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,14 +92,16 @@ var _ = BeforeSuite(func(done Done) {
Expect(err).ToNot(HaveOccurred())

err = (&atlasproject.AtlasProjectReconciler{
Client: k8sManager.GetClient(),
Log: logger.Named("controllers").Named("AtlasProject").Sugar(),
Client: k8sManager.GetClient(),
Log: logger.Named("controllers").Named("AtlasProject").Sugar(),
AtlasDomain: "https://cloud-qa.mongodb.com",
}).SetupWithManager(k8sManager)
Expect(err).ToNot(HaveOccurred())

err = (&atlascluster.AtlasClusterReconciler{
Client: k8sManager.GetClient(),
Log: logger.Named("controllers").Named("AtlasCluster").Sugar(),
Client: k8sManager.GetClient(),
Log: logger.Named("controllers").Named("AtlasCluster").Sugar(),
AtlasDomain: "https://cloud-qa.mongodb.com",
}).SetupWithManager(k8sManager)
Expect(err).ToNot(HaveOccurred())

Expand Down

0 comments on commit 822a61a

Please sign in to comment.