vitess.io/vitess@v0.16.2/go/vt/topo/decode.go (about) 1 /* 2 Copyright 2022 The Vitess 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 topo 18 19 import ( 20 "fmt" 21 "path" 22 23 "google.golang.org/protobuf/encoding/protojson" 24 "google.golang.org/protobuf/encoding/prototext" 25 "google.golang.org/protobuf/proto" 26 27 topodatapb "vitess.io/vitess/go/vt/proto/topodata" 28 vschemapb "vitess.io/vitess/go/vt/proto/vschema" 29 ) 30 31 // DecodeContent uses the filename to imply a type, and proto-decodes 32 // the right object, then echoes it as a string. 33 func DecodeContent(filename string, data []byte, json bool) (string, error) { 34 name := path.Base(filename) 35 dir := path.Dir(filename) 36 var p proto.Message 37 switch name { 38 case CellInfoFile: 39 p = new(topodatapb.CellInfo) 40 case KeyspaceFile: 41 p = new(topodatapb.Keyspace) 42 case ShardFile: 43 p = new(topodatapb.Shard) 44 case VSchemaFile: 45 p = new(vschemapb.Keyspace) 46 case ShardReplicationFile: 47 p = new(topodatapb.ShardReplication) 48 case TabletFile: 49 p = new(topodatapb.Tablet) 50 case SrvVSchemaFile: 51 p = new(vschemapb.SrvVSchema) 52 case SrvKeyspaceFile: 53 p = new(topodatapb.SrvKeyspace) 54 case RoutingRulesFile: 55 p = new(vschemapb.RoutingRules) 56 default: 57 switch dir { 58 case "/" + GetExternalVitessClusterDir(): 59 p = new(topodatapb.ExternalVitessCluster) 60 default: 61 } 62 if p == nil { 63 if json { 64 return "", fmt.Errorf("unknown topo protobuf type for %v", name) 65 } 66 return string(data), nil 67 } 68 } 69 70 if err := proto.Unmarshal(data, p); err != nil { 71 return string(data), err 72 } 73 74 var marshalled []byte 75 var err error 76 if json { 77 marshalled, err = protojson.Marshal(p) 78 } else { 79 marshalled, err = prototext.Marshal(p) 80 } 81 return string(marshalled), err 82 }