github.com/redhat-appstudio/release-service@v0.0.0-20240507045911-a8558ef3422a/syncer/syncer.go (about) 1 /* 2 Copyright 2022. 3 4 Licensed under the Apache License, Version 2.0 (the "License"); 5 you may not use this file except in compliance with the License. 6 You may obtain a copy of the License at 7 8 http://www.apache.org/licenses/LICENSE-2.0 9 10 Unless required by applicable law or agreed to in writing, software 11 distributed under the License is distributed on an "AS IS" BASIS, 12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 See the License for the specific language governing permissions and 14 limitations under the License. 15 */ 16 17 package syncer 18 19 import ( 20 "context" 21 "github.com/go-logr/logr" 22 applicationapiv1alpha1 "github.com/redhat-appstudio/application-api/api/v1alpha1" 23 "k8s.io/apimachinery/pkg/api/errors" 24 v1 "k8s.io/apimachinery/pkg/apis/meta/v1" 25 "sigs.k8s.io/controller-runtime/pkg/client" 26 ) 27 28 type Syncer struct { 29 client client.Client 30 ctx context.Context 31 logger *logr.Logger 32 } 33 34 // NewSyncer creates a new Syncer with the given client and logger. 35 func NewSyncer(client client.Client, logger *logr.Logger) *Syncer { 36 return NewSyncerWithContext(client, logger, context.TODO()) 37 } 38 39 // NewSyncerWithContext creates a new Syncer with the given client, logger and context. 40 func NewSyncerWithContext(client client.Client, logger *logr.Logger, ctx context.Context) *Syncer { 41 return &Syncer{ 42 client: client, 43 ctx: ctx, 44 logger: logger, 45 } 46 } 47 48 // SetContext sets a new context for the Syncer. 49 func (s *Syncer) SetContext(ctx context.Context) { 50 s.ctx = ctx 51 } 52 53 // SyncSnapshot syncs a Snapshot into the given namespace. If an exiting one is found, no operations will be taken. 54 func (s *Syncer) SyncSnapshot(snapshot *applicationapiv1alpha1.Snapshot, namespace string) error { 55 syncedSnapshot := snapshot.DeepCopy() 56 syncedSnapshot.ObjectMeta = v1.ObjectMeta{ 57 Name: snapshot.Name, 58 Namespace: namespace, 59 Annotations: snapshot.Annotations, 60 Labels: snapshot.Labels, 61 } 62 err := s.client.Create(s.ctx, syncedSnapshot) 63 if err != nil && !errors.IsAlreadyExists(err) { 64 return err 65 } 66 67 s.logger.Info("Snapshot synced", "Name", syncedSnapshot.Name, 68 "Origin namespace", snapshot.Namespace, "Target namespace", syncedSnapshot.Namespace) 69 70 return nil 71 }