github.com/IBM-Blockchain/fabric-operator@v1.0.4/pkg/restart/configmap/manager.go (about) 1 /* 2 * Copyright contributors to the Hyperledger Fabric Operator project 3 * 4 * SPDX-License-Identifier: Apache-2.0 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); 7 * you may not use this file except in compliance with the License. 8 * You may obtain a copy of the License at: 9 * 10 * http://www.apache.org/licenses/LICENSE-2.0 11 * 12 * Unless required by applicable law or agreed to in writing, software 13 * distributed under the License is distributed on an "AS IS" BASIS, 14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 * See the License for the specific language governing permissions and 16 * limitations under the License. 17 */ 18 19 package configmap 20 21 import ( 22 "context" 23 "encoding/json" 24 25 k8sclient "github.com/IBM-Blockchain/fabric-operator/pkg/k8s/controllerclient" 26 "github.com/pkg/errors" 27 corev1 "k8s.io/api/core/v1" 28 k8serrors "k8s.io/apimachinery/pkg/api/errors" 29 v1 "k8s.io/apimachinery/pkg/apis/meta/v1" 30 "k8s.io/apimachinery/pkg/types" 31 ) 32 33 type Manager struct { 34 Client k8sclient.Client 35 } 36 37 func NewManager(client k8sclient.Client) *Manager { 38 return &Manager{ 39 Client: client, 40 } 41 } 42 43 func (c *Manager) GetRestartConfigFrom(cmName string, namespace string, into interface{}) error { 44 cm := &corev1.ConfigMap{} 45 n := types.NamespacedName{ 46 Name: cmName, 47 Namespace: namespace, 48 } 49 50 err := c.Client.Get(context.TODO(), n, cm) 51 if err != nil { 52 if !k8serrors.IsNotFound(err) { 53 return errors.Wrapf(err, "failed to get %s config map", cmName) 54 } 55 56 // If config map doesn't exist yet, keep into cfg empty 57 return nil 58 } 59 60 if cm.BinaryData["restart-config.yaml"] == nil { 61 return nil 62 } 63 64 err = json.Unmarshal(cm.BinaryData["restart-config.yaml"], into) 65 if err != nil { 66 return errors.Wrapf(err, "failed to unmarshal %s config map", cmName) 67 } 68 69 return nil 70 } 71 72 func (c *Manager) UpdateConfig(cmName string, namespace string, cfg interface{}) error { 73 bytes, err := json.Marshal(cfg) 74 if err != nil { 75 return err 76 } 77 78 cm := &corev1.ConfigMap{ 79 ObjectMeta: v1.ObjectMeta{ 80 Name: cmName, 81 Namespace: namespace, 82 }, 83 BinaryData: map[string][]byte{ 84 "restart-config.yaml": bytes, 85 }, 86 } 87 88 err = c.Client.CreateOrUpdate(context.TODO(), cm) 89 if err != nil { 90 return errors.Wrapf(err, "failed to create or update %s config map", cmName) 91 } 92 93 return nil 94 }