rosetta-lbry/bitcoin/node.go

104 lines
2.3 KiB
Go
Raw Normal View History

2020-09-16 21:03:14 +02:00
// Copyright 2020 Coinbase, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2020-11-17 09:20:36 +01:00
package lbry
2020-09-16 21:03:14 +02:00
import (
"bufio"
"context"
"fmt"
"io"
"os"
"os/exec"
"strings"
2020-11-17 09:20:36 +01:00
"github.com/lbryio/rosetta-lbry/utils"
2020-09-16 21:03:14 +02:00
"golang.org/x/sync/errgroup"
)
const (
2020-11-17 09:20:36 +01:00
lbrydLogger = "lbryd"
lbrydStdErrLogger = "lbryd stderr"
2020-09-16 21:03:14 +02:00
)
func logPipe(ctx context.Context, pipe io.ReadCloser, identifier string) error {
logger := utils.ExtractLogger(ctx, identifier)
reader := bufio.NewReader(pipe)
for {
str, err := reader.ReadString('\n')
if err != nil {
logger.Warnw("closing logger", "error", err)
return err
}
message := strings.ReplaceAll(str, "\n", "")
2020-09-16 21:03:14 +02:00
messages := strings.SplitAfterN(message, " ", 2)
// Trim the timestamp from the log if it exists
if len(messages) > 1 {
message = messages[1]
}
2020-11-17 09:20:36 +01:00
// Print debug log if from lbrydLogger
if identifier == lbrydLogger {
2020-09-16 21:03:14 +02:00
logger.Debugw(message)
continue
}
logger.Warnw(message)
}
}
2020-11-17 09:20:36 +01:00
// Startlbryd starts a lbryd daemon in another goroutine
2020-09-16 21:03:14 +02:00
// and logs the results to the console.
2020-11-17 09:20:36 +01:00
func Startlbryd(ctx context.Context, configPath string, g *errgroup.Group) error {
logger := utils.ExtractLogger(ctx, "lbryd")
2020-09-16 21:03:14 +02:00
cmd := exec.Command(
2020-11-17 09:20:36 +01:00
"/app/lbryd",
2020-09-16 21:03:14 +02:00
fmt.Sprintf("--conf=%s", configPath),
) // #nosec G204
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
g.Go(func() error {
2020-11-17 09:20:36 +01:00
return logPipe(ctx, stdout, lbrydLogger)
2020-09-16 21:03:14 +02:00
})
g.Go(func() error {
2020-11-17 09:20:36 +01:00
return logPipe(ctx, stderr, lbrydStdErrLogger)
2020-09-16 21:03:14 +02:00
})
if err := cmd.Start(); err != nil {
2020-11-17 09:20:36 +01:00
return fmt.Errorf("%w: unable to start lbryd", err)
2020-09-16 21:03:14 +02:00
}
g.Go(func() error {
<-ctx.Done()
2020-11-17 09:20:36 +01:00
logger.Warnw("sending interrupt to lbryd")
2020-09-16 21:03:14 +02:00
return cmd.Process.Signal(os.Interrupt)
})
return cmd.Wait()
}