github.com/erda-project/erda-infra@v1.0.9/providers/component-protocol/protocol/state.go (about) 1 // Copyright (c) 2021 Terminus, Inc. 2 // 3 // Licensed under the Apache License, Version 2.0 (the "License"); 4 // you may not use this file except in compliance with the License. 5 // You may obtain a copy of the License at 6 // 7 // http://www.apache.org/licenses/LICENSE-2.0 8 // 9 // Unless required by applicable law or agreed to in writing, software 10 // distributed under the License is distributed on an "AS IS" BASIS, 11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 12 // See the License for the specific language governing permissions and 13 // limitations under the License. 14 15 package protocol 16 17 import ( 18 "fmt" 19 "strings" 20 21 "github.com/sirupsen/logrus" 22 23 "github.com/erda-project/erda-infra/providers/component-protocol/cptype" 24 ) 25 26 // setGlobalStateKV . 27 func setGlobalStateKV(p *cptype.ComponentProtocol, key string, value interface{}) { 28 if p.GlobalState == nil { 29 var gs = make(cptype.GlobalStateData) 30 p.GlobalState = &gs 31 } 32 s := p.GlobalState 33 (*s)[key] = value 34 } 35 36 // GetGlobalStateKV . 37 func GetGlobalStateKV(p *cptype.ComponentProtocol, key string) interface{} { 38 if p.GlobalState == nil { 39 return nil 40 } 41 return (*p.GlobalState)[key] 42 } 43 44 // getCompStateKV . 45 func getCompStateKV(c *cptype.Component, stateKey string) (interface{}, error) { 46 if c == nil { 47 err := fmt.Errorf("empty component") 48 return nil, err 49 } 50 if _, ok := c.State[stateKey]; !ok { 51 err := fmt.Errorf("state key [%s] not exist in component [%s] state", stateKey, c.Name) 52 return nil, err 53 } 54 return c.State[stateKey], nil 55 } 56 57 // setCompStateValueFromComps . 58 func setCompStateValueFromComps(c *cptype.Component, key string, value interface{}) error { 59 if c == nil { 60 err := fmt.Errorf("empty component") 61 return err 62 } 63 if key == "" { 64 err := fmt.Errorf("empty state key") 65 return err 66 } 67 if v, ok := c.State[key]; ok { 68 logrus.Infof("state key already exist in component, component:%s, key:%s, value old:%+v, new:%+v", c.Name, key, v, value) 69 } 70 if c.State == nil { 71 c.State = map[string]interface{}{} 72 } 73 c.State[key] = value 74 return nil 75 } 76 77 // parseStateBound . 78 func parseStateBound(b string) (comp, key string, err error) { 79 prefix := "{{" 80 suffix := "}}" 81 if !strings.HasPrefix(b, prefix) { 82 err = fmt.Errorf("state bound not prefix with {{") 83 return 84 } 85 if !strings.HasSuffix(b, "}}") { 86 err = fmt.Errorf("state bound not suffix with }}") 87 return 88 } 89 b = strings.TrimPrefix(b, prefix) 90 b = strings.TrimPrefix(b, " ") 91 b = strings.TrimSuffix(b, suffix) 92 b = strings.TrimSuffix(b, " ") 93 s := strings.Split(b, ".") 94 if len(s) != 2 { 95 err = fmt.Errorf("invalide bound expression: %s, with not exactly one '.' ", b) 96 return 97 } 98 comp = s[0] 99 key = s[1] 100 return 101 }