github.com/matrixorigin/matrixone@v1.2.0/pkg/tnservice/store_metadata.go (about) 1 // Copyright 2021 - 2022 Matrix Origin 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 tnservice 16 17 import ( 18 "path/filepath" 19 20 "github.com/fagongzi/util/protoc" 21 "github.com/matrixorigin/matrixone/pkg/pb/metadata" 22 "github.com/matrixorigin/matrixone/pkg/util/file" 23 "go.uber.org/zap" 24 ) 25 26 const ( 27 metadataDir = "dnservice" 28 ) 29 30 func getMetadataFile(uuid string) string { 31 return filepath.Join(metadataDir, uuid) 32 } 33 34 func (s *store) initMetadata() error { 35 data, err := file.ReadFile(s.metadataFileService, getMetadataFile(s.cfg.UUID)) 36 if err != nil { 37 return err 38 } 39 40 if len(data) == 0 { 41 s.mustUpdateMetadataLocked() 42 return nil 43 } 44 45 v := &metadata.TNStore{} 46 protoc.MustUnmarshal(v, data) 47 if v.UUID != s.mu.metadata.UUID { 48 s.rt.Logger().Fatal("BUG: disk DNStore and start DNStore not match", 49 zap.String("disk-store", v.UUID)) 50 } 51 s.mu.metadata = *v 52 53 s.rt.Logger().Info("local DNShard loaded", 54 zap.String("metadata", s.mu.metadata.DebugString())) 55 return nil 56 } 57 58 func (s *store) addTNShardLocked(shard metadata.TNShard) { 59 for _, tn := range s.mu.metadata.Shards { 60 if tn.ShardID == shard.ShardID { 61 return 62 } 63 } 64 s.mu.metadata.Shards = append(s.mu.metadata.Shards, shard) 65 s.mustUpdateMetadataLocked() 66 } 67 68 func (s *store) removeTNShard(id uint64) { 69 s.mu.Lock() 70 defer s.mu.Unlock() 71 72 var newShards []metadata.TNShard 73 for _, tn := range s.mu.metadata.Shards { 74 if tn.ShardID != id { 75 newShards = append(newShards, tn) 76 } 77 } 78 s.mu.metadata.Shards = newShards 79 s.mustUpdateMetadataLocked() 80 } 81 82 func (s *store) mustUpdateMetadataLocked() { 83 if err := file.WriteFile(s.metadataFileService, 84 getMetadataFile(s.cfg.UUID), 85 protoc.MustMarshal(&s.mu.metadata)); err != nil { 86 s.rt.Logger().Fatal("update metadata to local file failed", 87 zap.Error(err)) 88 } 89 }