func newPreorderedLogClient(
	ctx context.Context,
	conn *grpc.ClientConn,
	cfg *configpb.MigrationConfig,
) (*core.PreorderedLogClient, error) {
	admin := trillian.NewTrillianAdminClient(conn)
	gt := trillian.GetTreeRequest{TreeId: cfg.LogId}
	tree, err := admin.GetTree(ctx, &gt)
	if err != nil {
		return nil, err
	}
	log := trillian.NewTrillianLogClient(conn)
	pref := fmt.Sprintf("%d", cfg.LogId)
	return core.NewPreorderedLogClient(log, tree, cfg.IdentityFunction, pref)
}
newPreorderedLogClient creates a PreorderedLogClient for the specified tree.
package main
import (
	"context"
	"errors"
	"flag"
	"fmt"
	"net/http"
	"os"
	"strings"
	"time"
	"github.com/golang/glog"
	clientv3 "go.etcd.io/etcd/client/v3"
	"google.golang.org/grpc"
	"github.com/google/certificate-transparency-go/client"
	"github.com/google/certificate-transparency-go/jsonclient"
	"github.com/google/certificate-transparency-go/trillian/migrillian/configpb"
	"github.com/google/certificate-transparency-go/trillian/migrillian/core"
	"github.com/google/trillian"
	"github.com/google/trillian/monitoring"
	"github.com/google/trillian/monitoring/prometheus"
	"github.com/google/trillian/util"
	"github.com/google/trillian/util/election2"
	etcdelect "github.com/google/trillian/util/election2/etcd"
	"github.com/prometheus/client_golang/prometheus/promhttp"
)
var (
	cfgPath = flag.String("config", "", "Path to migration config file")
	forceMaster   = flag.Bool("force_master", false, "If true, assume master for all logs")
	etcdServers   = flag.String("etcd_servers", "", "A comma-separated list of etcd servers; no etcd registration if empty")
	lockDir       = flag.String("lock_file_path", "/migrillian/master", "etcd lock file directory path")
	electionDelay = flag.Duration("election_delay", 0, "Max random pause before participating in master election")
	backend       = flag.String("backend", "", "GRPC endpoing to connect to Trillian logservers")
	metricsEndpoint = flag.String("metrics_endpoint", "localhost:8099", "Endpoint for serving metrics")
	maxIdleConnsPerHost = flag.Int("max_idle_conns_per_host", 10, "Max idle HTTP connections per host (0 = DefaultMaxIdleConnsPerHost)")
	maxIdleConns        = flag.Int("max_idle_conns", 100, "Max number of idle HTTP connections across all hosts (0 = unlimited)")
)
func main() {
	flag.Parse()
	glog.CopyStandardLogTo("WARNING")
	defer glog.Flush()
	if *backend == "" {
		glog.Exit("--backend flag must be specified")
	}
	cfg, err := getConfig()
	if err != nil {
		glog.Exitf("Failed to load MigrillianConfig: %v", err)
	}
	if err := core.ValidateConfig(cfg); err != nil {
		glog.Exitf("Failed to validate MigrillianConfig: %v", err)
	}
	glog.Infof("Dialling Trillian backend: %v", *backend)
	conn, err := grpc.Dial(*backend, grpc.WithInsecure(), grpc.WithBlock())
	if err != nil {
		glog.Exitf("Could not dial Trillian server: %v: %v", *backend, err)
	}
	defer conn.Close()
	httpClient := getHTTPClient()
	mf := prometheus.MetricFactory{}
	ef, closeFn := getElectionFactory()
	defer closeFn()
	ctx := context.Background()
	var ctrls []*core.Controller
	for _, mc := range cfg.MigrationConfigs.Config {
		ctrl, err := getController(ctx, mc, httpClient, mf, ef, conn)
		if err != nil {
			glog.Exitf("Failed to create Controller for %q: %v", mc.SourceUri, err)
		}
		ctrls = append(ctrls, ctrl)
	}
	http.Handle("/metrics", promhttp.Handler())
	go func() {
		err := http.ListenAndServe(*metricsEndpoint, nil)
		glog.Fatalf("http.ListenAndServe(): %v", err)
	}()
	cctx, cancel := context.WithCancel(ctx)
	defer cancel()
	go util.AwaitSignal(cctx, cancel)
	core.RunMigration(cctx, ctrls)
}
func getController(
	ctx context.Context,
	cfg *configpb.MigrationConfig,
	httpClient *http.Client,
	mf monitoring.MetricFactory,
	ef election2.Factory,
	conn *grpc.ClientConn,
) (*core.Controller, error) {
	ctOpts := jsonclient.Options{PublicKeyDER: cfg.PublicKey.Der, UserAgent: "ct-go-migrillian/1.0"}
	ctClient, err := client.New(cfg.SourceUri, httpClient, ctOpts)
	if err != nil {
		return nil, fmt.Errorf("failed to create CT client: %v", err)
	}
	plClient, err := newPreorderedLogClient(ctx, conn, cfg)
	if err != nil {
		return nil, fmt.Errorf("failed to create PreorderedLogClient: %v", err)
	}
	opts := core.OptionsFromConfig(cfg)
	opts.StartDelay = *electionDelay
	return core.NewController(opts, ctClient, plClient, ef, mf), nil
}
func getConfig() (*configpb.MigrillianConfig, error) {
	if len(*cfgPath) == 0 {
		return nil, errors.New("config file not specified")
	}
	cfg, err := core.LoadConfigFromFile(*cfgPath)
	if err != nil {
		return nil, err
	}
	return cfg, nil
}
func getHTTPClient() *http.Client {
	transport := &http.Transport{
		TLSHandshakeTimeout:   30 * time.Second,
		DisableKeepAlives:     false,
		MaxIdleConns:          *maxIdleConns,
		MaxIdleConnsPerHost:   *maxIdleConnsPerHost,
		IdleConnTimeout:       90 * time.Second,
		ResponseHeaderTimeout: 30 * time.Second,
		ExpectContinueTimeout: 1 * time.Second,
	}
	return &http.Client{
		Timeout:   10 * time.Second,
		Transport: transport,
	}
}