func main() {
	optRegion := flag.String("region", "", "AWS Region")
	optInstanceID := flag.String("instance-id", "", "Instance ID")
	optAccessKeyID := flag.String("access-key-id", "", "AWS Access Key ID")
	optSecretAccessKey := flag.String("secret-access-key", "", "AWS Secret Access Key")
	optTempfile := flag.String("tempfile", "", "Temp file name")
	flag.Parse()

	var cpucredit CPUCreditPlugin

	if *optRegion == "" || *optInstanceID == "" {
		cpucredit.Region = aws.InstanceRegion()
		cpucredit.InstanceID = aws.InstanceId()
	} else {
		cpucredit.Region = *optRegion
		cpucredit.InstanceID = *optInstanceID
	}

	cpucredit.AccessKeyID = *optAccessKeyID
	cpucredit.SecretAccessKey = *optSecretAccessKey

	helper := mp.NewMackerelPlugin(cpucredit)
	if *optTempfile != "" {
		helper.Tempfile = *optTempfile
	} else {
		helper.Tempfile = "/tmp/mackerel-plugin-cpucredit"
	}

	if os.Getenv("MACKEREL_AGENT_PLUGIN_META") != "" {
		helper.OutputDefinitions()
	} else {
		helper.OutputValues()
	}
}
func main() {
	var inst_id string

	if instanceID == "" {
		inst_id := aws.InstanceId()
		if inst_id == "unknown" {
			log.Fatalln("Unable to get instance id")
		}
	} else {
		inst_id = instanceID
	}

	auth, err := aws.GetAuth(accesskey, secretkey, "", time.Time{})
	if err != nil {
		log.Fatalln("Unable to get AWS auth", err)
	}

	awsec2 = ec2.New(auth, aws.GetRegion(region))

	groupMap := getSecurityGroupIds(inst_id)
	for _, id := range securityGroupIDs {
		groupMap[id] = true
	}
	groupIds := make([]string, 0, len(groupMap))
	for id := range groupMap {
		groupIds = append(groupIds, id)
	}

	opts := &ec2.ModifyInstanceAttributeOptions{SecurityGroups: ec2.SecurityGroupIds(groupIds...)}
	resp, err := awsec2.ModifyInstanceAttribute(inst_id, opts)
	if err != nil || !resp.Return {
		log.Fatalln("Error adding security groups to instance", err)
	}

	log.Printf("Added security groups %s to instance %s\n", securityGroupIDs.String(), inst_id)

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)

	// this waits until we get a kill signal
	<-c

	groupMap = getSecurityGroupIds(inst_id)
	for _, id := range securityGroupIDs {
		delete(groupMap, id)
	}
	groupIds = make([]string, 0, len(groupMap))
	for id := range groupMap {
		groupIds = append(groupIds, id)
	}

	opts = &ec2.ModifyInstanceAttributeOptions{SecurityGroups: ec2.SecurityGroupIds(groupIds...)}
	resp, err = awsec2.ModifyInstanceAttribute(inst_id, opts)
	if err != nil || !resp.Return {
		log.Fatalln("Error removing security groups from instance", err)
	}

	log.Printf("Removed security groups %s from instance %s\n", securityGroupIDs.String(), inst_id)
}
Beispiel #3
0
func Main() error {
	log = os.Stderr
	if !*verbose {
		log = ioutil.Discard
	}

	if *mountPoint == "" {
		*mountPoint = "/ebs/" + *volumeID
	}

	instanceID = oldaws.InstanceId()
	if instanceID == "unknown" {
		return fmt.Errorf("cannot determine AWS instance ID. not running in EC2?")
	}
	region := oldaws.InstanceRegion()
	ec2Conn := ec2.New(&aws.Config{Region: region})

	if *unmountOnly {
		err1 := Unmount()
		err2 := Detach(ec2Conn)
		if err1 != nil {
			return err1
		}
		return err2
	}

	var err error

	linuxDeviceName := ""
	awsDeviceName := ""
	for i := 'a'; true; i++ {
		awsDeviceName = fmt.Sprintf("/dev/sd%c", i)
		linuxDeviceName = fmt.Sprintf("/dev/xvd%c", i)
		_, err = os.Stat(linuxDeviceName)
		if err != nil && os.IsNotExist(err) {
			fmt.Fprintf(log, "found device %s\n", linuxDeviceName)
			break
		}
		if err != nil {
			fmt.Fprintf(log, "%s: %s\n", linuxDeviceName, err)
		}
		if i == 'z' {
			return fmt.Errorf("Cannot locate an available device to mount")
		}
	}

	fmt.Fprintf(log, "attaching %s to %s\n", *volumeID, awsDeviceName)
	_, err = ec2Conn.AttachVolume(&ec2.AttachVolumeInput{
		Device:     &awsDeviceName,
		InstanceID: &instanceID,
		VolumeID:   volumeID,
	})
	if err != nil {
		return fmt.Errorf("failed to attach %s at %s: %s",
			*volumeID, awsDeviceName, err)
	}
	defer func() {
		fmt.Fprintf(log, "detaching %s from %s\n", *volumeID, awsDeviceName)
		if !*mountOnly || err != nil {
			if cleanupErr := Detach(ec2Conn); cleanupErr != nil {
				fmt.Fprintf(os.Stderr, "failed to detach %s: %s\n", *volumeID, cleanupErr)
			}
		}
	}()

	// Wait for the volume to attach
	for i := time.Duration(0); i < *attachTimeout; i += time.Second {
		_, err = os.Stat(linuxDeviceName)
		if err == nil {
			break
		}
		if !os.IsNotExist(err) {
			break
		}
		time.Sleep(time.Second)
	}
	if err != nil {
		return fmt.Errorf("failed to attach %s: %s\n", linuxDeviceName, err)
	}

	// Use blkid to tell if we need to create a filesystem
	_, err = exec.Command("blkid", linuxDeviceName).Output()
	if err != nil && err.Error() == "exit status 2" {
		// blkid told us we have no filesystem, so create one
		fmt.Fprintf(log, "Creating filesystem on %s\n", *volumeID)
		err = exec.Command(fmt.Sprintf("mkfs.%s", *fsType), linuxDeviceName).Run()
		if err != nil {
			return err
		}
	}

	// Mount the file system
	fmt.Fprintf(log, "mounting %s on %s\n", linuxDeviceName, *mountPoint)
	os.MkdirAll(*mountPoint, 0777)
	err = exec.Command("mount", linuxDeviceName, *mountPoint).Run()
	if err != nil {
		return fmt.Errorf("cannot mount %s: %s", *volumeID, err)
	}
	defer func() {
		if !*mountOnly || err != nil {
			fmt.Fprintf(log, "unmounting %s from %s\n", linuxDeviceName, *mountPoint)
			if cleanupErr := Unmount(); cleanupErr != nil {
				fmt.Fprintf(os.Stderr, "failed to unmount %s: %s\n", *volumeID, cleanupErr)
			}
		}
	}()

	if *mountOnly {
		return nil
	}

	// Invoke the command
	fmt.Fprintf(log, "invoking %s %#v\n", flag.Arg(0), flag.Args()[1:])
	cmd := exec.Command(flag.Arg(0), flag.Args()[1:]...)
	cmd.Stdin = os.Stdin
	cmd.Stdout = os.Stdout
	cmd.Stderr = os.Stderr

	// Catch shutdown signals and make sure we cleanup
	signalCh := make(chan os.Signal, 1)
	signal.Notify(signalCh, os.Interrupt, os.Kill)

	// Run the command. When finished, close the signalCh to wake up the main
	// "thread".
	var cmdErr error
	go func() {
		cmdErr = cmd.Run()
		close(signalCh)
	}()

	// Wait for the command to stop or a signal to arrive
	_ = <-signalCh

	return cmdErr
}
Beispiel #4
0
func main() {
	var inst_id string

	if instanceID == "" {
		inst_id := aws.InstanceId()
		if inst_id == "unknown" {
			log.Fatalln("Unable to get instance id")
		}
	} else {
		inst_id = instanceID
	}

	auth, err := aws.GetAuth(accesskey, secretkey, "", time.Time{})
	if err != nil {
		log.Fatalln("Unable to get AWS auth", err)
	}

	if securityGroupID != "" {
		awsec2 = ec2.New(auth, aws.GetRegion(region))

		groupMap := getSecurityGroupIds(inst_id)
		groupMap[securityGroupID] = true
		groupIds := make([]string, 0, len(groupMap))
		for id := range groupMap {
			groupIds = append(groupIds, id)
		}

		opts := &ec2.ModifyInstanceAttributeOptions{SecurityGroups: ec2.SecurityGroupIds(groupIds...)}
		resp, err := awsec2.ModifyInstanceAttribute(inst_id, opts)
		if err != nil || !resp.Return {
			log.Fatalln("Error adding security group to instance", err)
		}

		log.Printf("Added security group %s to instance %s\n", securityGroupID, inst_id)
	}

	awselb := elb.New(auth, aws.GetRegion(region))
	for _, lbname := range lbnames {
		_, err = awselb.RegisterInstancesWithLoadBalancer([]string{inst_id}, lbname)
		if err != nil {
			log.Fatalln("Error registering instance", err)
		}

		log.Printf("Registered instance %s with elb %s\n", inst_id, lbname)
	}

	c := make(chan os.Signal, 1)
	signal.Notify(c, syscall.SIGTERM, syscall.SIGINT, syscall.SIGKILL)

	// this waits until we get a kill signal
	<-c

	for _, lbname := range lbnames {
		_, err = awselb.DeregisterInstancesFromLoadBalancer([]string{inst_id}, lbname)
		if err != nil {
			log.Fatalln("Error deregistering instance", err)
		}

		log.Printf("Deregistered instance %s with elb %s\n", inst_id, lbname)
	}

	if securityGroupID != "" {
		groupMap := getSecurityGroupIds(inst_id)
		delete(groupMap, securityGroupID)
		groupIds := make([]string, 0, len(groupMap))
		for id := range groupMap {
			groupIds = append(groupIds, id)
		}

		opts := &ec2.ModifyInstanceAttributeOptions{SecurityGroups: ec2.SecurityGroupIds(groupIds...)}
		resp, err := awsec2.ModifyInstanceAttribute(inst_id, opts)
		if err != nil || !resp.Return {
			log.Fatalln("Error removing security group from instance", err)
		}

		log.Printf("Removed security group %s from instance %s\n", securityGroupID, inst_id)
	}
}
Beispiel #5
0
func main() {
	flag.Parse()

	dockerClient, err := docker.NewClient(*dockerEndpoint)
	if err != nil {
		fmt.Printf("cannot connect to docker: %s\n", err)
		os.Exit(1)
	}

	// Wait for the container to start
	// TODO(ross): this could be done with the events interface perhaps?
	for {
		_, err := dockerClient.InspectContainer(*containerID)
		if err == nil {
			break
		}
		if _, ok := err.(*docker.NoSuchContainer); ok {
			time.Sleep(time.Second)
			continue
		}
		fmt.Printf("docker: %s: %s\n", *containerID, err)
		os.Exit(1)
	}

	instanceID := aws.InstanceId()
	if instanceID == "unknown" {
		fmt.Printf("cannot determine AWS instance ID. not running in EC2?\n")
		os.Exit(1)
	}

	awsAuth, err := aws.GetAuth("", "", "", time.Time{})
	if err != nil {
		fmt.Printf("cannot get AWS auth: %s\n", err)
		os.Exit(1)
	}

	elbConn := elb.New(awsAuth, aws.GetRegion(aws.InstanceRegion()))
	_, err = elbConn.RegisterInstancesWithLoadBalancer(
		[]string{instanceID},
		*loadBalancerName)
	if err != nil {
		fmt.Printf("cannot register instance: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("registered instance %s from ELB %s\n", instanceID,
		*loadBalancerName)

	// Wait for the container to exit
	_, err = dockerClient.WaitContainer(*containerID)
	if err != nil {
		fmt.Printf("docker: %s: waiting: %s\n", *containerID, err)
	} else {
		fmt.Printf("docker: %s exited\n", *containerID)
	}

	_, err = elbConn.DeregisterInstancesFromLoadBalancer(
		[]string{instanceID}, *loadBalancerName)
	if err != nil {
		fmt.Printf("cannot unregister instance: %s\n", err)
		os.Exit(1)
	}
	fmt.Printf("unregisterd instance %s from ELB %s\n",
		instanceID, *loadBalancerName)
}