func NewStatus(log logging.Logger, mg MachineGetter) *Status { return &Status{ Log: log.New("status"), MachineGetter: mg, HTTPClient: defaultHTTPClient, } }
// MachineListCommand returns list of remote machines belonging to the user or // that can be accessed by her. func MachineListCommand(c *cli.Context, log logging.Logger, _ string) (int, error) { // List command doesn't support identifiers. idents, err := getIdentifiers(c) if err != nil { return 1, err } if err := identifiersLimit(idents, 0, 0); err != nil { return 1, err } opts := &machine.ListOptions{ Log: log.New("machine:list"), } infos, err := machine.List(opts) if err != nil { return 1, err } if c.Bool("json") { enc := json.NewEncoder(os.Stdout) enc.SetIndent("", "\t") enc.Encode(infos) return 0, nil } tabFormatter(os.Stdout, infos) return 0, nil }
// NewRecordManager creates a RecordManager func NewRecordManager(session *session.Session, log logging.Logger, region string, hostedZoneConf HostedZone) *RecordManager { return &RecordManager{ route53: route53.New(session), log: log.New("recordmanager"), region: region, hostedZoneConf: hostedZoneConf, } }
func NewPagerduty(pc *PagerdutyConfig, log logging.Logger) (*Pagerduty, error) { return &Pagerduty{ publicURL: pc.PublicURL, integrationURL: pc.IntegrationURL, log: log.New(PAGERDUTY), }, nil }
func NewErrorCommand(stdout io.Writer, log logging.Logger, err error, msg string) *ErrorCommand { return &ErrorCommand{ Stdout: util.NewFprint(stdout), Log: log.New("errorCommand"), Message: msg, Error: err, } }
func NewDefaultHealthChecker(l kodinglogging.Logger) *HealthChecker { return &HealthChecker{ Log: l.New("HealthChecker"), HTTPClient: defaultClient, LocalKlientAddress: config.Konfig.Endpoints.Klient.Private.String(), KontrolAddress: config.Konfig.Endpoints.Kontrol().Public.String(), InternetCheckAddress: config.Konfig.Endpoints.KlientLatest.Public.String(), TunnelKiteAddress: config.Konfig.Endpoints.Tunnel.Public.String(), } }
// RestartCommand stops and starts klient. If Klient is not running to begin // with, it *just* starts klient. func RestartCommand(c *cli.Context, log logging.Logger, _ string) int { if len(c.Args()) != 0 { cli.ShowCommandHelp(c, "restart") return 1 } log = log.New("cmd:restart") s, err := newService(nil) if err != nil { log.Error("Error creating Service. err:%s", err) fmt.Println(GenericInternalNewCodeError) return 1 } fmt.Printf("Restarting the %s, this may take a moment...\n", config.KlientName) klientWasRunning := IsKlientRunning(config.Konfig.Endpoints.Klient.Private.String()) if klientWasRunning { // If klient is running, stop it, and tell the user if we fail if err := s.Stop(); err != nil { log.Error("Error stopping Service. err:%s", err) fmt.Println(FailedStopKlient) return 1 } } else { // If klient appears to not be running, try to stop it anyway. However, // because it may not actually be running, don't inform the user if we fail here. s.Stop() } err = WaitUntilStopped(config.Konfig.Endpoints.Klient.Private.String(), CommandAttempts, CommandWaitTime) if err != nil { log.Error( "Timed out while waiting for Klient to start. attempts:%d, err:%s", 5, err, ) fmt.Println(FailedStopKlient) return 1 } if klientWasRunning { fmt.Println("Stopped successfully.") } // No UX message needed, startKlient will do that itself. if err := startKlient(log, s); err != nil { log.Error("failed to start klient: %s", err) return 1 } fmt.Printf("Successfully restarted %s\n", config.KlientName) return 0 }
func newCommand(cwd string, log logging.Logger) *command { cmd := &command{ cwd: cwd, } if log != nil { cmd.log = log.New(cwd) } return cmd }
// fetchHostedZone fetches all hosted zones from account and iterates over them // until it finds the respective one func (r *RecordManager) fetchHostedZone(hostedZoneLogger logging.Logger) error { const maxIterationCount = 100 iteration := 0 // for pagination var nextMarker *string // try to get our hosted zone for { // just be paranoid about remove api calls, dont harden too much if iteration == maxIterationCount { return errors.New("iteration terminated") } log := hostedZoneLogger.New("iteration", iteration) iteration++ log.Debug("Fetching hosted zone") listHostedZonesResp, err := r.route53.ListHostedZones( &route53.ListHostedZonesInput{ Marker: nextMarker, }, // we dont have anything to filter ) if err != nil { return err } if listHostedZonesResp == nil || listHostedZonesResp.HostedZones == nil { return errors.New("malformed response - reponse or hosted zone is nil") } for _, hostedZone := range listHostedZonesResp.HostedZones { if hostedZone == nil || hostedZone.CallerReference == nil { continue } if *hostedZone.CallerReference == r.hostedZoneConf.CallerReference { r.hostedZone = hostedZone return nil } } // if our result set is truncated we can try to fetch again, but if we // reach to end, nothing to do left if listHostedZonesResp.IsTruncated == nil || !*listHostedZonesResp.IsTruncated { return errHostedZoneNotFound } // assign next marker nextMarker = listHostedZonesResp.NextMarker } }
func NewPivotal(pc *PivotalConfig, log logging.Logger) (*Pivotal, error) { if pc.ServerURL == "" { pc.ServerURL = PivotalServerURL } return &Pivotal{ serverURL: pc.ServerURL, publicURL: pc.PublicURL, integrationURL: pc.IntegrationURL, log: log.New(PIVOTAL), }, nil }
// NewLifeCycle creates a new lifecycle management system, everything begins // with an autoscaling resource, we are listening to any change on that // resource, to be able to listen them we are attaching a notification // configuration to given autoscaling resource, notification configuration works // with a TopicARN, which is basically a SNS Topic, to be able to listen from a // Topic ARN we need a SQS, SQS is attached to Notification Topic and configured // to pass events as soon as they occur, it also has re- try mechanism. One // event only be handled by one manager, there wont be any race condition on // processing that particular message. Manager is idempotent, if any given // resource doesnt exist in the given AWS system, it will create or re-use the // previous ones func NewLifeCycle(session *session.Session, log logging.Logger, asgName string) *LifeCycle { return &LifeCycle{ closed: false, closeChan: make(chan chan struct{}), ec2: ec2.New(session), sqs: sqs.New(session), sns: sns.New(session), autoscaling: autoscaling.New(session), asgName: &asgName, log: log.New("lifecycle"), } }
// createHostedZone creates hosted zone and makes sure that it is in to be used // state func (r *RecordManager) createHostedZone(hostedZoneLogger logging.Logger) error { hostedZoneLogger.Debug("create hosted zone started") // CreateHostedZone is not idempotent, multiple calls to this function // result in duplicate records, fyi resp, err := r.route53.CreateHostedZone(&route53.CreateHostedZoneInput{ CallerReference: aws.String(r.hostedZoneConf.CallerReference), Name: aws.String(r.hostedZoneConf.Name), HostedZoneConfig: &route53.HostedZoneConfig{ Comment: aws.String(hostedZoneComment), }, }) if err != nil { return err } if resp == nil || resp.ChangeInfo == nil { return errors.New("malformed response, resp is nil") } deadline := time.After(time.Minute * 5) // at most i've seen ~3min check := time.NewTicker(time.Second * 3) for { select { case <-deadline: return errDeadlineReachedForChangeInfo case <-check.C: hostedZoneLogger.New("changeInfoID", *resp.ChangeInfo.Id).Debug("fetching latest status") getChangeResp, err := r.route53.GetChange(&route53.GetChangeInput{ Id: resp.ChangeInfo.Id, }) if err != nil { return err } if getChangeResp == nil || getChangeResp.ChangeInfo == nil { return errors.New("malformed response, getChangeResp is nil") } if getChangeResp.ChangeInfo.Status != nil && *getChangeResp.ChangeInfo.Status == validStateForHostedZone { r.hostedZone = resp.HostedZone hostedZoneLogger.Debug("create hosted finished successfully") return nil } } } }
// startIntervalerIfNeeded starts the given rsync interval, logs any errors, and adds the // resulting Intervaler to the Mount struct for later Stoppage. func startIntervalerIfNeeded(log logging.Logger, remoteMachine *machine.Machine, c *rsync.Client, opts rsync.SyncIntervalOpts) { log = log.New("startIntervalerIfNeeded") if opts.Interval <= 0 { // Using debug, because this is not an error - just informative. log.Debug( "startIntervalerIfNeeded() called with interval:%d. Cannot start Intervaler", opts.Interval, ) return } log.Info("Creating and starting RSync SyncInterval") intervaler, err := c.SyncInterval(opts) if err != nil { log.Error("rsync SyncInterval returned an error:%s", err) return } remoteMachine.Intervaler = intervaler }
// NewSSHCommand is the required initializer for SSHCommand. func NewSSHCommand(log logging.Logger, opts SSHCommandOpts) (*SSHCommand, error) { usr, err := user.Current() if err != nil { return nil, err } klientKite, err := klient.CreateKlientWithDefaultOpts() if err != nil { return nil, err } if err := klientKite.Dial(); err != nil { log.New("NewSSHCommand").Error("Dialing local klient failed. err:%s", err) return nil, ErrLocalDialingFailed } k := klient.NewKlient(klientKite) return &SSHCommand{ Klient: k, Log: log.New("SSHCommand"), Ask: opts.Ask, Debug: opts.Debug, SSHKey: &SSHKey{ Log: log.New("SSHKey"), Debug: opts.Debug, RemoteUsername: opts.RemoteUsername, KeyPath: path.Join(usr.HomeDir, config.SSHDefaultKeyDir), KeyName: config.SSHDefaultKeyName, Klient: k, }, }, nil }
// MachineSSHCommand allows to SSH into remote machine. func MachineSSHCommand(c *cli.Context, log logging.Logger, _ string) (int, error) { // SSH command must have only one identifier. idents, err := getIdentifiers(c) if err != nil { return 1, err } if err := identifiersLimit(idents, 1, 1); err != nil { return 1, err } opts := &machine.SSHOptions{ Identifier: idents[0], Username: c.String("username"), Log: log.New("machine:ssh"), } if err := machine.SSH(opts); err != nil { return 1, err } return 0, nil }
// StartCommand starts local klient. Requires sudo. func StartCommand(c *cli.Context, log logging.Logger, _ string) int { if len(c.Args()) != 0 { cli.ShowCommandHelp(c, "start") return 1 } log = log.New("cmd:start") s, err := newService(nil) if err != nil { log.Error("Error creating Service. err:%s", err) fmt.Println(GenericInternalNewCodeError) return 1 } // No UX message needed, startKlient will do that itself. if err := startKlient(log, s); err != nil { log.Error("failed to start klient: %s", err) return 1 } fmt.Printf("Successfully started %s\n", config.KlientName) return 0 }
// MachineLogger returns a new logger with the context of the given MachineMeta func MachineLogger(meta MachineMeta, l logging.Logger) logging.Logger { return l.New("machine").New( "name", meta.Name, "ip", meta.IP, ) }
func MountLogger(m *Mount, l logging.Logger) logging.Logger { return l.New("mount").New( "name", m.MountName, "path", m.LocalPath, ) }
func NewMachines(log logging.Logger, s storage.Interface) *Machines { return &Machines{ Log: log.New("Machines"), storage: s, } }