Skip to content

Commit

Permalink
Merge branch 'master' into delete-id-from-hist-asset
Browse files Browse the repository at this point in the history
  • Loading branch information
sydneynotthecity authored Mar 1, 2024
2 parents 232f829 + 81ee29d commit ff4797f
Show file tree
Hide file tree
Showing 31 changed files with 321 additions and 269 deletions.
137 changes: 137 additions & 0 deletions cmd/command_utils.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,137 @@
package cmd

import (
"bytes"
"encoding/json"
"fmt"
"os"
"path/filepath"
)

type CloudStorage interface {
UploadTo(credentialsPath, bucket, path string) error
}

func createOutputFile(filepath string) error {
var _, err = os.Stat(filepath)
if os.IsNotExist(err) {
var _, err = os.Create(filepath)
if err != nil {
return err
}
}

return nil
}

func mustOutFile(path string) *os.File {
absolutePath, err := filepath.Abs(path)
if err != nil {
cmdLogger.Fatal("could not get absolute filepath: ", err)
}

err = os.MkdirAll(filepath.Dir(path), os.ModePerm)
if err != nil {
cmdLogger.Fatalf("could not create directory %s: %s", path, err)
}

err = createOutputFile(absolutePath)
if err != nil {
cmdLogger.Fatal("could not create output file: ", err)
}

outFile, err := os.OpenFile(absolutePath, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
if err != nil {
cmdLogger.Fatal("error in opening output file: ", err)
}

return outFile
}

func exportEntry(entry interface{}, outFile *os.File, extra map[string]string) (int, error) {
// This extra marshalling/unmarshalling is silly, but it's required to properly handle the null.[String|Int*] types, and add the extra fields.
m, err := json.Marshal(entry)
if err != nil {
cmdLogger.Errorf("Error marshalling %+v: %v ", entry, err)
}
i := map[string]interface{}{}
// Use a decoder here so that 'UseNumber' ensures large ints are properly decoded
decoder := json.NewDecoder(bytes.NewReader(m))
decoder.UseNumber()
err = decoder.Decode(&i)
if err != nil {
cmdLogger.Errorf("Error unmarshalling %+v: %v ", i, err)
}
for k, v := range extra {
i[k] = v
}

marshalled, err := json.Marshal(i)
if err != nil {
return 0, fmt.Errorf("could not json encode %+v: %s", entry, err)
}
cmdLogger.Debugf("Writing entry to %s", outFile.Name())
numBytes, err := outFile.Write(marshalled)
if err != nil {
cmdLogger.Errorf("Error writing %+v to file: %s", entry, err)
}
newLineNumBytes, err := outFile.WriteString("\n")
if err != nil {
cmdLogger.Errorf("Error writing new line to file %s: %s", outFile.Name(), err)
}
return numBytes + newLineNumBytes, nil
}

// Prints the number of attempted, failed, and successful transformations as a JSON object
func printTransformStats(attempts, failures int) {
resultsMap := map[string]int{
"attempted_transforms": attempts,
"failed_transforms": failures,
"successful_transforms": attempts - failures,
}

results, err := json.Marshal(resultsMap)
if err != nil {
cmdLogger.Fatal("Could not marshal results: ", err)
}

cmdLogger.Info(string(results))
}

func exportFilename(start, end uint32, dataType string) string {
return fmt.Sprintf("%d-%d-%s.txt", start, end-1, dataType)
}

func deleteLocalFiles(path string) {
err := os.RemoveAll(path)
if err != nil {
cmdLogger.Errorf("Unable to remove %s: %s", path, err)
return
}
cmdLogger.Infof("Successfully deleted %s", path)
}

func maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path string) {
if cloudProvider == "" {
cmdLogger.Info("No cloud provider specified for upload. Skipping upload.")
return
}

if len(cloudStorageBucket) == 0 {
cmdLogger.Error("No bucket specified")
return
}

var cloudStorage CloudStorage
switch cloudProvider {
case "gcp":
cloudStorage = newGCS(cloudCredentials, cloudStorageBucket)
err := cloudStorage.UploadTo(cloudCredentials, cloudStorageBucket, path)
if err != nil {
cmdLogger.Errorf("Unable to upload output to GCS: %s", err)
return
}
default:
cmdLogger.Error("Unknown cloud provider")
}
}
6 changes: 3 additions & 3 deletions cmd/export_account_signers.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ the export_ledger_entry_changes command.`,
cmdLogger.StrictExport = strictExport
env := utils.GetEnvironmentDetails(isTest, isFuture)
path := utils.MustBucketFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)

accounts, err := input.GetEntriesFromGenesis(endNum, xdr.LedgerEntryTypeAccount, env.ArchiveURLs)
if err != nil {
Expand Down Expand Up @@ -65,14 +65,14 @@ the export_ledger_entry_changes command.`,

printTransformStats(numSigners, numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
},
}

func init() {
rootCmd.AddCommand(accountSignersCmd)
utils.AddCommonFlags(accountSignersCmd.Flags())
utils.AddBucketFlags("signers", accountSignersCmd.Flags())
utils.AddGcsFlags(accountSignersCmd.Flags())
utils.AddCloudStorageFlags(accountSignersCmd.Flags())
accountSignersCmd.MarkFlagRequired("end-ledger")
}
6 changes: 3 additions & 3 deletions cmd/export_accounts.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ the export_ledger_entry_changes command.`,
cmdLogger.StrictExport = strictExport
env := utils.GetEnvironmentDetails(isTest, isFuture)
path := utils.MustBucketFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)

accounts, err := input.GetEntriesFromGenesis(endNum, xdr.LedgerEntryTypeAccount, env.ArchiveURLs)
if err != nil {
Expand Down Expand Up @@ -59,15 +59,15 @@ the export_ledger_entry_changes command.`,

printTransformStats(len(accounts), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
},
}

func init() {
rootCmd.AddCommand(accountsCmd)
utils.AddCommonFlags(accountsCmd.Flags())
utils.AddBucketFlags("accounts", accountsCmd.Flags())
utils.AddGcsFlags(accountsCmd.Flags())
utils.AddCloudStorageFlags(accountsCmd.Flags())
accountsCmd.MarkFlagRequired("end-ledger")
/*
Current flags:
Expand Down
34 changes: 17 additions & 17 deletions cmd/export_all_history.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ in order to mitigate egress costs for the entity hosting history archives.`,
endNum, strictExport, isTest, isFuture, extra := utils.MustCommonFlags(cmd.Flags(), cmdLogger)
cmdLogger.StrictExport = strictExport
startNum, path, limit := utils.MustArchiveFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)
env := utils.GetEnvironmentDetails(isTest, isFuture)

allHistory, err := input.GetAllHistory(startNum, endNum, limit, env)
Expand All @@ -32,16 +32,16 @@ in order to mitigate egress costs for the entity hosting history archives.`,
}

cmdLogger.Info("start doing other exports")
getOperations(allHistory.Operations, extra, gcpCredentials, gcsBucket, path+"exported_operations.txt", env)
getTrades(allHistory.Trades, extra, gcpCredentials, gcsBucket, path+"exported_trades.txt")
getEffects(allHistory.Ledgers, extra, gcpCredentials, gcsBucket, path+"exported_effects.txt", env)
getTransactions(allHistory.Ledgers, extra, gcpCredentials, gcsBucket, path+"exported_transactions.txt")
getDiagnosticEvents(allHistory.Ledgers, extra, gcpCredentials, gcsBucket, path+"exported_diagnostic_events.txt")
getOperations(allHistory.Operations, extra, cloudStorageBucket, cloudCredentials, cloudProvider, path+"exported_operations.txt", env)
getTrades(allHistory.Trades, extra, cloudStorageBucket, cloudCredentials, cloudProvider, path+"exported_trades.txt")
getEffects(allHistory.Ledgers, extra, cloudStorageBucket, cloudCredentials, cloudProvider, path+"exported_effects.txt", env)
getTransactions(allHistory.Ledgers, extra, cloudStorageBucket, cloudCredentials, cloudProvider, path+"exported_transactions.txt")
getDiagnosticEvents(allHistory.Ledgers, extra, cloudStorageBucket, cloudCredentials, cloudProvider, path+"exported_diagnostic_events.txt")
cmdLogger.Info("done doing other exports")
},
}

func getOperations(operations []input.OperationTransformInput, extra map[string]string, gcpCredentials string, gcsBucket string, path string, env utils.EnvironmentDetails) {
func getOperations(operations []input.OperationTransformInput, extra map[string]string, cloudStorageBucket string, cloudCredentials string, cloudProvider string, path string, env utils.EnvironmentDetails) {
outFileOperations := mustOutFile(path)
numFailures := 0
totalNumBytes := 0
Expand All @@ -68,10 +68,10 @@ func getOperations(operations []input.OperationTransformInput, extra map[string]

printTransformStats(len(operations), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
}

func getTrades(trades []input.TradeTransformInput, extra map[string]string, gcpCredentials string, gcsBucket string, path string) {
func getTrades(trades []input.TradeTransformInput, extra map[string]string, cloudStorageBucket string, cloudCredentials string, cloudProvider string, path string) {
outFile := mustOutFile(path)
numFailures := 0
totalNumBytes := 0
Expand Down Expand Up @@ -100,10 +100,10 @@ func getTrades(trades []input.TradeTransformInput, extra map[string]string, gcpC

printTransformStats(len(trades), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
}

func getEffects(transactions []input.LedgerTransformInput, extra map[string]string, gcpCredentials string, gcsBucket string, path string, env utils.EnvironmentDetails) {
func getEffects(transactions []input.LedgerTransformInput, extra map[string]string, cloudStorageBucket string, cloudCredentials string, cloudProvider string, path string, env utils.EnvironmentDetails) {
outFile := mustOutFile(path)
numFailures := 0
totalNumBytes := 0
Expand Down Expand Up @@ -133,10 +133,10 @@ func getEffects(transactions []input.LedgerTransformInput, extra map[string]stri

printTransformStats(len(transactions), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
}

func getTransactions(transactions []input.LedgerTransformInput, extra map[string]string, gcpCredentials string, gcsBucket string, path string) {
func getTransactions(transactions []input.LedgerTransformInput, extra map[string]string, cloudStorageBucket string, cloudCredentials string, cloudProvider string, path string) {
outFile := mustOutFile(path)
numFailures := 0
totalNumBytes := 0
Expand All @@ -163,10 +163,10 @@ func getTransactions(transactions []input.LedgerTransformInput, extra map[string

printTransformStats(len(transactions), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
}

func getDiagnosticEvents(transactions []input.LedgerTransformInput, extra map[string]string, gcpCredentials string, gcsBucket string, path string) {
func getDiagnosticEvents(transactions []input.LedgerTransformInput, extra map[string]string, cloudStorageBucket string, cloudCredentials string, cloudProvider string, path string) {
outFile := mustOutFile(path)
numFailures := 0
for _, transformInput := range transactions {
Expand Down Expand Up @@ -195,13 +195,13 @@ func getDiagnosticEvents(transactions []input.LedgerTransformInput, extra map[st

printTransformStats(len(transactions), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
}

func init() {
rootCmd.AddCommand(allHistoryCmd)
utils.AddCommonFlags(allHistoryCmd.Flags())
utils.AddArchiveFlags("", allHistoryCmd.Flags())
utils.AddGcsFlags(allHistoryCmd.Flags())
utils.AddCloudStorageFlags(allHistoryCmd.Flags())
allHistoryCmd.MarkFlagRequired("end-ledger")
}
6 changes: 3 additions & 3 deletions cmd/export_assets.go
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ var assetsCmd = &cobra.Command{
endNum, strictExport, isTest, isFuture, extra := utils.MustCommonFlags(cmd.Flags(), cmdLogger)
cmdLogger.StrictExport = strictExport
startNum, path, limit := utils.MustArchiveFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)

outFile := mustOutFile(path)

Expand Down Expand Up @@ -61,15 +61,15 @@ var assetsCmd = &cobra.Command{

printTransformStats(len(paymentOps), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
},
}

func init() {
rootCmd.AddCommand(assetsCmd)
utils.AddCommonFlags(assetsCmd.Flags())
utils.AddArchiveFlags("assets", assetsCmd.Flags())
utils.AddGcsFlags(assetsCmd.Flags())
utils.AddCloudStorageFlags(assetsCmd.Flags())
assetsCmd.MarkFlagRequired("end-ledger")

/*
Expand Down
6 changes: 3 additions & 3 deletions cmd/export_claimable_balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var claimableBalancesCmd = &cobra.Command{
cmdLogger.StrictExport = strictExport
env := utils.GetEnvironmentDetails(isTest, isFuture)
path := utils.MustBucketFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)

balances, err := input.GetEntriesFromGenesis(endNum, xdr.LedgerEntryTypeClaimableBalance, env.ArchiveURLs)
if err != nil {
Expand Down Expand Up @@ -59,15 +59,15 @@ var claimableBalancesCmd = &cobra.Command{

printTransformStats(len(balances), numFailures)

maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)
},
}

func init() {
rootCmd.AddCommand(claimableBalancesCmd)
utils.AddCommonFlags(claimableBalancesCmd.Flags())
utils.AddBucketFlags("claimable_balances", claimableBalancesCmd.Flags())
utils.AddGcsFlags(claimableBalancesCmd.Flags())
utils.AddCloudStorageFlags(claimableBalancesCmd.Flags())
claimableBalancesCmd.MarkFlagRequired("end-ledger")

/*
Expand Down
6 changes: 3 additions & 3 deletions cmd/export_config_setting.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var configSettingCmd = &cobra.Command{
cmdLogger.StrictExport = strictExport
env := utils.GetEnvironmentDetails(isTest, isFuture)
path := utils.MustBucketFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)

settings, err := input.GetEntriesFromGenesis(endNum, xdr.LedgerEntryTypeConfigSetting, env.ArchiveURLs)
if err != nil {
Expand Down Expand Up @@ -57,7 +57,7 @@ var configSettingCmd = &cobra.Command{
cmdLogger.Info("Number of bytes written: ", totalNumBytes)

printTransformStats(len(settings), numFailures)
maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)

},
}
Expand All @@ -66,7 +66,7 @@ func init() {
rootCmd.AddCommand(configSettingCmd)
utils.AddCommonFlags(configSettingCmd.Flags())
utils.AddBucketFlags("config_settings", configSettingCmd.Flags())
utils.AddGcsFlags(configSettingCmd.Flags())
utils.AddCloudStorageFlags(configSettingCmd.Flags())
configSettingCmd.MarkFlagRequired("end-ledger")
/*
Current flags:
Expand Down
6 changes: 3 additions & 3 deletions cmd/export_contract_code.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ var codeCmd = &cobra.Command{
cmdLogger.StrictExport = strictExport
env := utils.GetEnvironmentDetails(isTest, isFuture)
path := utils.MustBucketFlags(cmd.Flags(), cmdLogger)
gcsBucket, gcpCredentials := utils.MustGcsFlags(cmd.Flags(), cmdLogger)
cloudStorageBucket, cloudCredentials, cloudProvider := utils.MustCloudStorageFlags(cmd.Flags(), cmdLogger)

codes, err := input.GetEntriesFromGenesis(endNum, xdr.LedgerEntryTypeContractCode, env.ArchiveURLs)
if err != nil {
Expand Down Expand Up @@ -57,7 +57,7 @@ var codeCmd = &cobra.Command{
cmdLogger.Info("Number of bytes written: ", totalNumBytes)

printTransformStats(len(codes), numFailures)
maybeUpload(gcpCredentials, gcsBucket, path)
maybeUpload(cloudCredentials, cloudStorageBucket, cloudProvider, path)

},
}
Expand All @@ -66,7 +66,7 @@ func init() {
rootCmd.AddCommand(codeCmd)
utils.AddCommonFlags(codeCmd.Flags())
utils.AddBucketFlags("contract_code", codeCmd.Flags())
utils.AddGcsFlags(codeCmd.Flags())
utils.AddCloudStorageFlags(codeCmd.Flags())
codeCmd.MarkFlagRequired("end-ledger")
/*
Current flags:
Expand Down
Loading

0 comments on commit ff4797f

Please sign in to comment.