github.com/kubevela/workflow@v0.6.0/pkg/context/storage.go (about)

     1  /*
     2  Copyright 2022 The KubeVela Authors.
     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 context
    18  
    19  import (
    20  	"fmt"
    21  	"sync"
    22  
    23  	v1 "k8s.io/api/core/v1"
    24  )
    25  
    26  var (
    27  	// EnableInMemoryContext optimize workflow context storage by storing it in memory instead of etcd
    28  	EnableInMemoryContext = false
    29  )
    30  
    31  type inMemoryContextStorage struct {
    32  	mu       sync.Mutex
    33  	contexts map[string]*v1.ConfigMap
    34  }
    35  
    36  // MemStore store in-memory context
    37  var MemStore = &inMemoryContextStorage{
    38  	contexts: map[string]*v1.ConfigMap{},
    39  }
    40  
    41  func (o *inMemoryContextStorage) getKey(cm *v1.ConfigMap) string {
    42  	ns := cm.GetNamespace()
    43  	if ns == "" {
    44  		ns = "default"
    45  	}
    46  	name := cm.GetName()
    47  	return ns + "/" + name
    48  }
    49  
    50  func (o *inMemoryContextStorage) GetOrCreateInMemoryContext(cm *v1.ConfigMap) {
    51  	if obj := o.GetInMemoryContext(cm.Name, cm.Namespace); obj != nil {
    52  		obj.DeepCopyInto(cm)
    53  	} else {
    54  		o.CreateInMemoryContext(cm)
    55  	}
    56  }
    57  
    58  func (o *inMemoryContextStorage) GetInMemoryContext(name, ns string) *v1.ConfigMap {
    59  	return o.contexts[ns+"/"+name]
    60  }
    61  
    62  func (o *inMemoryContextStorage) CreateInMemoryContext(cm *v1.ConfigMap) {
    63  	o.mu.Lock()
    64  	defer o.mu.Unlock()
    65  	cm.Data = map[string]string{}
    66  	o.contexts[o.getKey(cm)] = cm
    67  }
    68  
    69  func (o *inMemoryContextStorage) UpdateInMemoryContext(cm *v1.ConfigMap) {
    70  	o.mu.Lock()
    71  	defer o.mu.Unlock()
    72  	o.contexts[o.getKey(cm)] = cm
    73  }
    74  
    75  func (o *inMemoryContextStorage) DeleteInMemoryContext(appName string) {
    76  	o.mu.Lock()
    77  	defer o.mu.Unlock()
    78  	key := fmt.Sprintf("workflow-%s-context", appName)
    79  	delete(o.contexts, key)
    80  }