How to use Fail method of internal Package

Best Ginkgo code snippet using internal.Fail

querier.go

Source:querier.go Github

copy

Full Screen

1package thorchain2import (3 "errors"4 "fmt"5 "net/url"6 "strconv"7 "github.com/cosmos/cosmos-sdk/codec"8 sdk "github.com/cosmos/cosmos-sdk/types"9 abci "github.com/tendermint/tendermint/abci/types"10 "gitlab.com/thorchain/thornode/common"11 "gitlab.com/thorchain/thornode/constants"12 q "gitlab.com/thorchain/thornode/x/thorchain/query"13)14// NewQuerier is the module level router for state queries15func NewQuerier(keeper Keeper, validatorMgr VersionedValidatorManager) sdk.Querier {16 return func(ctx sdk.Context, path []string, req abci.RequestQuery) (res []byte, err sdk.Error) {17 switch path[0] {18 case q.QueryPool.Key:19 return queryPool(ctx, path[1:], req, keeper)20 case q.QueryPools.Key:21 return queryPools(ctx, req, keeper)22 case q.QueryStakers.Key:23 return queryStakers(ctx, path[1:], req, keeper)24 case q.QueryTxIn.Key:25 return queryTxIn(ctx, path[1:], req, keeper)26 case q.QueryKeysignArray.Key:27 return queryKeysign(ctx, path[1:], req, keeper)28 case q.QueryKeysignArrayPubkey.Key:29 return queryKeysign(ctx, path[1:], req, keeper)30 case q.QueryKeygensPubkey.Key:31 return queryKeygen(ctx, path[1:], req, keeper)32 case q.QueryCompEvents.Key:33 return queryCompEvents(ctx, path[1:], req, keeper)34 case q.QueryCompEventsByChain.Key:35 return queryCompEvents(ctx, path[1:], req, keeper)36 case q.QueryEventsByTxHash.Key:37 return queryEventsByTxHash(ctx, path[1:], req, keeper)38 case q.QueryHeights.Key:39 return queryHeights(ctx, path[1:], req, keeper)40 case q.QueryChainHeights.Key:41 return queryHeights(ctx, path[1:], req, keeper)42 case q.QueryObservers.Key:43 return queryObservers(ctx, path[1:], req, keeper)44 case q.QueryObserver.Key:45 return queryObserver(ctx, path[1:], req, keeper)46 case q.QueryNodeAccount.Key:47 return queryNodeAccount(ctx, path[1:], req, keeper)48 case q.QueryNodeAccounts.Key:49 return queryNodeAccounts(ctx, path[1:], req, keeper)50 case q.QueryPoolAddresses.Key:51 return queryPoolAddresses(ctx, path[1:], req, keeper)52 case q.QueryVaultData.Key:53 return queryVaultData(ctx, keeper)54 case q.QueryVaultsAsgard.Key:55 return queryAsgardVaults(ctx, keeper)56 case q.QueryVaultsYggdrasil.Key:57 return queryYggdrasilVaults(ctx, keeper)58 case q.QueryVaultPubkeys.Key:59 return queryVaultsPubkeys(ctx, keeper)60 case q.QueryTSSSigners.Key:61 return queryTSSSigners(ctx, path[1:], req, keeper)62 case q.QueryConstantValues.Key:63 return queryConstantValues(ctx, path[1:], req, keeper)64 case q.QueryMimirValues.Key:65 return queryMimirValues(ctx, path[1:], req, keeper)66 case q.QueryBan.Key:67 return queryBan(ctx, path[1:], req, keeper)68 default:69 return nil, sdk.ErrUnknownRequest(70 fmt.Sprintf("unknown thorchain query endpoint: %s", path[0]),71 )72 }73 }74}75func getURLFromData(data []byte) (*url.URL, error) {76 if data == nil {77 return nil, errors.New("empty data")78 }79 u := &url.URL{}80 err := u.UnmarshalBinary(data)81 if err != nil {82 return nil, fmt.Errorf("fail to unmarshal url.URL: %w", err)83 }84 return u, nil85}86func queryAsgardVaults(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) {87 vaults, err := keeper.GetAsgardVaults(ctx)88 if err != nil {89 ctx.Logger().Error("fail to get asgard vaults", "error", err)90 return nil, sdk.ErrInternal("fail to get asgard vaults")91 }92 var vaultsWithFunds Vaults93 for _, vault := range vaults {94 if vault.IsAsgard() && (vault.HasFunds() || vault.Status == ActiveVault) {95 vaultsWithFunds = append(vaultsWithFunds, vault)96 }97 }98 res, err := codec.MarshalJSONIndent(keeper.Cdc(), vaultsWithFunds)99 if err != nil {100 ctx.Logger().Error("fail to marshal vaults response to json", "error", err)101 return nil, sdk.ErrInternal("fail to marshal response to json")102 }103 return res, nil104}105func queryYggdrasilVaults(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) {106 vaults := make(Vaults, 0)107 iter := keeper.GetVaultIterator(ctx)108 defer iter.Close()109 for ; iter.Valid(); iter.Next() {110 var vault Vault111 if err := keeper.Cdc().UnmarshalBinaryBare(iter.Value(), &vault); err != nil {112 ctx.Logger().Error("fail to unmarshal yggdrasil", "error", err)113 return nil, sdk.ErrInternal("fail to unmarshal yggdrasil")114 }115 if vault.IsYggdrasil() && vault.HasFunds() {116 vaults = append(vaults, vault)117 }118 }119 respVaults := make([]QueryYggdrasilVaults, len(vaults))120 for i, vault := range vaults {121 totalValue := sdk.ZeroUint()122 // find the bond of this node account123 na, err := keeper.GetNodeAccountByPubKey(ctx, vault.PubKey)124 if err != nil {125 ctx.Logger().Error("fail to get node account by pubkey", "error", err)126 continue127 }128 // calculate the total value of this yggdrasil vault129 for _, coin := range vault.Coins {130 if coin.Asset.IsRune() {131 totalValue = totalValue.Add(coin.Amount)132 } else {133 pool, err := keeper.GetPool(ctx, coin.Asset)134 if err != nil {135 ctx.Logger().Error("fail to get pool", "error", err)136 continue137 }138 totalValue = totalValue.Add(pool.AssetValueInRune(coin.Amount))139 }140 }141 respVaults[i] = QueryYggdrasilVaults{142 vault, na.Status, na.Bond, totalValue,143 }144 }145 res, err := codec.MarshalJSONIndent(keeper.Cdc(), respVaults)146 if err != nil {147 ctx.Logger().Error("fail to marshal vaults response to json", "error", err)148 return nil, sdk.ErrInternal("fail to marshal response to json")149 }150 return res, nil151}152func queryVaultsPubkeys(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) {153 var resp struct {154 Asgard common.PubKeys `json:"asgard"`155 Yggdrasil common.PubKeys `json:"yggdrasil"`156 }157 resp.Asgard = make(common.PubKeys, 0)158 resp.Yggdrasil = make(common.PubKeys, 0)159 iter := keeper.GetVaultIterator(ctx)160 defer iter.Close()161 for ; iter.Valid(); iter.Next() {162 var vault Vault163 if err := keeper.Cdc().UnmarshalBinaryBare(iter.Value(), &vault); err != nil {164 ctx.Logger().Error("fail to unmarshal yggdrasil", "error", err)165 return nil, sdk.ErrInternal("fail to unmarshal yggdrasil")166 }167 if vault.Status == ActiveVault {168 if vault.IsYggdrasil() {169 resp.Yggdrasil = append(resp.Yggdrasil, vault.PubKey)170 } else if vault.IsAsgard() {171 resp.Asgard = append(resp.Asgard, vault.PubKey)172 }173 }174 }175 res, err := codec.MarshalJSONIndent(keeper.Cdc(), resp)176 if err != nil {177 ctx.Logger().Error("fail to marshal pubkeys response to json", "error", err)178 return nil, sdk.ErrInternal("fail to marshal response to json")179 }180 return res, nil181}182func queryVaultData(ctx sdk.Context, keeper Keeper) ([]byte, sdk.Error) {183 data, err := keeper.GetVaultData(ctx)184 if err != nil {185 ctx.Logger().Error("fail to get vault", "error", err)186 return nil, sdk.ErrInternal("fail to get vault")187 }188 if common.RuneAsset().Chain.Equals(common.THORChain) {189 data.TotalReserve = keeper.GetRuneBalaceOfModule(ctx, ReserveName)190 }191 res, err := codec.MarshalJSONIndent(keeper.Cdc(), data)192 if err != nil {193 ctx.Logger().Error("fail to marshal vault data to json", "error", err)194 return nil, sdk.ErrInternal("fail to marshal response to json")195 }196 return res, nil197}198func queryPoolAddresses(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {199 active, err := keeper.GetAsgardVaultsByStatus(ctx, ActiveVault)200 if err != nil {201 ctx.Logger().Error("fail to get active vaults", "error", err)202 return nil, sdk.ErrInternal("fail to get active vaults")203 }204 type address struct {205 Chain common.Chain `json:"chain"`206 PubKey common.PubKey `json:"pub_key"`207 Address common.Address `json:"address"`208 }209 var resp struct {210 Current []address `json:"current"`211 }212 if len(active) > 0 {213 // select vault with lowest amount of rune214 vault := active.SelectByMinCoin(common.RuneAsset())215 chains := vault.Chains216 if len(chains) == 0 {217 chains = common.Chains{common.RuneAsset().Chain}218 }219 for _, chain := range chains {220 vaultAddress, err := vault.PubKey.GetAddress(chain)221 if err != nil {222 ctx.Logger().Error("fail to get address for chain", "error", err)223 return nil, sdk.ErrInternal("fail to get address for chain")224 }225 addr := address{226 Chain: chain,227 PubKey: vault.PubKey,228 Address: vaultAddress,229 }230 resp.Current = append(resp.Current, addr)231 }232 }233 res, err := codec.MarshalJSONIndent(keeper.Cdc(), resp)234 if err != nil {235 ctx.Logger().Error("fail to marshal current pool address to json", "error", err)236 return nil, sdk.ErrInternal("fail to marshal current pool address to json")237 }238 return res, nil239}240func queryNodeAccount(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {241 nodeAddress := path[0]242 addr, err := sdk.AccAddressFromBech32(nodeAddress)243 if err != nil {244 return nil, sdk.ErrUnknownRequest("invalid account address")245 }246 nodeAcc, err := keeper.GetNodeAccount(ctx, addr)247 if err != nil {248 return nil, sdk.ErrInternal("fail to get node accounts")249 }250 slashPts, err := keeper.GetNodeAccountSlashPoints(ctx, addr)251 if err != nil {252 return nil, sdk.ErrInternal("fail to get node slash points")253 }254 result := NewQueryNodeAccount(nodeAcc)255 result.SlashPoints = slashPts256 res, err := codec.MarshalJSONIndent(keeper.Cdc(), result)257 if err != nil {258 ctx.Logger().Error("fail to marshal node account to json", "error", err)259 return nil, sdk.ErrInternal("fail to marshal node account to json")260 }261 return res, nil262}263func queryNodeAccounts(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {264 nodeAccounts, err := keeper.ListNodeAccountsWithBond(ctx)265 if err != nil {266 return nil, sdk.ErrInternal("fail to get node accounts")267 }268 result := make([]QueryNodeAccount, len(nodeAccounts))269 for i, na := range nodeAccounts {270 slashPts, err := keeper.GetNodeAccountSlashPoints(ctx, na.NodeAddress)271 if err != nil {272 return nil, sdk.ErrInternal("fail to get node slash points")273 }274 result[i] = NewQueryNodeAccount(na)275 result[i].SlashPoints = slashPts276 }277 res, err := codec.MarshalJSONIndent(keeper.Cdc(), result)278 if err != nil {279 ctx.Logger().Error("fail to marshal observers to json", "error", err)280 return nil, sdk.ErrInternal("fail to marshal observers to json")281 }282 return res, nil283}284// queryObservers will only return all the active accounts285func queryObservers(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {286 activeAccounts, err := keeper.ListActiveNodeAccounts(ctx)287 if err != nil {288 return nil, sdk.ErrInternal("fail to get node account iterator")289 }290 result := make([]string, 0, len(activeAccounts))291 for _, item := range activeAccounts {292 result = append(result, item.NodeAddress.String())293 }294 res, err := codec.MarshalJSONIndent(keeper.Cdc(), result)295 if err != nil {296 ctx.Logger().Error("fail to marshal observers to json", "error", err)297 return nil, sdk.ErrInternal("fail to marshal observers to json")298 }299 return res, nil300}301func queryObserver(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {302 observerAddr := path[0]303 addr, err := sdk.AccAddressFromBech32(observerAddr)304 if err != nil {305 return nil, sdk.ErrUnknownRequest("invalid account address")306 }307 nodeAcc, err := keeper.GetNodeAccount(ctx, addr)308 if err != nil {309 return nil, sdk.ErrInternal("fail to get node account")310 }311 res, err := codec.MarshalJSONIndent(keeper.Cdc(), nodeAcc)312 if err != nil {313 ctx.Logger().Error("fail to marshal node account to json", "error", err)314 return nil, sdk.ErrInternal("fail to marshal node account to json")315 }316 return res, nil317}318// queryStakers319func queryStakers(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {320 asset, err := common.NewAsset(path[0])321 if err != nil {322 ctx.Logger().Error("fail to get parse asset", "error", err)323 return nil, sdk.ErrInternal("fail to parse asset")324 }325 var stakers []Staker326 iterator := keeper.GetStakerIterator(ctx, asset)327 defer iterator.Close()328 for ; iterator.Valid(); iterator.Next() {329 var staker Staker330 keeper.Cdc().MustUnmarshalBinaryBare(iterator.Value(), &staker)331 stakers = append(stakers, staker)332 }333 res, err := codec.MarshalJSONIndent(keeper.Cdc(), stakers)334 if err != nil {335 ctx.Logger().Error("fail to marshal stakers to json", "error", err)336 return nil, sdk.ErrInternal("fail to marshal stakers to json")337 }338 return res, nil339}340// nolint: unparam341func queryPool(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {342 asset, err := common.NewAsset(path[0])343 if err != nil {344 ctx.Logger().Error("fail to parse asset", "error", err)345 return nil, sdk.ErrInternal("Could not parse asset")346 }347 active, err := keeper.GetAsgardVaultsByStatus(ctx, ActiveVault)348 if err != nil {349 ctx.Logger().Error("fail to get active vaults", "error", err)350 return nil, sdk.ErrInternal("fail to get active vaults")351 }352 vault := active.SelectByMinCoin(asset)353 if vault.IsEmpty() {354 return nil, sdk.ErrInternal("Could not find active asgard vault")355 }356 addr, err := vault.PubKey.GetAddress(asset.Chain)357 if err != nil {358 return nil, sdk.ErrInternal("fail to get chain pool address")359 }360 pool, err := keeper.GetPool(ctx, asset)361 if err != nil {362 ctx.Logger().Error("fail to get pool", "error", err)363 return nil, sdk.ErrInternal("Could not get pool")364 }365 if pool.Empty() {366 return nil, sdk.ErrUnknownRequest(fmt.Sprintf("pool: %s doesn't exist", path[0]))367 }368 pool.PoolAddress = addr369 res, err := codec.MarshalJSONIndent(keeper.Cdc(), pool)370 if err != nil {371 return nil, sdk.ErrInternal("could not marshal result to JSON")372 }373 return res, nil374}375func queryPools(ctx sdk.Context, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {376 pools := QueryResPools{}377 iterator := keeper.GetPoolIterator(ctx)378 active, err := keeper.GetAsgardVaultsByStatus(ctx, ActiveVault)379 if err != nil {380 ctx.Logger().Error("fail to get active vaults", "error", err)381 return nil, sdk.ErrInternal("fail to get active vaults")382 }383 for ; iterator.Valid(); iterator.Next() {384 var pool Pool385 if err := keeper.Cdc().UnmarshalBinaryBare(iterator.Value(), &pool); err != nil {386 return nil, sdk.ErrInternal("Unmarshl: Pool")387 }388 // ignore pool if no stake units389 if pool.PoolUnits.IsZero() {390 continue391 }392 vault := active.SelectByMinCoin(pool.Asset)393 if vault.IsEmpty() {394 return nil, sdk.ErrInternal("Could not find active asgard vault")395 }396 addr, err := vault.PubKey.GetAddress(pool.Asset.Chain)397 if err != nil {398 return nil, sdk.ErrInternal("Could get address of chain")399 }400 pool.PoolAddress = addr401 pools = append(pools, pool)402 }403 res, err := codec.MarshalJSONIndent(keeper.Cdc(), pools)404 if err != nil {405 return nil, sdk.ErrInternal("could not marshal pools result to json")406 }407 return res, nil408}409func queryTxIn(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {410 hash, err := common.NewTxID(path[0])411 if err != nil {412 ctx.Logger().Error("fail to parse tx id", "error", err)413 return nil, sdk.ErrInternal("fail to parse tx id")414 }415 voter, err := keeper.GetObservedTxVoter(ctx, hash)416 if err != nil {417 ctx.Logger().Error("fail to get observed tx voter", "error", err)418 return nil, sdk.ErrInternal("fail to get observed tx voter")419 }420 nodeAccounts, err := keeper.ListActiveNodeAccounts(ctx)421 if err != nil {422 return nil, sdk.ErrInternal("fail to get node accounts")423 }424 res, err := codec.MarshalJSONIndent(keeper.Cdc(), voter.GetTx(nodeAccounts))425 if err != nil {426 ctx.Logger().Error("fail to marshal tx hash to json", "error", err)427 return nil, sdk.ErrInternal("fail to marshal tx hash to json")428 }429 return res, nil430}431func queryKeygen(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {432 var err error433 height, err := strconv.ParseInt(path[0], 0, 64)434 if err != nil {435 ctx.Logger().Error("fail to parse block height", "error", err)436 return nil, sdk.ErrInternal("fail to parse block height")437 }438 if height > ctx.BlockHeight() {439 return nil, sdk.ErrInternal("block height not available yet")440 }441 keygenBlock, err := keeper.GetKeygenBlock(ctx, height)442 if err != nil {443 ctx.Logger().Error("fail to get keygen block", "error", err)444 return nil, sdk.ErrInternal("fail to get keygen block")445 }446 if len(path) > 1 {447 pk, err := common.NewPubKey(path[1])448 if err != nil {449 ctx.Logger().Error("fail to parse pubkey", "error", err)450 return nil, sdk.ErrInternal("fail to parse pubkey")451 }452 // only return those keygen contains the request pub key453 newKeygenBlock := NewKeygenBlock(keygenBlock.Height)454 for _, keygen := range keygenBlock.Keygens {455 if keygen.Members.Contains(pk) {456 newKeygenBlock.Keygens = append(newKeygenBlock.Keygens, keygen)457 }458 }459 keygenBlock = newKeygenBlock460 }461 res, err := codec.MarshalJSONIndent(keeper.Cdc(), keygenBlock)462 if err != nil {463 ctx.Logger().Error("fail to marshal keygen block to json", "error", err)464 return nil, sdk.ErrInternal("fail to marshal keygen block to json")465 }466 return res, nil467}468func queryKeysign(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {469 var err error470 height, err := strconv.ParseInt(path[0], 0, 64)471 if err != nil {472 ctx.Logger().Error("fail to parse block height", "error", err)473 return nil, sdk.ErrInternal("fail to parse block height")474 }475 if height > ctx.BlockHeight() {476 return nil, sdk.ErrInternal("block height not available yet")477 }478 pk := common.EmptyPubKey479 if len(path) > 1 {480 pk, err = common.NewPubKey(path[1])481 if err != nil {482 ctx.Logger().Error("fail to parse pubkey", "error", err)483 return nil, sdk.ErrInternal("fail to parse pubkey")484 }485 }486 txs, err := keeper.GetTxOut(ctx, height)487 if err != nil {488 ctx.Logger().Error("fail to get tx out array from key value store", "error", err)489 return nil, sdk.ErrInternal("fail to get tx out array from key value store")490 }491 if !pk.IsEmpty() {492 newTxs := &TxOut{493 Height: txs.Height,494 }495 for _, tx := range txs.TxArray {496 if pk.Equals(tx.VaultPubKey) {497 newTxs.TxArray = append(newTxs.TxArray, tx)498 }499 }500 txs = newTxs501 }502 out := make(map[common.Chain]ResTxOut, 0)503 for _, item := range txs.TxArray {504 res, ok := out[item.Chain]505 if !ok {506 res = ResTxOut{507 Height: txs.Height,508 Chain: item.Coin.Asset.Chain,509 TxArray: make([]TxOutItem, 0),510 }511 }512 res.TxArray = append(res.TxArray, *item)513 out[item.Chain] = res514 }515 res, err := codec.MarshalJSONIndent(keeper.Cdc(), QueryResTxOut{516 Chains: out,517 })518 if err != nil {519 ctx.Logger().Error("fail to marshal tx hash to json", "error", err)520 return nil, sdk.ErrInternal("fail to marshal tx hash to json")521 }522 return res, nil523}524func isIncludeAllEvents(u *url.URL) bool {525 if u == nil {526 return false527 }528 values, ok := u.Query()["include"]529 if !ok {530 return false531 }532 for _, value := range values {533 if value == "all" {534 return true535 }536 }537 return false538}539func getEventStatusFromQuery(u *url.URL) EventStatuses {540 var result EventStatuses541 if u == nil {542 return result543 }544 values, ok := u.Query()["include"]545 if !ok {546 return result547 }548 return GetEventStatuses(values)549}550func queryEventsByTxHash(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {551 txID, err := common.NewTxID(path[0])552 if err != nil {553 ctx.Logger().Error("fail to discover tx hash", "error", err)554 return nil, sdk.ErrInternal("fail to discover tx hash")555 }556 eventIDs, err := keeper.GetEventsIDByTxHash(ctx, txID)557 if err != nil {558 errMsg := fmt.Sprintf("fail to get event ids by txhash(%s)", txID.String())559 ctx.Logger().Error(errMsg)560 return nil, sdk.ErrInternal(errMsg)561 }562 limit := 100 // limit the number of events, aka pagination563 if len(eventIDs) > 100 {564 eventIDs = eventIDs[len(eventIDs)-limit:]565 }566 events := make(Events, 0, len(eventIDs))567 for _, id := range eventIDs {568 event, err := keeper.GetEvent(ctx, id)569 if err != nil {570 errMsg := fmt.Sprintf("fail to get event(%d)", id)571 return nil, sdk.ErrInternal(errMsg)572 }573 if event.Empty() {574 break575 }576 events = append(events, event)577 }578 res, err := codec.MarshalJSONIndent(keeper.Cdc(), events)579 if err != nil {580 ctx.Logger().Error("fail to marshal events to json", "error", err)581 return nil, sdk.ErrInternal("fail to marshal events to json")582 }583 return res, nil584}585func queryCompEvents(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {586 id, err := strconv.ParseInt(path[0], 10, 64)587 if err != nil {588 ctx.Logger().Error("fail to discover id number", "error", err)589 return nil, sdk.ErrInternal("fail to discover id number")590 }591 chain := common.EmptyChain592 if len(path) > 1 && len(path[1]) > 0 {593 chain, err = common.NewChain(path[1])594 if err != nil {595 ctx.Logger().Error("fail to discover chain name", "error", err)596 return nil, sdk.ErrInternal("fail to discover chain name")597 }598 }599 u, err := getURLFromData(req.Data)600 if err != nil {601 ctx.Logger().Error(err.Error())602 }603 all := isIncludeAllEvents(u)604 es := getEventStatusFromQuery(u)605 limit := int64(100) // limit the number of events, aka pagination606 events := make(Events, 0)607 for i := id; i <= id+limit; i++ {608 event, _ := keeper.GetEvent(ctx, i)609 if all {610 events = append(events, event)611 continue612 }613 // discover the chain event614 // if no out txs, use intx chain615 // if out txs, use first non-rune chain, else use rune chain616 evtChain := event.InTx.Chain617 if len(event.OutTxs) > 0 {618 evtChain = common.RuneAsset().Chain619 for _, outTx := range event.OutTxs {620 if !outTx.Chain.IsEmpty() && !evtChain.Equals(outTx.Chain) {621 evtChain = outTx.Chain622 break623 }624 }625 }626 // if event is pending, get the chain event from memo627 if event.Status == EventPending {628 memo, _ := ParseMemo(event.InTx.Memo)629 asset := memo.GetAsset()630 if asset.Chain != "" {631 evtChain = asset.Chain632 }633 }634 if !chain.IsEmpty() && !evtChain.Equals(chain) && !evtChain.IsEmpty() {635 continue636 }637 if evtChain.IsEmpty() && !chain.IsBNB() && !chain.IsEmpty() {638 continue639 }640 if event.Empty() {641 continue642 }643 if len(es) == 0 {644 if event.Status == EventPending {645 break646 }647 events = append(events, event)648 } else {649 if es.Contains(event.Status) {650 events = append(events, event)651 }652 }653 }654 res, err := codec.MarshalJSONIndent(keeper.Cdc(), events)655 if err != nil {656 ctx.Logger().Error("fail to marshal events to json", "error", err)657 return nil, sdk.ErrInternal("fail to marshal events to json")658 }659 return res, nil660}661func queryHeights(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {662 chain := common.BNBChain663 if len(path[0]) > 0 {664 var err error665 chain, err = common.NewChain(path[0])666 if err != nil {667 ctx.Logger().Error("fail to retrieve chain", "error", err)668 return nil, sdk.ErrInternal("fail to retrieve chain")669 }670 }671 chainHeight, err := keeper.GetLastChainHeight(ctx, chain)672 if err != nil {673 return nil, sdk.ErrInternal(err.Error())674 }675 signed, err := keeper.GetLastSignedHeight(ctx)676 if err != nil {677 return nil, sdk.ErrInternal(err.Error())678 }679 res, err := codec.MarshalJSONIndent(keeper.Cdc(), QueryResHeights{680 Chain: chain,681 LastChainHeight: chainHeight,682 LastSignedHeight: signed,683 Statechain: ctx.BlockHeight(),684 })685 if err != nil {686 ctx.Logger().Error("fail to marshal events to json", "error", err)687 return nil, sdk.ErrInternal("fail to marshal events to json")688 }689 return res, nil690}691// queryTSSSigner692func queryTSSSigners(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {693 vaultPubKey := path[0]694 if len(vaultPubKey) == 0 {695 ctx.Logger().Error("empty vault pub key")696 return nil, sdk.ErrUnknownRequest("empty pool pub key")697 }698 pk, err := common.NewPubKey(vaultPubKey)699 if err != nil {700 ctx.Logger().Error("fail to parse pool pub key", "error", err)701 return nil, sdk.ErrUnknownRequest("invalid pool pub key")702 }703 // seed is the current block height, rounded down to the nearest 100th704 // This helps keep the selected nodes to be the same across blocks, but705 // also change immediately if we have a change in which nodes are active706 seed := ctx.BlockHeight() / 100707 accountAddrs, err := keeper.GetObservingAddresses(ctx)708 if err != nil {709 ctx.Logger().Error("fail to get observing addresses", "error", err)710 return nil, sdk.ErrInternal("fail to get observing addresses")711 }712 vault, err := keeper.GetVault(ctx, pk)713 if err != nil {714 ctx.Logger().Error("fail to get vault", "error", err)715 return nil, sdk.ErrInternal("fail to get vault")716 }717 signers := vault.Membership718 threshold, err := GetThreshold(len(vault.Membership))719 if err != nil {720 ctx.Logger().Error("fail to get threshold", "error", err)721 return nil, sdk.ErrInternal("fail to get threshold")722 }723 totalObservingAccounts := len(accountAddrs)724 if totalObservingAccounts > 0 && totalObservingAccounts >= threshold {725 signers, err = vault.GetMembers(accountAddrs)726 if err != nil {727 ctx.Logger().Error("fail to get signers", "error", err)728 return nil, sdk.ErrInternal("fail to get signers")729 }730 }731 // if we don't have enough signer732 if len(signers) < threshold {733 signers = vault.Membership734 }735 // if there are 9 nodes in total , it need 6 nodes to sign a message736 // 3 signer send request to thorchain at block height 100737 // another 3 signer send request to thorchain at block height 101738 // in this case we get into trouble ,they get different results, key sign is going to fail739 signerParty, err := ChooseSignerParty(signers, seed, len(vault.Membership))740 if err != nil {741 ctx.Logger().Error("fail to choose signer party members", "error", err)742 return nil, sdk.ErrInternal("fail to choose signer party members")743 }744 res, err := codec.MarshalJSONIndent(keeper.Cdc(), signerParty)745 if err != nil {746 ctx.Logger().Error("fail to marshal to json", "error", err)747 return nil, sdk.ErrInternal("fail to marshal to json")748 }749 return res, nil750}751func queryConstantValues(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {752 ver := keeper.GetLowestActiveVersion(ctx)753 constAccessor := constants.GetConstantValues(ver)754 res, err := codec.MarshalJSONIndent(keeper.Cdc(), constAccessor)755 if err != nil {756 ctx.Logger().Error("fail to marshal constant values to json", "error", err)757 return nil, sdk.ErrInternal("fail to marshal constant values to json")758 }759 return res, nil760}761func queryMimirValues(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {762 values := make(map[string]int64, 0)763 iter := keeper.GetMimirIterator(ctx)764 defer iter.Close()765 for ; iter.Valid(); iter.Next() {766 var value int64767 if err := keeper.Cdc().UnmarshalBinaryBare(iter.Value(), &value); err != nil {768 ctx.Logger().Error("fail to unmarshal mimir attribute", "error", err)769 return nil, sdk.ErrInternal("fail to unmarshal mimir attribute")770 }771 values[string(iter.Key())] = value772 }773 res, err := codec.MarshalJSONIndent(keeper.Cdc(), values)774 if err != nil {775 ctx.Logger().Error("fail to marshal mimir values to json", "error", err)776 return nil, sdk.ErrInternal("fail to marshal mimir values to json")777 }778 return res, nil779}780func queryBan(ctx sdk.Context, path []string, req abci.RequestQuery, keeper Keeper) ([]byte, sdk.Error) {781 addr, err := sdk.AccAddressFromBech32(path[0])782 if err != nil {783 ctx.Logger().Error("invalid node address", "error", err)784 return nil, sdk.ErrInternal("invalid node address")785 }786 ban, err := keeper.GetBanVoter(ctx, addr)787 if err != nil {788 ctx.Logger().Error("fail to get ban voter", "error", err)789 return nil, sdk.ErrInternal("fail to get ban voter")790 }791 res, err := codec.MarshalJSONIndent(keeper.Cdc(), ban)792 if err != nil {793 ctx.Logger().Error("fail to marshal ban voter to json", "error", err)794 return nil, sdk.ErrInternal("fail to ban voter to json")795 }796 return res, nil797}...

Full Screen

Full Screen

configParser.go

Source:configParser.go Github

copy

Full Screen

...21}22func parseMysql() {23 config.MysqlConfig = conf.Get("mysql")24 if config.MysqlConfig == nil {25 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no mysql section").Fatal()26 }27 Mysql = mysql{}28 Mysql.ID, err = config.MysqlConfig.String("id")29 if err != nil {30 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()31 }32 Mysql.Address, err = config.MysqlConfig.String("address")33 if err != nil {34 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()35 }36 Mysql.Port, err = config.MysqlConfig.Int("port")37 if err != nil {38 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()39 }40 Mysql.Database, err = config.MysqlConfig.String("database")41 if err != nil {42 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()43 }44 Mysql.ConnectionRetryCount, err = config.MysqlConfig.Int("connection_retry_count")45 if err != nil {46 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()47 }48 Mysql.ConnectionRetryIntervalMs, err = config.MysqlConfig.Int("connection_retry_interval_ms")49 if err != nil {50 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()51 }52}53func parseGrpc() {54 config.GrpcConfig = conf.Get("grpc")55 if config.GrpcConfig == nil {56 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no grpc section").Fatal()57 }58 Grpc.Port, err = config.GrpcConfig.Int("port")59 if err != nil {60 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()61 }62 Grpc.ClientPingIntervalMs, err = config.GrpcConfig.Int("client_ping_interval_ms")63 if err != nil {64 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()65 }66 Grpc.ClientPingTimeoutMs, err = config.GrpcConfig.Int("client_ping_timeout_ms")67 if err != nil {68 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()69 }70}71func parseGraphQL() {72 config.GraphQLConfig = conf.Get("graphql")73 if config.GraphQLConfig == nil {74 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no graphql section").Fatal()75 }76 GraphQL = graphql{}77 GraphQL.ProductionListenPort, err = config.GraphQLConfig.Int("production_listen_port")78 if err != nil {79 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()80 }81 GraphQL.DevInternalListenPort, err = config.GraphQLConfig.Int("dev_internal_listen_port")82 if err != nil {83 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()84 }85 GraphQL.DevInternalUsePlayground, _ = config.GraphQLConfig.Bool("dev_internal_use_playground")86 GraphQL.SubscriptionInterval, err = config.GraphQLConfig.Int("subscription_interval_ms")87 if err != nil {88 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()89 }90}91func parseHorn() {92 config.HornConfig = conf.Get("horn")93 if config.HornConfig == nil {94 logger.Logger.Panicln("no horn section")95 }96 Horn = horn{}97 Horn.ServerAddress, err = config.HornConfig.String("horn_server_address")98 if err != nil {99 logger.Logger.Panicln(err)100 }101 Horn.ServerPort, err = config.HornConfig.Int("horn_server_port")102 if err != nil {103 logger.Logger.Panicln(err)104 }105 Horn.ConnectionTimeOutMs, err = config.HornConfig.Int("horn_connection_timeout_ms")106 if err != nil {107 logger.Logger.Panicln(err)108 }109 Horn.ConnectionRetryCount, err = config.HornConfig.Int("horn_connection_retry_count")110 if err != nil {111 logger.Logger.Panicln(err)112 }113 Horn.RequestTimeoutMs, err = config.HornConfig.Int("horn_request_timeout_ms")114 if err != nil {115 logger.Logger.Panicln(err)116 }117}118func parseFlute() {119 config.FluteConfig = conf.Get("flute")120 if config.FluteConfig == nil {121 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no flute section").Fatal()122 }123 Flute = flute{}124 Flute.ServerAddress, err = config.FluteConfig.String("flute_server_address")125 if err != nil {126 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()127 }128 Flute.ServerPort, err = config.FluteConfig.Int("flute_server_port")129 if err != nil {130 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()131 }132 Flute.RequestTimeoutMs, err = config.FluteConfig.Int("flute_request_timeout_ms")133 if err != nil {134 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()135 }136}137func parseCello() {138 config.CelloConfig = conf.Get("cello")139 if config.CelloConfig == nil {140 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no cello section").Fatal()141 }142 Cello = cello{}143 Cello.ServerAddress, err = config.CelloConfig.String("cello_server_address")144 if err != nil {145 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()146 }147 Cello.ServerPort, err = config.CelloConfig.Int("cello_server_port")148 if err != nil {149 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()150 }151 Cello.RequestTimeoutMs, err = config.CelloConfig.Int("cello_request_timeout_ms")152 if err != nil {153 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()154 }155}156func parseHarp() {157 config.HarpConfig = conf.Get("harp")158 if config.HarpConfig == nil {159 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no harp section").Fatal()160 }161 Harp = harp{}162 Harp.ServerAddress, err = config.HarpConfig.String("harp_server_address")163 if err != nil {164 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()165 }166 Harp.ServerPort, err = config.HarpConfig.Int("harp_server_port")167 if err != nil {168 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()169 }170 Harp.RequestTimeoutMs, err = config.HarpConfig.Int("harp_request_timeout_ms")171 if err != nil {172 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()173 }174}175func parseViolin() {176 config.ViolinConfig = conf.Get("violin")177 if config.ViolinConfig == nil {178 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no violin section").Fatal()179 }180 Violin = violin{}181 Violin.ServerAddress, err = config.ViolinConfig.String("violin_server_address")182 if err != nil {183 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()184 }185 Violin.ServerPort, err = config.ViolinConfig.Int("violin_server_port")186 if err != nil {187 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()188 }189 Violin.RequestTimeoutMs, err = config.ViolinConfig.Int("violin_request_timeout_ms")190 if err != nil {191 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()192 }193}194func parseViolinNoVnc() {195 config.ViolinNoVncConfig = conf.Get("violinnovnc")196 if config.ViolinNoVncConfig == nil {197 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no violinnovnc section").Fatal()198 }199 ViolinNoVnc = violinNoVnc{}200 ViolinNoVnc.ServerAddress, err = config.ViolinNoVncConfig.String("violinnovnc_server_address")201 if err != nil {202 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()203 }204 ViolinNoVnc.ServerPort, err = config.ViolinNoVncConfig.Int("violinnovnc_server_port")205 if err != nil {206 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()207 }208 ViolinNoVnc.RequestTimeoutMs, err = config.ViolinNoVncConfig.Int("violinnovnc_request_timeout_ms")209 if err != nil {210 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()211 }212}213func parsePiano() {214 config.PianoConfig = conf.Get("piano")215 if config.PianoConfig == nil {216 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no piano section").Fatal()217 }218 Piano = piano{}219 Piano.ServerAddress, err = config.PianoConfig.String("piano_server_address")220 if err != nil {221 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()222 }223 Piano.ServerPort, err = config.PianoConfig.Int("piano_server_port")224 if err != nil {225 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()226 }227 Piano.RequestTimeoutMs, err = config.PianoConfig.Int("piano_request_timeout_ms")228 if err != nil {229 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()230 }231}232func parseTuba() {233 config.TubaConfig = conf.Get("tuba")234 if config.TubaConfig == nil {235 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no tuba section").Fatal()236 }237 Tuba = tuba{}238 Tuba.ServerPort, err = config.TubaConfig.Int("tuba_server_port")239 if err != nil {240 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()241 }242 Tuba.RequestTimeoutMs, err = config.TubaConfig.Int("tuba_request_timeout_ms")243 if err != nil {244 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()245 }246}247func parseTimpani() {248 config.TimpaniConfig = conf.Get("timpani")249 if config.TimpaniConfig == nil {250 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no timpani section").Fatal()251 }252 Timpani = timpani{}253 Timpani.ServerAddress, err = config.TimpaniConfig.String("timpani_server_address")254 if err != nil {255 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()256 }257 Timpani.ServerPort, err = config.TimpaniConfig.Int("timpani_server_port")258 if err != nil {259 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()260 }261 Timpani.RequestTimeoutMs, err = config.TimpaniConfig.Int("timpani_request_timeout_ms")262 if err != nil {263 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()264 }265}266func parseUser() {267 config.UserConfig = conf.Get("user")268 if config.UserConfig == nil {269 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, "no user section").Fatal()270 }271 User = user{}272 User.TokenExpirationTimeMinutes, err = config.UserConfig.Int("token_expiration_time_minutes")273 if err != nil {274 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()275 }276}277// Init : Parse config file and initialize config structure278func Init() {279 if err = conf.Parse(configLocation); err != nil {280 hcc_errors.NewHccError(hcc_errors.PiccoloInternalInitFail, err.Error()).Fatal()281 }282 parseRsakey()283 parseMysql()284 parseGrpc()285 parseGraphQL()286 parseHorn()287 parseFlute()288 parseCello()289 parseHarp()290 parseViolin()291 parseViolinNoVnc()292 parsePiano()293 parseTuba()294 parseUser()...

Full Screen

Full Screen

serv.go

Source:serv.go Github

copy

Full Screen

...97 cmd := os.Getenv("SSH_ORIGINAL_COMMAND")98 if len(cmd) == 0 {99 key, user, err := private.ServNoCommand(keyID)100 if err != nil {101 fail("Internal error", "Failed to check provided key: %v", err)102 }103 if key.Type == models.KeyTypeDeploy {104 println("Hi there! You've successfully authenticated with the deploy key named " + key.Name + ", but Gitea does not provide shell access.")105 } else {106 println("Hi there, " + user.Name + "! You've successfully authenticated with the key named " + key.Name + ", but Gitea does not provide shell access.")107 }108 println("If this is unexpected, please log in with password and setup Gitea under another user.")109 return nil110 }111 verb, args := parseCmd(cmd)112 var lfsVerb string113 if verb == lfsAuthenticateVerb {114 if !setting.LFS.StartServer {115 fail("Unknown git command", "LFS authentication request over SSH denied, LFS support is disabled")116 }117 argsSplit := strings.Split(args, " ")118 if len(argsSplit) >= 2 {119 args = strings.TrimSpace(argsSplit[0])120 lfsVerb = strings.TrimSpace(argsSplit[1])121 }122 }123 repoPath := strings.ToLower(strings.Trim(args, "'"))124 rr := strings.SplitN(repoPath, "/", 2)125 if len(rr) != 2 {126 fail("Invalid repository path", "Invalid repository path: %v", args)127 }128 username := strings.ToLower(rr[0])129 reponame := strings.ToLower(strings.TrimSuffix(rr[1], ".git"))130 if alphaDashDotPattern.MatchString(reponame) {131 fail("Invalid repo name", "Invalid repo name: %s", reponame)132 }133 if setting.EnablePprof || c.Bool("enable-pprof") {134 if err := os.MkdirAll(setting.PprofDataPath, os.ModePerm); err != nil {135 fail("Error while trying to create PPROF_DATA_PATH", "Error while trying to create PPROF_DATA_PATH: %v", err)136 }137 stopCPUProfiler, err := pprof.DumpCPUProfileForUsername(setting.PprofDataPath, username)138 if err != nil {139 fail("Internal Server Error", "Unable to start CPU profile: %v", err)140 }141 defer func() {142 stopCPUProfiler()143 err := pprof.DumpMemProfileForUsername(setting.PprofDataPath, username)144 if err != nil {145 fail("Internal Server Error", "Unable to dump Mem Profile: %v", err)146 }147 }()148 }149 requestedMode, has := allowedCommands[verb]150 if !has {151 fail("Unknown git command", "Unknown git command %s", verb)152 }153 if verb == lfsAuthenticateVerb {154 if lfsVerb == "upload" {155 requestedMode = models.AccessModeWrite156 } else if lfsVerb == "download" {157 requestedMode = models.AccessModeRead158 } else {159 fail("Unknown LFS verb", "Unknown lfs verb %s", lfsVerb)160 }161 }162 results, err := private.ServCommand(keyID, username, reponame, requestedMode, verb, lfsVerb)163 if err != nil {164 if private.IsErrServCommand(err) {165 errServCommand := err.(private.ErrServCommand)166 if errServCommand.StatusCode != http.StatusInternalServerError {167 fail("Unauthorized", "%s", errServCommand.Error())168 } else {169 fail("Internal Server Error", "%s", errServCommand.Error())170 }171 }172 fail("Internal Server Error", "%s", err.Error())173 }174 os.Setenv(models.EnvRepoIsWiki, strconv.FormatBool(results.IsWiki))175 os.Setenv(models.EnvRepoName, results.RepoName)176 os.Setenv(models.EnvRepoUsername, results.OwnerName)177 os.Setenv(models.EnvPusherName, results.UserName)178 os.Setenv(models.EnvPusherID, strconv.FormatInt(results.UserID, 10))179 os.Setenv(models.ProtectedBranchRepoID, strconv.FormatInt(results.RepoID, 10))180 os.Setenv(models.ProtectedBranchPRID, fmt.Sprintf("%d", 0))181 os.Setenv(models.EnvIsDeployKey, fmt.Sprintf("%t", results.IsDeployKey))182 os.Setenv(models.EnvKeyID, fmt.Sprintf("%d", results.KeyID))183 //LFS token authentication184 if verb == lfsAuthenticateVerb {185 url := fmt.Sprintf("%s%s/%s.git/info/lfs", setting.AppURL, url.PathEscape(results.OwnerName), url.PathEscape(results.RepoName))186 now := time.Now()187 claims := lfs.Claims{188 StandardClaims: jwt.StandardClaims{189 ExpiresAt: now.Add(setting.LFS.HTTPAuthExpiry).Unix(),190 NotBefore: now.Unix(),191 },192 RepoID: results.RepoID,193 Op: lfsVerb,194 UserID: results.UserID,195 }196 token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)197 // Sign and get the complete encoded token as a string using the secret198 tokenString, err := token.SignedString(setting.LFS.JWTSecretBytes)199 if err != nil {200 fail("Internal error", "Failed to sign JWT token: %v", err)201 }202 tokenAuthentication := &models.LFSTokenResponse{203 Header: make(map[string]string),204 Href: url,205 }206 tokenAuthentication.Header["Authorization"] = fmt.Sprintf("Bearer %s", tokenString)207 enc := json.NewEncoder(os.Stdout)208 err = enc.Encode(tokenAuthentication)209 if err != nil {210 fail("Internal error", "Failed to encode LFS json response: %v", err)211 }212 return nil213 }214 // Special handle for Windows.215 if setting.IsWindows {216 verb = strings.Replace(verb, "-", " ", 1)217 }218 var gitcmd *exec.Cmd219 verbs := strings.Split(verb, " ")220 if len(verbs) == 2 {221 gitcmd = exec.Command(verbs[0], verbs[1], repoPath)222 } else {223 gitcmd = exec.Command(verb, repoPath)224 }225 gitcmd.Dir = setting.RepoRootPath226 gitcmd.Stdout = os.Stdout227 gitcmd.Stdin = os.Stdin228 gitcmd.Stderr = os.Stderr229 if err = gitcmd.Run(); err != nil {230 fail("Internal error", "Failed to execute git command: %v", err)231 }232 // Update user key activity.233 if results.KeyID > 0 {234 if err = private.UpdatePublicKeyInRepo(results.KeyID, results.RepoID); err != nil {235 fail("Internal error", "UpdatePublicKeyInRepo: %v", err)236 }237 }238 return nil239}...

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4}5import (6func main() {7 fmt.Println("Hello, playground")8}9import (10func main() {11 fmt.Println("Hello, playground")12}13import (14func main() {15 fmt.Println("Hello, playground")16}17import (18func main() {19 fmt.Println("Hello, playground")20}21import (22func main() {23 fmt.Println("Hello, playground")24}25import (26func main() {27 fmt.Println("Hello, playground")28}29import (30func main() {31 fmt.Println("Hello, playground")32}33import (34func main() {35 fmt.Println("Hello, playground")36}37import (38func main() {39 fmt.Println("Hello, playground")40}41import (42func main() {43 fmt.Println("Hello, playground")44}45import (46func main() {

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 internal.Fail()5}6import (7func main() {8 fmt.Println("Hello, playground")9 internal.Fail()10}11import (12func Fail() {13 fmt.Println("Internal Fail")14}15import (16func TestFail(t *testing.T) {17 Fail()18}19import (20func main() {21 fmt.Println("Hello, playground")22 internal.Fail()23}24import (25func TestMain(t *testing.T) {26 main()27}28import (29func main() {30 fmt.Println("Hello, playground")31 internal.Fail()32}33import (34func TestSub1(t *testing.T) {35 main()36}37import (38func main() {39 fmt.Println("Hello, playground")40 internal.Fail()41}42import (43func TestSub2(t *testing.T) {44 main()45}46--- PASS: TestFail (0.00s)47--- PASS: TestMain (0.00s)48--- PASS: TestSub1 (0.00s)

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello, playground")4 _1.Fail()5}6func Fail() {7 fmt.Println("Fail")8}9import "testing"10func TestFail(t *testing.T) {11 Fail()12}

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 internal.Fail()5}6import "fmt"7func Fail() {8 fmt.Println("Internal Fail")9}10import (11func main() {12 fmt.Println("Hello World!")13 internal.Fail()14}15import (16func main() {17 fmt.Println("Hello World!")18 internal.Fail()19}20import (21func main() {22 fmt.Println("Hello World!")23 internal.Fail()24}

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("In 1.go")4 internal.Fail()5}6import (7func main() {8 fmt.Println("In 2.go")9 internal.Fail()10}11import "fmt"12func Fail() {13 fmt.Println("In internal.go")14}15In this example, I have created a package named myapp which has two files 1.go and 2.go. Each of these files imports the internal package and calls the Fail method. Now, if you try to run go build myapp/..., you will get the following error:

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 xyz.Fail()5}6import (7func main() {8 fmt.Println("Hello World!")9 xyz.Fail()10}11import (12func main() {13 fmt.Println("Hello World!")14 xyz.Fail()15}16import (17func main() {18 fmt.Println("Hello World!")19 xyz.Fail()20}21import (22func main() {23 fmt.Println("Hello World!")24 xyz.Fail()25}26import (27func main() {28 fmt.Println("Hello World!")29 xyz.Fail()30}31import (32func main() {33 fmt.Println("Hello World!")34 xyz.Fail()35}36import (37func main() {38 fmt.Println("Hello World!")39 xyz.Fail()40}41import (42func main() {43 fmt.Println("Hello World!")44 xyz.Fail()45}46import (47func main() {48 fmt.Println("Hello World!")

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import "internal/1/internal.go"2func main() {3 internal.Fail()4}5func Fail() {6 panic("fail")7}8main.main()9internal.Fail()10main.main()11internal.Fail()12main.main()13internal.Fail()14main.main()15internal.Fail()16main.main()17internal.Fail()18main.main()19internal.Fail()20main.main()

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World")4 goltest.Fail("This is a test failure")5}6import (7func main() {8 fmt.Println("Hello World")9 goltest.Fail("This is a test failure")10}11import (12func main() {13 fmt.Println("Hello World")14 goltest.Fail("This is a test failure")15}16import (17func main() {18 fmt.Println("Hello World")19 goltest.Fail("This is a test failure")20}21import (22func main() {23 fmt.Println("Hello World")24 goltest.Fail("This is a test failure")25}26import (27func main() {28 fmt.Println("Hello World")29 goltest.Fail("This is a test failure")30}31import (32func main() {33 fmt.Println("Hello World")34 goltest.Fail("This is a test failure")35}36import (37func main() {38 fmt.Println("Hello World")39 goltest.Fail("This is a test failure")40}

Full Screen

Full Screen

Fail

Using AI Code Generation

copy

Full Screen

1import (2func main() {3 fmt.Println("Hello World!")4 var x = new(abc.Abc)5 x.Fail()6}7import (8type Abc struct {9}10func (a Abc) Fail() {11 fmt.Println("Fail!")12}

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Ginkgo automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Most used method in

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful