-
Notifications
You must be signed in to change notification settings - Fork 33
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[CLI][Localnet][Bug] - [localnet_client_debug] Error 137 - Issue #607 #608
Merged
Merged
Changes from 8 commits
Commits
Show all changes
18 commits
Select commit
Hold shift + click to select a range
eb9cb58
feat(build): debug_keybase snapshotter
deblasis 0cf1c47
fix(build): updates in private_keys.yaml handling
deblasis 868984b
refactor(cli): updated to use the DebugKeybaseBackup
deblasis ce156d7
feat(Makefile): added refresh_debug_keybase make target
deblasis 15d607b
feat(build): keybase backup artifacts
deblasis a7ea14b
chore(cli): nits
deblasis d6baa4d
Update build/debug_keybase/main.go
deblasis 1c696ae
refactor(build): using utils.FileExists
deblasis c741167
chore(build): nits
deblasis 19aeb26
docs(app): CHANGELOG
deblasis fdc299e
docs(build): CHANGELOG
deblasis 1dbc665
chore(build): lint
deblasis 32c957b
chore(app): nits
deblasis 15daa63
chore(build): nits
deblasis aee322b
docs(app): CHANGELOG
deblasis 917d7ae
docs(build): CHANGELOG
deblasis 0d9f5c2
Merge remote-tracking branch 'origin/main' into issue/memoize_debug_k…
deblasis d2e951e
fix(build): typo
deblasis File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
This file is used to check if the keybase dump is in sync with the YAML file. Its name is the MD5 hash of the private_keys.yaml |
Binary file not shown.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,192 @@ | ||
package main | ||
|
||
import ( | ||
"crypto/md5" | ||
"fmt" | ||
"io/ioutil" | ||
"os" | ||
"path/filepath" | ||
|
||
"github.com/korovkin/limiter" | ||
"gopkg.in/yaml.v2" | ||
|
||
"github.com/pokt-network/pocket/app/client/keybase" | ||
cryptoPocket "github.com/pokt-network/pocket/shared/crypto" | ||
"github.com/pokt-network/pocket/shared/utils" | ||
) | ||
|
||
const ( | ||
// NOTE: This is the number of validators in the private-keys.yaml manifest file | ||
numValidators = 999 | ||
|
||
// Increasing this number is linearly proportional to the amount of RAM required for the debug client to start and import | ||
// pre-generated keys into the keybase. Beware that might cause OOM and process can exit with 137 status code. | ||
// 4 threads takes 350-400MiB from a few tests which sounds acceptable. | ||
debugKeybaseImportConcurrencyLimit = 4 | ||
) | ||
|
||
func main() { | ||
if len(os.Args) < 3 { | ||
fmt.Println("Usage: go run main.go <source_yaml> <target_folder>") | ||
Olshansk marked this conversation as resolved.
Show resolved
Hide resolved
|
||
return | ||
} | ||
sourceYamlPath := os.Args[1] | ||
targetFolderPath := os.Args[2] | ||
|
||
privateKeysYamlBytes, err := ioutil.ReadFile(sourceYamlPath) | ||
if err != nil { | ||
fmt.Printf("Error reading source_yaml: %v\n", err) | ||
return | ||
} | ||
sourceYamlHash := md5.Sum(privateKeysYamlBytes) // nolint:gosec // Weak hashing function only used to check if the file has been changed | ||
hashString := fmt.Sprintf("%x.md5", sourceYamlHash) | ||
hashFilePath := filepath.Join(targetFolderPath, hashString) | ||
deblasis marked this conversation as resolved.
Show resolved
Hide resolved
|
||
targetFilePath := filepath.Join(targetFolderPath, "debug_keybase.bak") | ||
if exists, _ := utils.FileExists(hashFilePath); !exists { | ||
cleanupStaleFiles(targetFolderPath) | ||
dumpKeybase(privateKeysYamlBytes, targetFilePath) | ||
createHashFile(hashFilePath) | ||
} else { | ||
fmt.Println("✅ Keybase dump already exists and in sync with YAML file") | ||
} | ||
} | ||
|
||
func dumpKeybase(privateKeysYamlBytes []byte, targetFilePath string) { | ||
fmt.Println("⚙️ Initializing debug Keybase...") | ||
|
||
validatorKeysPairMap, err := parseValidatorPrivateKeysFromEmbeddedYaml(privateKeysYamlBytes) | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
tmpDir, err := os.MkdirTemp("/tmp", "pocket_debug_keybase_*") | ||
if err != nil { | ||
panic(err) | ||
} | ||
defer os.RemoveAll(tmpDir) | ||
|
||
kb, err := keybase.NewKeybase(tmpDir) | ||
if err != nil { | ||
panic(err) | ||
} | ||
db := kb.GetBadgerDB() | ||
|
||
// Add validator addresses if not present | ||
fmt.Println("✍️ Debug keybase initializing... Adding all the validator keys") | ||
|
||
// Use writebatch to speed up bulk insert | ||
wb := db.NewWriteBatch() | ||
|
||
// Create a channel to receive errors from goroutines | ||
errCh := make(chan error, numValidators) | ||
|
||
limit := limiter.NewConcurrencyLimiter(debugKeybaseImportConcurrencyLimit) | ||
for _, privHexString := range validatorKeysPairMap { | ||
limit.Execute(func() { | ||
// Import the keys into the keybase with no passphrase or hint as these are for debug purposes | ||
keyPair, err := cryptoPocket.CreateNewKeyFromString(privHexString, "", "") | ||
if err != nil { | ||
errCh <- err | ||
return | ||
} | ||
|
||
// Use key address as key in DB | ||
addrKey := keyPair.GetAddressBytes() | ||
|
||
// Encode KeyPair into []byte for value | ||
keypairBz, err := keyPair.Marshal() | ||
if err != nil { | ||
errCh <- err | ||
return | ||
} | ||
if err := wb.Set(addrKey, keypairBz); err != nil { | ||
errCh <- err | ||
return | ||
} | ||
}) | ||
} | ||
|
||
limit.WaitAndClose() | ||
|
||
// Check if any goroutines returned an error | ||
select { | ||
case err := <-errCh: | ||
panic(err) | ||
default: | ||
} | ||
|
||
if err := wb.Flush(); err != nil { | ||
panic(err) | ||
} | ||
|
||
fmt.Println("✅ Keybase initialized!") | ||
|
||
fmt.Println("⚙️ Creating a dump of the Keybase...") | ||
backupFile, err := os.Create(targetFilePath) | ||
if err != nil { | ||
panic(err) | ||
} | ||
defer backupFile.Close() | ||
if _, err := db.Backup(backupFile, 0); err != nil { | ||
panic(err) | ||
} | ||
|
||
// Close DB connection | ||
if err := kb.Stop(); err != nil { | ||
panic(err) | ||
} | ||
|
||
fmt.Printf("✅ Keybase dumped in %s\n", targetFilePath) | ||
} | ||
|
||
func parseValidatorPrivateKeysFromEmbeddedYaml(privateKeysYamlBytes []byte) (map[string]string, error) { | ||
// Parse the YAML file and load into the config struct | ||
var config struct { | ||
ApiVersion string `yaml:"apiVersion"` | ||
Kind string `yaml:"kind"` | ||
MetaData map[string]string `yaml:"metadata"` | ||
Type string `yaml:"type"` | ||
StringData map[string]string `yaml:"stringData"` | ||
} | ||
if err := yaml.Unmarshal(privateKeysYamlBytes, &config); err != nil { | ||
return nil, err | ||
} | ||
validatorKeysMap := make(map[string]string) | ||
|
||
for id, privHexString := range config.StringData { | ||
validatorKeysMap[id] = privHexString | ||
} | ||
return validatorKeysMap, nil | ||
} | ||
|
||
func cleanupStaleFiles(targetFolderPath string) { | ||
fmt.Printf("🧹 Cleaning up stale backup files in in %s\n", targetFolderPath) | ||
|
||
if err := filepath.Walk(targetFolderPath, func(path string, info os.FileInfo, err error) error { | ||
if err != nil { | ||
panic(err) | ||
} | ||
|
||
if !info.IsDir() && (filepath.Ext(path) == ".bak" || filepath.Ext(path) == ".md5") { | ||
if err := os.Remove(path); err != nil { | ||
panic(err) | ||
} | ||
fmt.Println("🚮 Deleted file:", path) | ||
} | ||
|
||
return nil | ||
}); err != nil { | ||
panic(err) | ||
} | ||
} | ||
|
||
func createHashFile(hashFilePath string) { | ||
fmt.Printf("🔖 Creating the MD5 hash file used to track consistency: %s\n", hashFilePath) | ||
|
||
file, err := os.Create(hashFilePath) | ||
if err != nil { | ||
panic(err) | ||
} | ||
defer file.Close() | ||
file.WriteString("This file is used to check if the keybase dump is in sync with the YAML file. Its name is the MD5 hash of the private_keys.yaml") | ||
} |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
This logic is much cleaner 10/10 🚀